blob: c523407f201a41f54b1120e4f1a926dbe9f05738 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Romain Guyf8b4ca52017-03-16 18:39:20 +000048#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070073#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080075#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800121bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800122int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600123bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700126 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700128 mTransactionPending(false),
129 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700130 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700131 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700132 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800133 mHwc(nullptr),
134 mRealHwc(nullptr),
135 mVrHwc(nullptr),
136 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800152 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000153 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700154 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700155 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700160 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800161 mNumLayers(0),
162 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
Steven Thomas050b2c82017-03-06 11:45:16 -0800187 // Vr flinger is only enabled on Daydream ready devices.
188 useVrFlinger = getBool< ISurfaceFlingerConfigs,
189 &ISurfaceFlingerConfigs::useVrFlinger>(false);
190
Fabien Sanglard1971b632017-03-10 14:50:03 -0800191 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
192 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
193
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600194 hasWideColorDisplay =
195 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 // debugging stuff...
198 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopianb4b17302013-03-20 18:36:41 -0700200 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700201 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 property_get("debug.sf.showupdates", value, "0");
204 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 property_get("debug.sf.ddms", value, "0");
207 mDebugDDMS = atoi(value);
208 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700209 if (!startDdmConnection()) {
210 // start failed, and DDMS debugging not enabled
211 mDebugDDMS = 0;
212 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700213 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700214 ALOGI_IF(mDebugRegion, "showupdates enabled");
215 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700216
217 property_get("debug.sf.disable_backpressure", value, "0");
218 mPropagateBackpressure = !atoi(value);
219 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700220
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800221 property_get("debug.sf.enable_hwc_vds", value, "0");
222 mUseHwcVirtualDisplays = atoi(value);
223 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800224
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800225 property_get("ro.sf.disable_triple_buffer", value, "1");
226 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228}
229
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230void SurfaceFlinger::onFirstRef()
231{
232 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233}
234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235SurfaceFlinger::~SurfaceFlinger()
236{
Mathias Agopiana4912602012-07-12 14:25:33 -0700237 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
238 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
239 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240}
241
Dan Stozac7014012014-02-14 15:03:43 -0800242void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243{
244 // the window manager died on us. prepare its eulogy.
245
Andy McFadden13a082e2012-08-24 10:16:42 -0700246 // restore initial conditions (default device unblank, etc)
247 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248
249 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700250 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251}
252
Robert Carr1db73f62016-12-21 12:58:51 -0800253static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700254 status_t err = client->initCheck();
255 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return nullptr;
259}
260
261sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
262 return initClient(new Client(this));
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
266 const sp<IGraphicBufferProducer>& gbp) {
267 if (authenticateSurfaceTexture(gbp) == false) {
268 return nullptr;
269 }
270 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
271 if (layer == nullptr) {
272 return nullptr;
273 }
274
275 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700278sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
279 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280{
281 class DisplayToken : public BBinder {
282 sp<SurfaceFlinger> flinger;
283 virtual ~DisplayToken() {
284 // no more references, this display must be terminated
285 Mutex::Autolock _l(flinger->mStateLock);
286 flinger->mCurrentState.displays.removeItem(this);
287 flinger->setTransactionFlags(eDisplayTransactionNeeded);
288 }
289 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700290 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 : flinger(flinger) {
292 }
293 };
294
295 sp<BBinder> token = new DisplayToken(this);
296
297 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700298 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700299 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 return token;
303}
304
Jesse Hall6c913be2013-08-08 12:15:49 -0700305void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
306 Mutex::Autolock _l(mStateLock);
307
308 ssize_t idx = mCurrentState.displays.indexOfKey(display);
309 if (idx < 0) {
310 ALOGW("destroyDisplay: invalid display token");
311 return;
312 }
313
314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
315 if (!info.isVirtualDisplay()) {
316 ALOGE("destroyDisplay called for non-virtual display");
317 return;
318 }
Irvelffc9efc2016-07-27 15:16:37 -0700319 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700320 mCurrentState.displays.removeItemsAt(idx);
321 setTransactionFlags(eDisplayTransactionNeeded);
322}
323
Jesse Hall692c7232012-11-08 15:41:56 -0800324void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800325 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 ALOGW_IF(mBuiltinDisplays[type],
327 "Overwriting display token for display type %d", type);
328 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800329 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700330 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700332 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800333}
334
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700336 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
338 return NULL;
339 }
Jesse Hall692c7232012-11-08 15:41:56 -0800340 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341}
342
Romain Guyf8b4ca52017-03-16 18:39:20 +0000343sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
344{
345 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
346 return gba;
347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangb254fa32017-01-31 17:43:23 -0800351 if (mStartBootAnimThread->join() != NO_ERROR) {
352 ALOGE("Join StartBootAnimThread failed!");
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
Steven Thomas050b2c82017-03-06 11:45:16 -0800366 if (mVrFlinger) {
367 mVrFlinger->OnBootFinished();
368 }
369
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700370 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700371 // formerly we would just kill the process, but we now ask it to exit so it
372 // can choose where to stop the animation.
373 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700374
375 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
376 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
377 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian3f844832013-08-07 21:24:32 -0700380void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 RenderEngine& engine;
383 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
386 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 }
388 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 return true;
391 }
392 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394}
395
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396class DispSyncSource : public VSyncSource, private DispSync::Callback {
397public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700398 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 const char* name) :
400 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700401 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700402 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
404 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 mDispSync(dispSync),
406 mCallbackMutex(),
407 mCallback(),
408 mVsyncMutex(),
409 mPhaseOffset(phaseOffset),
410 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 virtual ~DispSyncSource() {}
413
414 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 } else {
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mCallback = callback;
439 }
440
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 virtual void setPhaseOffset(nsecs_t phaseOffset) {
442 Mutex::Autolock lock(mVsyncMutex);
443
444 // Normalize phaseOffset to [0, period)
445 auto period = mDispSync->getPeriod();
446 phaseOffset %= period;
447 if (phaseOffset < 0) {
448 // If we're here, then phaseOffset is in (-period, 0). After this
449 // operation, it will be in (0, period)
450 phaseOffset += period;
451 }
452 mPhaseOffset = phaseOffset;
453
454 // If we're not enabled, we don't need to mess with the listeners
455 if (!mEnabled) {
456 return;
457 }
458
459 // Remove the listener with the old offset
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466
467 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error registering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474 }
475
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476private:
477 virtual void onDispSyncEvent(nsecs_t when) {
478 sp<VSyncSource::Callback> callback;
479 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 callback = mCallback;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 if (mTraceVsync) {
484 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488
489 if (callback != NULL) {
490 callback->onVSyncEvent(when);
491 }
492 }
493
Tim Murray4a4e4a22016-04-19 16:29:23 +0000494 const char* const mName;
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 int mValue;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 const String8 mVsyncOnLabel;
500 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mVsyncMutex; // Protects the following
508 nsecs_t mPhaseOffset;
509 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510};
511
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700512class InjectVSyncSource : public VSyncSource {
513public:
514 InjectVSyncSource() {}
515
516 virtual ~InjectVSyncSource() {}
517
518 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback = callback;
521 }
522
523 virtual void onInjectSyncEvent(nsecs_t when) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback->onVSyncEvent(when);
526 }
527
528 virtual void setVSyncEnabled(bool) {}
529 virtual void setPhaseOffset(nsecs_t) {}
530
531private:
532 std::mutex mCallbackMutex; // Protects the following
533 sp<VSyncSource::Callback> mCallback;
534};
535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700537 ALOGI( "SurfaceFlinger's main thread ready to run. "
538 "Initializing graphics H/W...");
539
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900540 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
541
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 { // Autolock scope
543 Mutex::Autolock _l(mStateLock);
544
545 // initialize EGL for the default display
546 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
547 eglInitialize(mEGLDisplay, NULL, NULL);
548
549 // start the EventThread
550 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700552 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700555 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 mEventQueue.setEventThread(mSFEventThread);
557
Tim Murrayacff43d2016-07-29 13:57:24 -0700558 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700559 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700560 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700561 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
563 }
564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
567 HAL_PIXEL_FORMAT_RGBA_8888);
568 }
569
570 // Drop the state lock while we initialize the hardware composer. We drop
571 // the lock because on creation, it will call back into SurfaceFlinger to
572 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
574 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800575 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800576 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
578
Jesse Hall692c7232012-11-08 15:41:56 -0800579 Mutex::Autolock _l(mStateLock);
580
Steven Thomas050b2c82017-03-06 11:45:16 -0800581 if (useVrFlinger) {
582 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
583 mVrFlingerRequestsDisplay = requestDisplay;
584 signalTransaction();
585 };
586 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
587 vrFlingerRequestDisplayCallback);
588 if (!mVrFlinger) {
589 ALOGE("Failed to start vrflinger");
590 }
591 }
592
Mathias Agopian875d8e12013-06-07 15:35:48 -0700593 // retrieve the EGL context that was selected/created
594 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700595
Mathias Agopianda27af92012-09-13 18:17:13 -0700596 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
597 "couldn't create EGLContext");
598
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599 // make the GLContext current so that we can create textures when creating
600 // Layers (which may happens before we render something)
Polina Bondarenko80c02322017-04-10 10:15:42 +0000601 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700602
Jamie Gennisd1700752013-10-14 12:22:52 -0700603 mEventControlThread = new EventControlThread(this);
604 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
605
Mathias Agopian92a979a2012-08-02 18:32:23 -0700606 // initialize our drawing state
607 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700608
Andy McFadden13a082e2012-08-24 10:16:42 -0700609 // set initial conditions (e.g. unblank default device)
610 initializeDisplays();
611
Dan Stoza4e637772016-07-28 13:31:51 -0700612 mRenderEngine->primeCache();
613
Wei Wangb254fa32017-01-31 17:43:23 -0800614 mStartBootAnimThread = new StartBootAnimThread();
615 if (mStartBootAnimThread->Start() != NO_ERROR) {
616 ALOGE("Run StartBootAnimThread failed!");
617 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800618
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700620}
621
Mathias Agopiana67e4182012-06-19 17:26:12 -0700622void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800623 // Start boot animation service by setting a property mailbox
624 // if property setting thread is already running, Start() will be just a NOP
625 mStartBootAnimThread->Start();
626 // Wait until property was set
627 if (mStartBootAnimThread->join() != NO_ERROR) {
628 ALOGE("Join StartBootAnimThread failed!");
629 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700630}
631
Mathias Agopian875d8e12013-06-07 15:35:48 -0700632size_t SurfaceFlinger::getMaxTextureSize() const {
633 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700634}
635
Mathias Agopian875d8e12013-06-07 15:35:48 -0700636size_t SurfaceFlinger::getMaxViewportDims() const {
637 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700638}
639
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800641
Jamie Gennis582270d2011-08-17 18:19:00 -0700642bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800643 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800644 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800645 return authenticateSurfaceTextureLocked(bufferProducer);
646}
647
648bool SurfaceFlinger::authenticateSurfaceTextureLocked(
649 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800650 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700651 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800652}
653
Brian Anderson6b376712017-04-04 10:51:39 -0700654status_t SurfaceFlinger::getSupportedFrameTimestamps(
655 std::vector<FrameEvent>* outSupported) const {
656 *outSupported = {
657 FrameEvent::REQUESTED_PRESENT,
658 FrameEvent::ACQUIRE,
659 FrameEvent::LATCH,
660 FrameEvent::FIRST_REFRESH_START,
661 FrameEvent::LAST_REFRESH_START,
662 FrameEvent::GPU_COMPOSITION_DONE,
663 FrameEvent::DEQUEUE_READY,
664 FrameEvent::RELEASE,
665 };
666 if (!getHwComposer().hasCapability(
667 HWC2::Capability::PresentFenceIsNotReliable)) {
668 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
669 }
670 return NO_ERROR;
671}
672
Dan Stoza7f7da322014-05-02 15:26:25 -0700673status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
674 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700675 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700676 return BAD_VALUE;
677 }
678
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500679 if (!display.get())
680 return NAME_NOT_FOUND;
681
Jesse Hall692c7232012-11-08 15:41:56 -0800682 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700683 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800684 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700685 type = i;
686 break;
687 }
688 }
689
690 if (type < 0) {
691 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700692 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700693
Mathias Agopian8b736f12012-08-13 17:54:26 -0700694 // TODO: Not sure if display density should handled by SF any longer
695 class Density {
696 static int getDensityFromProperty(char const* propName) {
697 char property[PROPERTY_VALUE_MAX];
698 int density = 0;
699 if (property_get(propName, property, NULL) > 0) {
700 density = atoi(property);
701 }
702 return density;
703 }
704 public:
705 static int getEmuDensity() {
706 return getDensityFromProperty("qemu.sf.lcd_density"); }
707 static int getBuildDensity() {
708 return getDensityFromProperty("ro.sf.lcd_density"); }
709 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700710
Dan Stoza7f7da322014-05-02 15:26:25 -0700711 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700712
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700714 DisplayInfo info = DisplayInfo();
715
Dan Stoza9e56aa02015-11-02 13:00:03 -0800716 float xdpi = hwConfig->getDpiX();
717 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700718
719 if (type == DisplayDevice::DISPLAY_PRIMARY) {
720 // The density of the device is provided by a build property
721 float density = Density::getBuildDensity() / 160.0f;
722 if (density == 0) {
723 // the build doesn't provide a density -- this is wrong!
724 // use xdpi instead
725 ALOGE("ro.sf.lcd_density must be defined as a build property");
726 density = xdpi / 160.0f;
727 }
728 if (Density::getEmuDensity()) {
729 // if "qemu.sf.lcd_density" is specified, it overrides everything
730 xdpi = ydpi = density = Density::getEmuDensity();
731 density /= 160.0f;
732 }
733 info.density = density;
734
735 // TODO: this needs to go away (currently needed only by webkit)
Polina Bondarenko80c02322017-04-10 10:15:42 +0000736 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
737 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 } else {
739 // TODO: where should this value come from?
740 static const int TV_DENSITY = 213;
741 info.density = TV_DENSITY / 160.0f;
742 info.orientation = 0;
743 }
744
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 info.w = hwConfig->getWidth();
746 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700747 info.xdpi = xdpi;
748 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900750 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751
Andy McFadden91b2ca82014-06-13 14:04:23 -0700752 // This is how far in advance a buffer must be queued for
753 // presentation at a given time. If you want a buffer to appear
754 // on the screen at time N, you must submit the buffer before
755 // (N - presentationDeadline).
756 //
757 // Normally it's one full refresh period (to give SF a chance to
758 // latch the buffer), but this can be reduced by configuring a
759 // DispSync offset. Any additional delays introduced by the hardware
760 // composer or panel must be accounted for here.
761 //
762 // We add an additional 1ms to allow for processing time and
763 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800764 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800765 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700766
767 // All non-virtual displays are currently considered secure.
768 info.secure = true;
769
Michael Wright28f24d02016-07-12 13:30:53 -0700770 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771 }
772
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 return NO_ERROR;
774}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700775
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800776status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700777 DisplayStatInfo* stats) {
778 if (stats == NULL) {
779 return BAD_VALUE;
780 }
781
782 // FIXME for now we always return stats for the primary display
783 memset(stats, 0, sizeof(*stats));
784 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
785 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
786 return NO_ERROR;
787}
788
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700789int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800790 if (display == NULL) {
791 ALOGE("%s : display is NULL", __func__);
792 return BAD_VALUE;
793 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700794 sp<DisplayDevice> device(getDisplayDevice(display));
795 if (device != NULL) {
796 return device->getActiveConfig();
797 }
798 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700799}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700800
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700801void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
802 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
803 this);
804 int32_t type = hw->getDisplayType();
805 int currentMode = hw->getActiveConfig();
806
807 if (mode == currentMode) {
808 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
809 return;
810 }
811
812 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
813 ALOGW("Trying to set config for virtual display");
814 return;
815 }
816
817 hw->setActiveConfig(mode);
818 getHwComposer().setActiveConfig(type, mode);
819}
820
821status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
822 class MessageSetActiveConfig: public MessageBase {
823 SurfaceFlinger& mFlinger;
824 sp<IBinder> mDisplay;
825 int mMode;
826 public:
827 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
828 int mode) :
829 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
830 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700831 Vector<DisplayInfo> configs;
832 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700833 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700834 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700835 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700836 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700837 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700838 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
839 if (hw == NULL) {
840 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700841 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700842 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
843 ALOGW("Attempt to set active config = %d for virtual display",
844 mMode);
845 } else {
846 mFlinger.setActiveConfigInternal(hw, mMode);
847 }
848 return true;
849 }
850 };
851 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
852 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700853 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700854}
Michael Wright28f24d02016-07-12 13:30:53 -0700855status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
856 Vector<android_color_mode_t>* outColorModes) {
857 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
858 return BAD_VALUE;
859 }
860
861 if (!display.get()) {
862 return NAME_NOT_FOUND;
863 }
864
865 int32_t type = NAME_NOT_FOUND;
866 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
867 if (display == mBuiltinDisplays[i]) {
868 type = i;
869 break;
870 }
871 }
872
873 if (type < 0) {
874 return type;
875 }
876
877 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
878 outColorModes->clear();
879 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
880
881 return NO_ERROR;
882}
883
884android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
885 sp<DisplayDevice> device(getDisplayDevice(display));
886 if (device != nullptr) {
887 return device->getActiveColorMode();
888 }
889 return static_cast<android_color_mode_t>(BAD_VALUE);
890}
891
892void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
893 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700894 int32_t type = hw->getDisplayType();
895 android_color_mode_t currentMode = hw->getActiveColorMode();
896
897 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700898 return;
899 }
900
901 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
902 ALOGW("Trying to set config for virtual display");
903 return;
904 }
905
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600906 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
907 hw->getDisplayType());
908
Michael Wright28f24d02016-07-12 13:30:53 -0700909 hw->setActiveColorMode(mode);
910 getHwComposer().setActiveColorMode(type, mode);
911}
912
913
914status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
915 android_color_mode_t colorMode) {
916 class MessageSetActiveColorMode: public MessageBase {
917 SurfaceFlinger& mFlinger;
918 sp<IBinder> mDisplay;
919 android_color_mode_t mMode;
920 public:
921 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
922 android_color_mode_t mode) :
923 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
924 virtual bool handler() {
925 Vector<android_color_mode_t> modes;
926 mFlinger.getDisplayColorModes(mDisplay, &modes);
927 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
928 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600929 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
930 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700931 return true;
932 }
933 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
934 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600935 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
936 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700937 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600938 ALOGW("Attempt to set active color mode %s %d for virtual display",
939 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700940 } else {
941 mFlinger.setActiveColorModeInternal(hw, mMode);
942 }
943 return true;
944 }
945 };
946 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
947 postMessageSync(msg);
948 return NO_ERROR;
949}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700950
Svetoslavd85084b2014-03-20 10:28:31 -0700951status_t SurfaceFlinger::clearAnimationFrameStats() {
952 Mutex::Autolock _l(mStateLock);
953 mAnimFrameTracker.clearStats();
954 return NO_ERROR;
955}
956
957status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
958 Mutex::Autolock _l(mStateLock);
959 mAnimFrameTracker.getStats(outStats);
960 return NO_ERROR;
961}
962
Dan Stozac4f471e2016-03-24 09:31:08 -0700963status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
964 HdrCapabilities* outCapabilities) const {
965 Mutex::Autolock _l(mStateLock);
966
967 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
968 if (displayDevice == nullptr) {
969 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
970 return BAD_VALUE;
971 }
972
973 std::unique_ptr<HdrCapabilities> capabilities =
974 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
975 if (capabilities) {
976 std::swap(*outCapabilities, *capabilities);
977 } else {
978 return BAD_VALUE;
979 }
980
981 return NO_ERROR;
982}
983
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700984status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
985 if (enable == mInjectVSyncs) {
986 return NO_ERROR;
987 }
988
989 if (enable) {
990 mInjectVSyncs = enable;
991 ALOGV("VSync Injections enabled");
992 if (mVSyncInjector.get() == nullptr) {
993 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700994 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700995 }
996 mEventQueue.setEventThread(mInjectorEventThread);
997 } else {
998 mInjectVSyncs = enable;
999 ALOGV("VSync Injections disabled");
1000 mEventQueue.setEventThread(mSFEventThread);
1001 mVSyncInjector.clear();
1002 }
1003 return NO_ERROR;
1004}
1005
1006status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1007 if (!mInjectVSyncs) {
1008 ALOGE("VSync Injections not enabled");
1009 return BAD_VALUE;
1010 }
1011 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1012 ALOGV("Injecting VSync inside SurfaceFlinger");
1013 mVSyncInjector->onInjectSyncEvent(when);
1014 }
1015 return NO_ERROR;
1016}
1017
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001018// ----------------------------------------------------------------------------
1019
1020sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001021 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001022}
1023
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001025
1026void SurfaceFlinger::waitForEvent() {
1027 mEventQueue.waitMessage();
1028}
1029
1030void SurfaceFlinger::signalTransaction() {
1031 mEventQueue.invalidate();
1032}
1033
1034void SurfaceFlinger::signalLayerUpdate() {
1035 mEventQueue.invalidate();
1036}
1037
1038void SurfaceFlinger::signalRefresh() {
1039 mEventQueue.refresh();
1040}
1041
1042status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001043 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001044 return mEventQueue.postMessage(msg, reltime);
1045}
1046
1047status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001048 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001049 status_t res = mEventQueue.postMessage(msg, reltime);
1050 if (res == NO_ERROR) {
1051 msg->wait();
1052 }
1053 return res;
1054}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001055
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001056void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001057 do {
1058 waitForEvent();
1059 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001060}
1061
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001062void SurfaceFlinger::enableHardwareVsync() {
1063 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001064 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001066 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1067 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001068 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001069 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070}
1071
Jesse Hall948fe0c2013-10-14 12:56:09 -07001072void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073 Mutex::Autolock _l(mHWVsyncLock);
1074
Jesse Hall948fe0c2013-10-14 12:56:09 -07001075 if (makeAvailable) {
1076 mHWVsyncAvailable = true;
1077 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001078 // Hardware vsync is not currently available, so abort the resync
1079 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001080 return;
1081 }
1082
Dan Stoza9e56aa02015-11-02 13:00:03 -08001083 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1084 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001085
1086 mPrimaryDispSync.reset();
1087 mPrimaryDispSync.setPeriod(period);
1088
1089 if (!mPrimaryHWVsyncEnabled) {
1090 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001091 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1092 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093 mPrimaryHWVsyncEnabled = true;
1094 }
1095}
1096
Jesse Hall948fe0c2013-10-14 12:56:09 -07001097void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001098 Mutex::Autolock _l(mHWVsyncLock);
1099 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001100 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1101 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001102 mPrimaryDispSync.endResync();
1103 mPrimaryHWVsyncEnabled = false;
1104 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001105 if (makeUnavailable) {
1106 mHWVsyncAvailable = false;
1107 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108}
1109
Tim Murray4a4e4a22016-04-19 16:29:23 +00001110void SurfaceFlinger::resyncWithRateLimit() {
1111 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1112 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001113 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001114 }
1115}
1116
Steven Thomas3cfac282017-02-06 12:29:30 -08001117void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1118 nsecs_t timestamp) {
1119 Mutex::Autolock lock(mStateLock);
1120 // Ignore any vsyncs from the non-active hardware composer.
1121 if (composer != mHwc) {
1122 return;
1123 }
1124
Jamie Gennisd1700752013-10-14 12:22:52 -07001125 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001126
Jamie Gennisd1700752013-10-14 12:22:52 -07001127 { // Scope for the lock
1128 Mutex::Autolock _l(mHWVsyncLock);
1129 if (type == 0 && mPrimaryHWVsyncEnabled) {
1130 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001131 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001132 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001133
1134 if (needsHwVsync) {
1135 enableHardwareVsync();
1136 } else {
1137 disableHardwareVsync(false);
1138 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001139}
1140
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001141void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001142 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001143 *compositorTiming = mCompositorTiming;
1144}
1145
Polina Bondarenko80c02322017-04-10 10:15:42 +00001146void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001147 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1148 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1149 Mutex::Autolock lock(mStateLock);
Polina Bondarenko80c02322017-04-10 10:15:42 +00001150
1151 // All non-virtual displays are currently considered secure.
1152 bool isSecure = true;
1153
1154 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1155
1156 // When we're using the vr composer, the assumption is that we've
1157 // already created the IBinder object for the primary display.
1158 if (!mHwc->isUsingVrComposer()) {
1159 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1160 }
1161
1162 wp<IBinder> token = mBuiltinDisplays[type];
1163
1164 sp<IGraphicBufferProducer> producer;
1165 sp<IGraphicBufferConsumer> consumer;
1166 BufferQueue::createBufferQueue(&producer, &consumer,
1167 new GraphicBufferAlloc());
1168
1169 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1170 DisplayDevice::DISPLAY_PRIMARY, consumer);
1171
1172 bool hasWideColorModes = false;
1173 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1174 for (android_color_mode_t colorMode : modes) {
1175 switch (colorMode) {
1176 case HAL_COLOR_MODE_DISPLAY_P3:
1177 case HAL_COLOR_MODE_ADOBE_RGB:
1178 case HAL_COLOR_MODE_DCI_P3:
1179 hasWideColorModes = true;
1180 break;
1181 default:
1182 break;
1183 }
1184 }
1185 sp<DisplayDevice> hw =
1186 new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1187 producer, mRenderEngine->getEGLConfig(),
1188 hasWideColorModes && hasWideColorDisplay);
1189 mDisplays.add(token, hw);
1190 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1191 if (hasWideColorModes && hasWideColorDisplay) {
1192 defaultColorMode = HAL_COLOR_MODE_SRGB;
1193 }
1194 setActiveColorModeInternal(hw, defaultColorMode);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001195 } else {
1196 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001197 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001198 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001199 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001200 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001201 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1202 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001203 }
1204 setTransactionFlags(eDisplayTransactionNeeded);
1205
Andy McFadden9e9689c2012-10-10 18:17:51 -07001206 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001207 }
Mathias Agopian86303202012-07-24 22:46:10 -07001208}
1209
Steven Thomas3cfac282017-02-06 12:29:30 -08001210void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1211 Mutex::Autolock lock(mStateLock);
1212 if (composer == mHwc) {
1213 repaintEverything();
1214 } else {
1215 // This isn't from our current hardware composer. If it's a callback
1216 // from the real composer, forward the refresh request to vr
1217 // flinger. Otherwise ignore it.
1218 if (!composer->isUsingVrComposer()) {
1219 mVrFlinger->OnHardwareComposerRefresh();
1220 }
1221 }
1222}
1223
Dan Stoza9e56aa02015-11-02 13:00:03 -08001224void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001226 getHwComposer().setVsyncEnabled(disp,
1227 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001228}
1229
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001230void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1231 for (size_t i = 0; i < layers.size(); ++i) {
1232 layers[i]->clearHwcLayers();
1233 }
1234}
1235
1236void SurfaceFlinger::resetHwc() {
1237 disableHardwareVsync(true);
1238 clearHwcLayers(mDrawingState.layersSortedByZ);
1239 clearHwcLayers(mCurrentState.layersSortedByZ);
1240 // Clear the drawing state so that the logic inside of
1241 // handleTransactionLocked will fire. It will determine the delta between
1242 // mCurrentState and mDrawingState and re-apply all changes when we make the
1243 // transition.
1244 mDrawingState.displays.clear();
1245 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001246 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001247}
1248
Steven Thomas050b2c82017-03-06 11:45:16 -08001249void SurfaceFlinger::updateVrFlinger() {
1250 if (!mVrFlinger)
1251 return;
1252 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1253 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001254 return;
1255 }
Steven Thomas050b2c82017-03-06 11:45:16 -08001256 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001257 // Construct new HWComposer without holding any locks.
1258 mVrHwc = new HWComposer(true);
1259 ALOGV("Vr HWC created");
1260 }
Polina Bondarenko80c02322017-04-10 10:15:42 +00001261 {
1262 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001263
Polina Bondarenko80c02322017-04-10 10:15:42 +00001264 if (vrFlingerRequestsDisplay) {
1265 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001266
Polina Bondarenko80c02322017-04-10 10:15:42 +00001267 mHwc = mVrHwc;
1268 mVrFlinger->GrantDisplayOwnership();
1269 } else {
1270 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001271
Polina Bondarenko80c02322017-04-10 10:15:42 +00001272 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001273
Polina Bondarenko80c02322017-04-10 10:15:42 +00001274 mHwc = mRealHwc;
1275 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001276 }
1277
Polina Bondarenko80c02322017-04-10 10:15:42 +00001278 mVisibleRegionsDirty = true;
1279 invalidateHwcGeometry();
1280 android_atomic_or(1, &mRepaintEverything);
1281 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001282 }
Polina Bondarenko80c02322017-04-10 10:15:42 +00001283 if (mVrHwc) {
1284 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1285 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001286}
1287
Mathias Agopian4fec8732012-06-29 14:12:52 -07001288void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001289 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001290 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001291 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001292 bool frameMissed = !mHadClientComposition &&
1293 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001294 (mPreviousPresentFence->getSignalTime() ==
1295 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001296 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001297 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001298 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001299 signalLayerUpdate();
1300 break;
1301 }
1302
Steven Thomas050b2c82017-03-06 11:45:16 -08001303 // Now that we're going to make it to the handleMessageTransaction()
1304 // call below it's safe to call updateVrFlinger(), which will
1305 // potentially trigger a display handoff.
1306 updateVrFlinger();
1307
Dan Stoza6b9454d2014-11-07 16:00:59 -08001308 bool refreshNeeded = handleMessageTransaction();
1309 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001310 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001311 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001312 // Signal a refresh if a transaction modified the window state,
1313 // a new buffer was latched, or if HWC has requested a full
1314 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001315 signalRefresh();
1316 }
1317 break;
1318 }
1319 case MessageQueue::REFRESH: {
1320 handleMessageRefresh();
1321 break;
1322 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001323 }
1324}
1325
Dan Stoza6b9454d2014-11-07 16:00:59 -08001326bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001327 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001328 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001329 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001330 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001331 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001332 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001333}
1334
Dan Stoza6b9454d2014-11-07 16:00:59 -08001335bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001336 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001337 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001338}
1339
1340void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001341 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001342
Pablo Ceballos40845df2016-01-25 17:41:15 -08001343 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001344
Brian Andersond6927fb2016-07-23 23:37:30 -07001345 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001346 rebuildLayerStacks();
1347 setUpHWComposer();
1348 doDebugFlashRegions();
1349 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001350 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001351
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001352 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001353
1354 mHadClientComposition = false;
1355 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1356 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1357 mHadClientComposition = mHadClientComposition ||
1358 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1359 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001360
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001362}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001363
Mathias Agopiancd60f992012-08-16 16:28:27 -07001364void SurfaceFlinger::doDebugFlashRegions()
1365{
1366 // is debugging enabled
1367 if (CC_LIKELY(!mDebugRegion))
1368 return;
1369
1370 const bool repaintEverything = mRepaintEverything;
1371 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1372 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001373 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001374 // transform the dirty region into this screen's coordinate space
1375 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1376 if (!dirtyRegion.isEmpty()) {
1377 // redraw the whole screen
1378 doComposeSurfaces(hw, Region(hw->bounds()));
1379
1380 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001381 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001382 RenderEngine& engine(getRenderEngine());
1383 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1384
Mathias Agopianda27af92012-09-13 18:17:13 -07001385 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386 }
1387 }
1388 }
1389
1390 postFramebuffer();
1391
1392 if (mDebugRegion > 1) {
1393 usleep(mDebugRegion * 1000);
1394 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001395
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001397 auto& displayDevice = mDisplays[displayId];
1398 if (!displayDevice->isDisplayOn()) {
1399 continue;
1400 }
1401
1402 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001403 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1404 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001405 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001406}
1407
Brian Andersond6927fb2016-07-23 23:37:30 -07001408void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001409{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001410 ATRACE_CALL();
1411 ALOGV("preComposition");
1412
Mathias Agopiancd60f992012-08-16 16:28:27 -07001413 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001414 mDrawingState.traverseInZOrder([&](Layer* layer) {
1415 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001416 needExtraInvalidate = true;
1417 }
Robert Carr2047fae2016-11-28 14:09:09 -08001418 });
1419
Mathias Agopiancd60f992012-08-16 16:28:27 -07001420 if (needExtraInvalidate) {
1421 signalLayerUpdate();
1422 }
1423}
1424
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425void SurfaceFlinger::updateCompositorTiming(
1426 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1427 std::shared_ptr<FenceTime>& presentFenceTime) {
1428 // Update queue of past composite+present times and determine the
1429 // most recently known composite to present latency.
1430 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1431 nsecs_t compositeToPresentLatency = -1;
1432 while (!mCompositePresentTimes.empty()) {
1433 CompositePresentTime& cpt = mCompositePresentTimes.front();
1434 // Cached values should have been updated before calling this method,
1435 // which helps avoid duplicate syscalls.
1436 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1437 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1438 break;
1439 }
1440 compositeToPresentLatency = displayTime - cpt.composite;
1441 mCompositePresentTimes.pop();
1442 }
1443
1444 // Don't let mCompositePresentTimes grow unbounded, just in case.
1445 while (mCompositePresentTimes.size() > 16) {
1446 mCompositePresentTimes.pop();
1447 }
1448
Brian Andersond0010582017-03-07 13:20:31 -08001449 setCompositorTimingSnapped(
1450 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1451}
1452
1453void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1454 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001455 // Integer division and modulo round toward 0 not -inf, so we need to
1456 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001457 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1459 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1460
Brian Andersond0010582017-03-07 13:20:31 -08001461 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1462 if (idealLatency <= 0) {
1463 idealLatency = vsyncInterval;
1464 }
1465
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001466 // Snap the latency to a value that removes scheduling jitter from the
1467 // composition and present times, which often have >1ms of jitter.
1468 // Reducing jitter is important if an app attempts to extrapolate
1469 // something (such as user input) to an accurate diasplay time.
1470 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1471 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001472 nsecs_t bias = vsyncInterval / 2;
1473 int64_t extraVsyncs =
1474 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1475 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1476 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001477
Brian Andersond0010582017-03-07 13:20:31 -08001478 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1480 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001481 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001482}
1483
1484void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001486 ATRACE_CALL();
1487 ALOGV("postComposition");
1488
Brian Anderson3546a3f2016-07-14 11:51:14 -07001489 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001490 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001491 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001492 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001493 }
1494
Polina Bondarenko80c02322017-04-10 10:15:42 +00001495 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001496
1497 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1498 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1499 glCompositionDoneFenceTime =
1500 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1501 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1502 } else {
1503 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1504 }
1505 mGlCompositionDoneTimeline.updateSignalTimes();
1506
Brian Anderson4e606e32017-03-16 15:34:57 -07001507 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1508 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1509 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001510 mDisplayTimeline.updateSignalTimes();
1511
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001512 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1513 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1514
1515 // We use the refreshStartTime which might be sampled a little later than
1516 // when we started doing work for this frame, but that should be okay
1517 // since updateCompositorTiming has snapping logic.
1518 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001519 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001520 CompositorTiming compositorTiming;
1521 {
1522 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1523 compositorTiming = mCompositorTiming;
1524 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001525
Robert Carr2047fae2016-11-28 14:09:09 -08001526 mDrawingState.traverseInZOrder([&](Layer* layer) {
1527 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001528 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001529 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001530 recordBufferingStats(layer->getName().string(),
1531 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001532 }
Robert Carr2047fae2016-11-28 14:09:09 -08001533 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001534
Brian Anderson4e606e32017-03-16 15:34:57 -07001535 if (presentFence->isValid()) {
1536 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001537 enableHardwareVsync();
1538 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001539 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001540 }
1541 }
1542
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001543 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001544 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001545 enableHardwareVsync();
1546 }
1547 }
1548
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001549 if (mAnimCompositionPending) {
1550 mAnimCompositionPending = false;
1551
Brian Anderson4e606e32017-03-16 15:34:57 -07001552 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001553 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001554 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001555 } else {
1556 // The HWC doesn't support present fences, so use the refresh
1557 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001558 nsecs_t presentTime =
1559 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001560 mAnimFrameTracker.setActualPresentTime(presentTime);
1561 }
1562 mAnimFrameTracker.advanceFrame();
1563 }
Dan Stozab90cf072015-03-05 11:05:59 -08001564
1565 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1566 return;
1567 }
1568
1569 nsecs_t currentTime = systemTime();
1570 if (mHasPoweredOff) {
1571 mHasPoweredOff = false;
1572 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001573 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001575 if (numPeriods < NUM_BUCKETS - 1) {
1576 mFrameBuckets[numPeriods] += elapsedTime;
1577 } else {
1578 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1579 }
1580 mTotalTime += elapsedTime;
1581 }
1582 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583}
1584
1585void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 ATRACE_CALL();
1587 ALOGV("rebuildLayerStacks");
1588
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001590 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1591 ATRACE_CALL();
1592 mVisibleRegionsDirty = false;
1593 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001594
Jeff Sharkey76488112017-02-27 14:15:18 -07001595 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1596 Region opaqueRegion;
1597 Region dirtyRegion;
1598 Vector<sp<Layer>> layersSortedByZ;
1599 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1600 const Transform& tr(displayDevice->getTransform());
1601 const Rect bounds(displayDevice->getBounds());
1602 if (displayDevice->isDisplayOn()) {
1603 computeVisibleRegions(
1604 displayDevice->getLayerStack(), dirtyRegion,
1605 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001606
Jeff Sharkey76488112017-02-27 14:15:18 -07001607 mDrawingState.traverseInZOrder([&](Layer* layer) {
1608 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1609 Region drawRegion(tr.transform(
1610 layer->visibleNonTransparentRegion));
1611 drawRegion.andSelf(bounds);
1612 if (!drawRegion.isEmpty()) {
1613 layersSortedByZ.add(layer);
1614 } else {
1615 // Clear out the HWC layer if this layer was
1616 // previously visible, but no longer is
1617 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1618 nullptr);
1619 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001620 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001621 // WM changes displayDevice->layerStack upon sleep/awake.
1622 // Here we make sure we delete the HWC layers even if
1623 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001624 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1625 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001626 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001627 });
1628 }
1629 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1630 displayDevice->undefinedRegion.set(bounds);
1631 displayDevice->undefinedRegion.subtractSelf(
1632 tr.transform(opaqueRegion));
1633 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001634 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001635 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001637
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001638// pickColorMode translates a given dataspace into the best available color mode.
1639// Currently only support sRGB and Display-P3.
1640android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1641 switch (dataSpace) {
1642 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1643 // system expects.
1644 case HAL_DATASPACE_UNKNOWN:
1645 case HAL_DATASPACE_SRGB:
1646 case HAL_DATASPACE_V0_SRGB:
1647 return HAL_COLOR_MODE_SRGB;
1648 break;
1649
1650 case HAL_DATASPACE_DISPLAY_P3:
1651 return HAL_COLOR_MODE_DISPLAY_P3;
1652 break;
1653
1654 default:
1655 // TODO (courtneygo): Do we want to assert an error here?
1656 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1657 dataSpace);
1658 return HAL_COLOR_MODE_SRGB;
1659 break;
1660 }
1661}
1662
1663android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1664 // Only support sRGB and Display-P3 right now.
1665 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1666 return HAL_DATASPACE_DISPLAY_P3;
1667 }
1668 return HAL_DATASPACE_V0_SRGB;
1669}
1670
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 ATRACE_CALL();
1673 ALOGV("setUpHWComposer");
1674
Jesse Hall028dc8f2013-08-20 16:35:32 -07001675 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001676 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1677 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1678 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1679
1680 // If nothing has changed (!dirty), don't recompose.
1681 // If something changed, but we don't currently have any visible layers,
1682 // and didn't when we last did a composition, then skip it this time.
1683 // The second rule does two things:
1684 // - When all layers are removed from a display, we'll emit one black
1685 // frame, then nothing more until we get new layers.
1686 // - When a display is created with a private layer stack, we won't
1687 // emit any black frames until a layer is added to the layer stack.
1688 bool mustRecompose = dirty && !(empty && wasEmpty);
1689
1690 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1691 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1692 mustRecompose ? "doing" : "skipping",
1693 dirty ? "+" : "-",
1694 empty ? "+" : "-",
1695 wasEmpty ? "+" : "-");
1696
Dan Stoza71433162014-02-04 16:22:36 -08001697 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001698
1699 if (mustRecompose) {
1700 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1701 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001702 }
1703
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 // build the h/w work list
1705 if (CC_UNLIKELY(mGeometryInvalid)) {
1706 mGeometryInvalid = false;
1707 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1708 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1709 const auto hwcId = displayDevice->getHwcDisplayId();
1710 if (hwcId >= 0) {
1711 const Vector<sp<Layer>>& currentLayers(
1712 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001713 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001714 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001715 if (!layer->hasHwcLayer(hwcId)) {
1716 auto hwcLayer = mHwc->createLayer(hwcId);
1717 if (hwcLayer) {
1718 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1719 } else {
1720 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001722 }
1723 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001724
Robert Carrae060832016-11-28 10:51:00 -08001725 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001726 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001727 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001728 }
1729 }
1730 }
1731 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 }
Riley Andrews03414a12014-07-01 14:22:59 -07001733
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001734
1735 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1736
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 // Set the per-frame data
1738 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1739 auto& displayDevice = mDisplays[displayId];
1740 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001741
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 if (hwcId < 0) {
1743 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001744 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001745 if (colorMatrix != mPreviousColorMatrix) {
1746 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1747 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1748 "display %zd: %d", displayId, result);
1749 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001750 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1751 layer->setPerFrameData(displayDevice);
1752 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001753
1754 if (hasWideColorDisplay) {
1755 android_color_mode newColorMode;
1756 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1757
1758 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1759 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1760 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1761 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1762 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1763 }
1764 newColorMode = pickColorMode(newDataSpace);
1765
1766 setActiveColorModeInternal(displayDevice, newColorMode);
1767 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001768 }
1769
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001770 mPreviousColorMatrix = colorMatrix;
1771
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001773 auto& displayDevice = mDisplays[displayId];
1774 if (!displayDevice->isDisplayOn()) {
1775 continue;
1776 }
1777
1778 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1780 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001781 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001782}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001783
Mathias Agopiancd60f992012-08-16 16:28:27 -07001784void SurfaceFlinger::doComposition() {
1785 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001786 ALOGV("doComposition");
1787
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001788 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001789 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001790 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001791 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001792 // transform the dirty region into this screen's coordinate space
1793 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001794
1795 // repaint the framebuffer (if needed)
1796 doDisplayComposition(hw, dirtyRegion);
1797
Mathias Agopiancd60f992012-08-16 16:28:27 -07001798 hw->dirtyRegion.clear();
1799 hw->flip(hw->swapRegion);
1800 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001801 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001802 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001803 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001804}
1805
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806void SurfaceFlinger::postFramebuffer()
1807{
Mathias Agopian841cde52012-03-01 15:44:37 -08001808 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001810
Mathias Agopiana44b0412011-10-16 18:46:35 -07001811 const nsecs_t now = systemTime();
1812 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001813
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1815 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001816 if (!displayDevice->isDisplayOn()) {
1817 continue;
1818 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819 const auto hwcId = displayDevice->getHwcDisplayId();
1820 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001821 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001822 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001823 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001824 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1826 sp<Fence> releaseFence = Fence::NO_FENCE;
1827 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1828 releaseFence = displayDevice->getClientTargetAcquireFence();
1829 } else {
1830 auto hwcLayer = layer->getHwcLayer(hwcId);
1831 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001832 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 layer->onLayerDisplayed(releaseFence);
1834 }
1835 if (hwcId >= 0) {
1836 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001837 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001838 }
1839
Mathias Agopiana44b0412011-10-16 18:46:35 -07001840 mLastSwapBufferTime = systemTime() - now;
1841 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001842
Polina Bondarenko80c02322017-04-10 10:15:42 +00001843 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001844 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1845 logFrameStats();
1846 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001847}
1848
Mathias Agopian87baae12012-07-31 12:38:26 -07001849void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001850{
Mathias Agopian841cde52012-03-01 15:44:37 -08001851 ATRACE_CALL();
1852
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001853 // here we keep a copy of the drawing state (that is the state that's
1854 // going to be overwritten by handleTransactionLocked()) outside of
1855 // mStateLock so that the side-effects of the State assignment
1856 // don't happen with mStateLock held (which can cause deadlocks).
1857 State drawingState(mDrawingState);
1858
Mathias Agopianca4d3602011-05-19 15:38:14 -07001859 Mutex::Autolock _l(mStateLock);
1860 const nsecs_t now = systemTime();
1861 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001862
Mathias Agopianca4d3602011-05-19 15:38:14 -07001863 // Here we're guaranteed that some transaction flags are set
1864 // so we can call handleTransactionLocked() unconditionally.
1865 // We call getTransactionFlags(), which will also clear the flags,
1866 // with mStateLock held to guarantee that mCurrentState won't change
1867 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001868
Mathias Agopiane57f2922012-08-09 16:29:12 -07001869 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001870 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001871
Mathias Agopianca4d3602011-05-19 15:38:14 -07001872 mLastTransactionTime = systemTime() - now;
1873 mDebugInTransaction = 0;
1874 invalidateHwcGeometry();
1875 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001876}
1877
Mathias Agopian87baae12012-07-31 12:38:26 -07001878void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001879{
Dan Stoza7dde5992015-05-22 09:51:44 -07001880 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001881 mCurrentState.traverseInZOrder([](Layer* layer) {
1882 layer->notifyAvailableFrames();
1883 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001884
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001885 /*
1886 * Traversal of the children
1887 * (perform the transaction for each of them if needed)
1888 */
1889
Mathias Agopian3559b072012-08-15 13:46:03 -07001890 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001891 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001892 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001893 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001894
1895 const uint32_t flags = layer->doTransaction(0);
1896 if (flags & Layer::eVisibleRegion)
1897 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001898 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899 }
1900
1901 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001902 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001903 */
1904
Mathias Agopiane57f2922012-08-09 16:29:12 -07001905 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001906 // here we take advantage of Vector's copy-on-write semantics to
1907 // improve performance by skipping the transaction entirely when
1908 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001909 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1910 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001911 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001912 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001913 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001914 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001915
1916 // find the displays that were removed
1917 // (ie: in drawing state but not in current state)
1918 // also handle displays that changed
1919 // (ie: displays that are in both lists)
1920 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001921 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1922 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001923 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001924 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001925 // Call makeCurrent() on the primary display so we can
1926 // be sure that nothing associated with this display
1927 // is current.
Polina Bondarenko80c02322017-04-10 10:15:42 +00001928 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001929 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001930 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1931 if (hw != NULL)
1932 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001933 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001934 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001935 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001936 } else {
1937 ALOGW("trying to remove the main display");
1938 }
1939 } else {
1940 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001941 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001942 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001943 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1944 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001945 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001946 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001947 // recreating the DisplayDevice, so we just remove it
1948 // from the drawing state, so that it get re-added
1949 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001950 sp<DisplayDevice> hw(getDisplayDevice(display));
1951 if (hw != NULL)
1952 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001953 mDisplays.removeItem(display);
1954 mDrawingState.displays.removeItemsAt(i);
1955 dc--; i--;
1956 // at this point we must loop to the next item
1957 continue;
1958 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001959
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001960 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001961 if (disp != NULL) {
1962 if (state.layerStack != draw[i].layerStack) {
1963 disp->setLayerStack(state.layerStack);
1964 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001965 if ((state.orientation != draw[i].orientation)
1966 || (state.viewport != draw[i].viewport)
1967 || (state.frame != draw[i].frame))
1968 {
1969 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001970 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001971 }
Michael Lentine47e45402014-07-18 15:34:25 -07001972 if (state.width != draw[i].width || state.height != draw[i].height) {
1973 disp->setDisplaySize(state.width, state.height);
1974 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001975 }
1976 }
1977 }
1978
1979 // find displays that were added
1980 // (ie: in current state but not in drawing state)
1981 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001982 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001983 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001984
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001985 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001986 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001987 sp<IGraphicBufferProducer> bqProducer;
1988 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001989 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1990 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001991
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001993 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001994 // Virtual displays without a surface are dormant:
1995 // they have external state (layer stack, projection,
1996 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001997 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001998
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04001999 // Allow VR composer to use virtual displays.
2000 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002001 int width = 0;
2002 int status = state.surface->query(
2003 NATIVE_WINDOW_WIDTH, &width);
2004 ALOGE_IF(status != NO_ERROR,
2005 "Unable to query width (%d)", status);
2006 int height = 0;
2007 status = state.surface->query(
2008 NATIVE_WINDOW_HEIGHT, &height);
2009 ALOGE_IF(status != NO_ERROR,
2010 "Unable to query height (%d)", status);
2011 int intFormat = 0;
2012 status = state.surface->query(
2013 NATIVE_WINDOW_FORMAT, &intFormat);
2014 ALOGE_IF(status != NO_ERROR,
2015 "Unable to query format (%d)", status);
2016 auto format = static_cast<android_pixel_format_t>(
2017 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002018
Dan Stoza8cf150a2016-08-02 10:27:31 -07002019 mHwc->allocateVirtualDisplay(width, height, &format,
2020 &hwcId);
2021 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002022
Dan Stoza5cf424b2016-05-20 14:02:39 -07002023 // TODO: Plumb requested format back up to consumer
2024
Dan Stoza9e56aa02015-11-02 13:00:03 -08002025 sp<VirtualDisplaySurface> vds =
2026 new VirtualDisplaySurface(*mHwc,
2027 hwcId, state.surface, bqProducer,
2028 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002029
2030 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002031 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002032 }
2033 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002034 ALOGE_IF(state.surface!=NULL,
2035 "adding a supported display, but rendering "
2036 "surface is provided (%p), ignoring it",
2037 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002038
2039 hwcId = state.type;
2040 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2041 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002042 }
2043
2044 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002045 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002046 sp<DisplayDevice> hw =
2047 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2048 dispSurface, producer,
2049 mRenderEngine->getEGLConfig(),
2050 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002051 hw->setLayerStack(state.layerStack);
2052 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002053 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002054 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002055 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002057 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002058 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002059 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002060 }
2061 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002062 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064
Mathias Agopian84300952012-11-21 16:02:13 -08002065 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2066 // The transform hint might have changed for some layers
2067 // (either because a display has changed, or because a layer
2068 // as changed).
2069 //
2070 // Walk through all the layers in currentLayers,
2071 // and update their transform hint.
2072 //
2073 // If a layer is visible only on a single display, then that
2074 // display is used to calculate the hint, otherwise we use the
2075 // default display.
2076 //
2077 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2078 // the hint is set before we acquire a buffer from the surface texture.
2079 //
2080 // NOTE: layer transactions have taken place already, so we use their
2081 // drawing state. However, SurfaceFlinger's own transaction has not
2082 // happened yet, so we must use the current state layer list
2083 // (soon to become the drawing state list).
2084 //
2085 sp<const DisplayDevice> disp;
2086 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002087 bool first = true;
2088 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002089 // NOTE: we rely on the fact that layers are sorted by
2090 // layerStack first (so we don't have to traverse the list
2091 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002092 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002093 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002094 currentlayerStack = layerStack;
2095 // figure out if this layerstack is mirrored
2096 // (more than one display) if so, pick the default display,
2097 // if not, pick the only display it's on.
2098 disp.clear();
2099 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2100 sp<const DisplayDevice> hw(mDisplays[dpy]);
2101 if (hw->getLayerStack() == currentlayerStack) {
2102 if (disp == NULL) {
2103 disp = hw;
2104 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002105 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002106 break;
2107 }
2108 }
2109 }
2110 }
Chet Haase91d25932013-04-11 15:24:55 -07002111 if (disp == NULL) {
2112 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2113 // redraw after transform hint changes. See bug 8508397.
2114
2115 // could be null when this layer is using a layerStack
2116 // that is not visible on any display. Also can occur at
2117 // screen off/on times.
Polina Bondarenko80c02322017-04-10 10:15:42 +00002118 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002119 }
Chet Haase91d25932013-04-11 15:24:55 -07002120 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002121
2122 first = false;
2123 });
Mathias Agopian84300952012-11-21 16:02:13 -08002124 }
2125
2126
Mathias Agopian3559b072012-08-15 13:46:03 -07002127 /*
2128 * Perform our own transaction if needed
2129 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002130
2131 if (mLayersAdded) {
2132 mLayersAdded = false;
2133 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002134 mVisibleRegionsDirty = true;
2135 }
2136
2137 // some layers might have been removed, so
2138 // we need to update the regions they're exposing.
2139 if (mLayersRemoved) {
2140 mLayersRemoved = false;
2141 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002142 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002143 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002144 // this layer is not visible anymore
2145 // TODO: we could traverse the tree from front to back and
2146 // compute the actual visible region
2147 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002148 Region visibleReg;
2149 visibleReg.set(layer->computeScreenBounds());
2150 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002151 }
Robert Carr2047fae2016-11-28 14:09:09 -08002152 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002153 }
2154
2155 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002156
2157 updateCursorAsync();
2158}
2159
2160void SurfaceFlinger::updateCursorAsync()
2161{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2163 auto& displayDevice = mDisplays[displayId];
2164 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002165 continue;
2166 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167
2168 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2169 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002170 }
2171 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002172}
2173
2174void SurfaceFlinger::commitTransaction()
2175{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002176 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002177 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002178 for (const auto& l : mLayersPendingRemoval) {
2179 recordBufferingStats(l->getName().string(),
2180 l->getOccupancyHistory(true));
2181 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002182 }
2183 mLayersPendingRemoval.clear();
2184 }
2185
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002186 // If this transaction is part of a window animation then the next frame
2187 // we composite should be considered an animation as well.
2188 mAnimCompositionPending = mAnimTransactionPending;
2189
Mathias Agopian4fec8732012-06-29 14:12:52 -07002190 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002191 mDrawingState.traverseInZOrder([](Layer* layer) {
2192 layer->commitChildList();
2193 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002194 mTransactionPending = false;
2195 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002196 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002197}
2198
Robert Carr2047fae2016-11-28 14:09:09 -08002199void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002200 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201{
Mathias Agopian841cde52012-03-01 15:44:37 -08002202 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002203 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205 Region aboveOpaqueLayers;
2206 Region aboveCoveredLayers;
2207 Region dirty;
2208
Mathias Agopian87baae12012-07-31 12:38:26 -07002209 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210
Robert Carr2047fae2016-11-28 14:09:09 -08002211 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002213 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214
Jesse Hall01e29052013-02-19 16:13:35 -08002215 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002216 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002217 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002218
Mathias Agopianab028732010-03-16 16:41:46 -07002219 /*
2220 * opaqueRegion: area of a surface that is fully opaque.
2221 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002222 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002223
2224 /*
2225 * visibleRegion: area of a surface that is visible on screen
2226 * and not fully transparent. This is essentially the layer's
2227 * footprint minus the opaque regions above it.
2228 * Areas covered by a translucent surface are considered visible.
2229 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002231
2232 /*
2233 * coveredRegion: area of a surface that is covered by all
2234 * visible regions above it (which includes the translucent areas).
2235 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002237
Jesse Halla8026d22012-09-25 13:25:04 -07002238 /*
2239 * transparentRegion: area of a surface that is hinted to be completely
2240 * transparent. This is only used to tell when the layer has no visible
2241 * non-transparent regions and can be removed from the layer list. It
2242 * does not affect the visibleRegion of this layer or any layers
2243 * beneath it. The hint may not be correct if apps don't respect the
2244 * SurfaceView restrictions (which, sadly, some don't).
2245 */
2246 Region transparentRegion;
2247
Mathias Agopianab028732010-03-16 16:41:46 -07002248
2249 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002250 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002251 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002252 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002254 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002255 if (!visibleRegion.isEmpty()) {
2256 // Remove the transparent area from the visible region
2257 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002258 if (tr.preserveRects()) {
2259 // transform the transparent region
2260 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002261 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002262 // transformation too complex, can't do the
2263 // transparent region optimization.
2264 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002265 }
Mathias Agopianab028732010-03-16 16:41:46 -07002266 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002267
Mathias Agopianab028732010-03-16 16:41:46 -07002268 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002269 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002271 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2272 // the opaque region is the layer's footprint
2273 opaqueRegion = visibleRegion;
2274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002275 }
2276 }
2277
Mathias Agopianab028732010-03-16 16:41:46 -07002278 // Clip the covered region to the visible region
2279 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2280
2281 // Update aboveCoveredLayers for next (lower) layer
2282 aboveCoveredLayers.orSelf(visibleRegion);
2283
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002284 // subtract the opaque region covered by the layers above us
2285 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286
2287 // compute this layer's dirty region
2288 if (layer->contentDirty) {
2289 // we need to invalidate the whole region
2290 dirty = visibleRegion;
2291 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002292 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002293 layer->contentDirty = false;
2294 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002295 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002296 * the exposed region consists of two components:
2297 * 1) what's VISIBLE now and was COVERED before
2298 * 2) what's EXPOSED now less what was EXPOSED before
2299 *
2300 * note that (1) is conservative, we start with the whole
2301 * visible region but only keep what used to be covered by
2302 * something -- which mean it may have been exposed.
2303 *
2304 * (2) handles areas that were not covered by anything but got
2305 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002306 */
Mathias Agopianab028732010-03-16 16:41:46 -07002307 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002308 const Region oldVisibleRegion = layer->visibleRegion;
2309 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002310 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2311 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 }
2313 dirty.subtractSelf(aboveOpaqueLayers);
2314
2315 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002316 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317
Mathias Agopianab028732010-03-16 16:41:46 -07002318 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002320
Jesse Halla8026d22012-09-25 13:25:04 -07002321 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322 layer->setVisibleRegion(visibleRegion);
2323 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002324 layer->setVisibleNonTransparentRegion(
2325 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002326 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327
Mathias Agopian87baae12012-07-31 12:38:26 -07002328 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002329}
2330
Mathias Agopian87baae12012-07-31 12:38:26 -07002331void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2332 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002333 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002334 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2335 if (hw->getLayerStack() == layerStack) {
2336 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002337 }
2338 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002339}
2340
Dan Stoza6b9454d2014-11-07 16:00:59 -08002341bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002343 ALOGV("handlePageFlip");
2344
Brian Andersond6927fb2016-07-23 23:37:30 -07002345 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346
Mathias Agopian4fec8732012-06-29 14:12:52 -07002347 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002348 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002349
2350 // Store the set of layers that need updates. This set must not change as
2351 // buffers are being latched, as this could result in a deadlock.
2352 // Example: Two producers share the same command stream and:
2353 // 1.) Layer 0 is latched
2354 // 2.) Layer 0 gets a new frame
2355 // 2.) Layer 1 gets a new frame
2356 // 3.) Layer 1 is latched.
2357 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2358 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002359 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002360 if (layer->hasQueuedFrame()) {
2361 frameQueued = true;
2362 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002363 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002364 } else {
2365 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002366 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002367 } else {
2368 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002369 }
Robert Carr2047fae2016-11-28 14:09:09 -08002370 });
2371
Dan Stoza9e56aa02015-11-02 13:00:03 -08002372 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002373 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002374 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002375 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002376 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002377
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002378 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002379
2380 // If we will need to wake up at some time in the future to deal with a
2381 // queued frame that shouldn't be displayed during this vsync period, wake
2382 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002384 signalLayerUpdate();
2385 }
2386
2387 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389}
2390
Mathias Agopianad456f92011-01-13 17:53:01 -08002391void SurfaceFlinger::invalidateHwcGeometry()
2392{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002394}
2395
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002396
Fabien Sanglard830b8472016-11-30 16:35:58 -08002397void SurfaceFlinger::doDisplayComposition(
2398 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002399 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400{
Dan Stoza71433162014-02-04 16:22:36 -08002401 // We only need to actually compose the display if:
2402 // 1) It is being handled by hardware composer, which may need this to
2403 // keep its virtual display state machine in sync, or
2404 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002405 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002406 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002408 return;
2409 }
2410
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 ALOGV("doDisplayComposition");
2412
Mathias Agopian87baae12012-07-31 12:38:26 -07002413 Region dirtyRegion(inDirtyRegion);
2414
Mathias Agopianb8a55602009-06-26 19:06:36 -07002415 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002416 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417
Fabien Sanglard830b8472016-11-30 16:35:58 -08002418 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002419 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002420 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2421 // takes a rectangle, we must make sure to update that whole
2422 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002423 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002424 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002425 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002426 // We need to redraw the rectangle that will be updated
2427 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002428 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002429 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002430 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002431 } else {
2432 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002433 dirtyRegion.set(displayDevice->bounds());
2434 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435 }
2436 }
2437
Fabien Sanglard830b8472016-11-30 16:35:58 -08002438 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002440 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002441 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002442
2443 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002444 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445}
2446
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447bool SurfaceFlinger::doComposeSurfaces(
2448 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002449{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002450 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002451
Dan Stoza9e56aa02015-11-02 13:00:03 -08002452 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002453
2454 mat4 oldColorMatrix;
2455 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2456 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2457 if (applyColorMatrix) {
2458 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2459 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2460 }
2461
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2463 if (hasClientComposition) {
2464 ALOGV("hasClientComposition");
2465
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002466#ifdef USE_HWC2
2467 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2468 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2469#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002471 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002473 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Polina Bondarenko80c02322017-04-10 10:15:42 +00002474 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002475 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2476 }
2477 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002478 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002479
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002480 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2482 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002483 // when using overlays, we assume a fully transparent framebuffer
2484 // NOTE: we could reduce how much we need to clear, for instance
2485 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002486 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002487 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002489 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002490 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002492
2493 // we remove the scissor part
2494 // we're left with the letterbox region
2495 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002497
2498 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002500
2501 // but limit it to the dirty region
2502 region.andSelf(dirty);
2503
Mathias Agopianb9494d52012-04-18 02:28:45 -07002504 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002505 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002506 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002507 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002508 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002509 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002510
Dan Stoza9e56aa02015-11-02 13:00:03 -08002511 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002512 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002513 // scissor on the main display. It should never be needed
2514 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 const Rect& bounds(displayDevice->getBounds());
2516 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002517 if (scissor != bounds) {
2518 // scissor doesn't match the screen's dimensions, so we
2519 // need to clear everything outside of it and enable
2520 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002521
Mathias Agopianf45c5102012-10-24 16:29:17 -07002522 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 const uint32_t height = displayDevice->getHeight();
2524 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002525 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002526 }
2527 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002528 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002529
Mathias Agopian85d751c2012-08-29 16:59:24 -07002530 /*
2531 * and then, render the layers targeted at the framebuffer
2532 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002533
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534 ALOGV("Rendering client layers");
2535 const Transform& displayTransform = displayDevice->getTransform();
2536 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002537 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002538 bool firstLayer = true;
2539 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2540 const Region clip(dirty.intersect(
2541 displayTransform.transform(layer->visibleRegion)));
2542 ALOGV("Layer: %s", layer->getName().string());
2543 ALOGV(" Composition type: %s",
2544 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002545 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 switch (layer->getCompositionType(hwcId)) {
2547 case HWC2::Composition::Cursor:
2548 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002549 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002550 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002551 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002552 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2553 layer->isOpaque(state) && (state.alpha == 1.0f)
2554 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002555 // never clear the very first layer since we're
2556 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002557 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002558 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002559 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002560 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002561 case HWC2::Composition::Client: {
2562 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002563 break;
2564 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002566 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002567 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002568 } else {
2569 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002570 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002571 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002572 }
2573 } else {
2574 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002575 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002576 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002578 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002580 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002581 }
2582 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002583
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002584 if (applyColorMatrix) {
2585 getRenderEngine().setupColorTransform(oldColorMatrix);
2586 }
2587
Mathias Agopianf45c5102012-10-24 16:29:17 -07002588 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002590 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591}
2592
Fabien Sanglard830b8472016-11-30 16:35:58 -08002593void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2594 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002595 RenderEngine& engine(getRenderEngine());
2596 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597}
2598
Dan Stoza7d89d062015-04-30 13:29:25 -07002599status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002600 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002601 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002602 const sp<Layer>& lbc,
2603 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002604{
Dan Stoza7d89d062015-04-30 13:29:25 -07002605 // add this layer to the current state list
2606 {
2607 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002608 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002609 return NO_MEMORY;
2610 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002611 if (parent == nullptr) {
2612 mCurrentState.layersSortedByZ.add(lbc);
2613 } else {
2614 parent->addChild(lbc);
2615 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002616 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002617 mLayersAdded = true;
2618 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002619 }
2620
Mathias Agopian96f08192010-06-02 23:28:45 -07002621 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002622 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002623
Dan Stoza7d89d062015-04-30 13:29:25 -07002624 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002625}
2626
Robert Carr9524cb32017-02-13 11:32:32 -08002627status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002628 Mutex::Autolock _l(mStateLock);
2629
Robert Carr1f0a16a2016-10-24 16:27:39 -07002630 const auto& p = layer->getParent();
2631 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2632 mCurrentState.layersSortedByZ.remove(layer);
2633
Robert Carr136e2f62017-02-08 17:54:29 -08002634 // As a matter of normal operation, the LayerCleaner will produce a second
2635 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2636 // so we will succeed in promoting it, but it's already been removed
2637 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2638 // otherwise something has gone wrong and we are leaking the layer.
2639 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2641 layer->getName().string(),
2642 (p != nullptr) ? p->getName().string() : "no-parent");
2643 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002644 } else if (index < 0) {
2645 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002646 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002647
2648 mLayersPendingRemoval.add(layer);
2649 mLayersRemoved = true;
2650 mNumLayers--;
2651 setTransactionFlags(eTransactionNeeded);
2652 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653}
2654
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002655uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002656 return android_atomic_release_load(&mTransactionFlags);
2657}
2658
Mathias Agopian3f844832013-08-07 21:24:32 -07002659uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2661}
2662
Mathias Agopian3f844832013-08-07 21:24:32 -07002663uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2665 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002666 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 }
2668 return old;
2669}
2670
Mathias Agopian8b33f032012-07-24 20:43:54 -07002671void SurfaceFlinger::setTransactionState(
2672 const Vector<ComposerState>& state,
2673 const Vector<DisplayState>& displays,
2674 uint32_t flags)
2675{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002676 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002677 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002678 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002680 if (flags & eAnimation) {
2681 // For window updates that are part of an animation we must wait for
2682 // previous animation "frames" to be handled.
2683 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002684 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002685 if (CC_UNLIKELY(err != NO_ERROR)) {
2686 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002687 // caller after a few seconds.
2688 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2689 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002690 mAnimTransactionPending = false;
2691 break;
2692 }
2693 }
2694 }
2695
Mathias Agopiane57f2922012-08-09 16:29:12 -07002696 size_t count = displays.size();
2697 for (size_t i=0 ; i<count ; i++) {
2698 const DisplayState& s(displays[i]);
2699 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002700 }
2701
Mathias Agopiane57f2922012-08-09 16:29:12 -07002702 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002703 for (size_t i=0 ; i<count ; i++) {
2704 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002705 // Here we need to check that the interface we're given is indeed
2706 // one of our own. A malicious client could give us a NULL
2707 // IInterface, or one of its own or even one of our own but a
2708 // different type. All these situations would cause us to crash.
2709 //
2710 // NOTE: it would be better to use RTTI as we could directly check
2711 // that we have a Client*. however, RTTI is disabled in Android.
2712 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002713 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002714 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002715 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002716 sp<Client> client( static_cast<Client *>(s.client.get()) );
2717 transactionFlags |= setClientStateLocked(client, s.state);
2718 }
2719 }
2720 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002721 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002722
Robert Carr2a7dbb42016-05-24 11:41:28 -07002723 // If a synchronous transaction is explicitly requested without any changes,
2724 // force a transaction anyway. This can be used as a flush mechanism for
2725 // previous async transactions.
2726 if (transactionFlags == 0 && (flags & eSynchronous)) {
2727 transactionFlags = eTransactionNeeded;
2728 }
2729
Mathias Agopian386aa982011-11-07 21:58:03 -08002730 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002731 if (mInterceptor.isEnabled()) {
2732 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2733 }
Irvel468051e2016-06-13 16:44:44 -07002734
Mathias Agopian386aa982011-11-07 21:58:03 -08002735 // this triggers the transaction
2736 setTransactionFlags(transactionFlags);
2737
2738 // if this is a synchronous transaction, wait for it to take effect
2739 // before returning.
2740 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002741 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002742 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002743 if (flags & eAnimation) {
2744 mAnimTransactionPending = true;
2745 }
2746 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002747 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2748 if (CC_UNLIKELY(err != NO_ERROR)) {
2749 // just in case something goes wrong in SF, return to the
2750 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002751 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2752 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002753 break;
2754 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 }
2757}
2758
Mathias Agopiane57f2922012-08-09 16:29:12 -07002759uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2760{
Jesse Hall9a143922012-10-04 16:29:19 -07002761 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2762 if (dpyIdx < 0)
2763 return 0;
2764
Mathias Agopiane57f2922012-08-09 16:29:12 -07002765 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002766 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002767 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002768 const uint32_t what = s.what;
2769 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002770 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002771 disp.surface = s.surface;
2772 flags |= eDisplayTransactionNeeded;
2773 }
2774 }
2775 if (what & DisplayState::eLayerStackChanged) {
2776 if (disp.layerStack != s.layerStack) {
2777 disp.layerStack = s.layerStack;
2778 flags |= eDisplayTransactionNeeded;
2779 }
2780 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002781 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 if (disp.orientation != s.orientation) {
2783 disp.orientation = s.orientation;
2784 flags |= eDisplayTransactionNeeded;
2785 }
2786 if (disp.frame != s.frame) {
2787 disp.frame = s.frame;
2788 flags |= eDisplayTransactionNeeded;
2789 }
2790 if (disp.viewport != s.viewport) {
2791 disp.viewport = s.viewport;
2792 flags |= eDisplayTransactionNeeded;
2793 }
2794 }
Michael Lentine47e45402014-07-18 15:34:25 -07002795 if (what & DisplayState::eDisplaySizeChanged) {
2796 if (disp.width != s.width) {
2797 disp.width = s.width;
2798 flags |= eDisplayTransactionNeeded;
2799 }
2800 if (disp.height != s.height) {
2801 disp.height = s.height;
2802 flags |= eDisplayTransactionNeeded;
2803 }
2804 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002805 }
2806 return flags;
2807}
2808
2809uint32_t SurfaceFlinger::setClientStateLocked(
2810 const sp<Client>& client,
2811 const layer_state_t& s)
2812{
2813 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002814 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002815 if (layer != 0) {
2816 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002817 bool geometryAppliesWithResize =
2818 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002819 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002820 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002821 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002822 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002823 }
2824 if (what & layer_state_t::eLayerChanged) {
2825 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 const auto& p = layer->getParent();
2827 if (p == nullptr) {
2828 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2829 if (layer->setLayer(s.z) && idx >= 0) {
2830 mCurrentState.layersSortedByZ.removeAt(idx);
2831 mCurrentState.layersSortedByZ.add(layer);
2832 // we need traversal (state changed)
2833 // AND transaction (list changed)
2834 flags |= eTransactionNeeded|eTraversalNeeded;
2835 }
2836 } else {
2837 if (p->setChildLayer(layer, s.z)) {
2838 flags |= eTransactionNeeded|eTraversalNeeded;
2839 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002840 }
2841 }
2842 if (what & layer_state_t::eSizeChanged) {
2843 if (layer->setSize(s.w, s.h)) {
2844 flags |= eTraversalNeeded;
2845 }
2846 }
2847 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002849 flags |= eTraversalNeeded;
2850 }
2851 if (what & layer_state_t::eMatrixChanged) {
2852 if (layer->setMatrix(s.matrix))
2853 flags |= eTraversalNeeded;
2854 }
2855 if (what & layer_state_t::eTransparentRegionChanged) {
2856 if (layer->setTransparentRegionHint(s.transparentRegion))
2857 flags |= eTraversalNeeded;
2858 }
Dan Stoza23116082015-06-18 14:58:39 -07002859 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002860 if (layer->setFlags(s.flags, s.mask))
2861 flags |= eTraversalNeeded;
2862 }
2863 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002864 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002865 flags |= eTraversalNeeded;
2866 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002867 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002868 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002869 flags |= eTraversalNeeded;
2870 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002871 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002872 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002873 // We only allow setting layer stacks for top level layers,
2874 // everything else inherits layer stack from its parent.
2875 if (layer->hasParent()) {
2876 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2877 layer->getName().string());
2878 } else if (idx < 0) {
2879 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2880 "that also does not appear in the top level layer list. Something"
2881 " has gone wrong.", layer->getName().string());
2882 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002883 mCurrentState.layersSortedByZ.removeAt(idx);
2884 mCurrentState.layersSortedByZ.add(layer);
2885 // we need traversal (state changed)
2886 // AND transaction (list changed)
2887 flags |= eTransactionNeeded|eTraversalNeeded;
2888 }
2889 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002890 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002891 if (s.barrierHandle != nullptr) {
2892 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2893 } else if (s.barrierGbp != nullptr) {
2894 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2895 if (authenticateSurfaceTextureLocked(gbp)) {
2896 const auto& otherLayer =
2897 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2898 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2899 } else {
2900 ALOGE("Attempt to defer transaction to to an"
2901 " unrecognized GraphicBufferProducer");
2902 }
2903 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002904 // We don't trigger a traversal here because if no other state is
2905 // changed, we don't want this to cause any more work
2906 }
Robert Carr1db73f62016-12-21 12:58:51 -08002907 if (what & layer_state_t::eReparentChildren) {
2908 if (layer->reparentChildren(s.reparentHandle)) {
2909 flags |= eTransactionNeeded|eTraversalNeeded;
2910 }
2911 }
Robert Carr9524cb32017-02-13 11:32:32 -08002912 if (what & layer_state_t::eDetachChildren) {
2913 layer->detachChildren();
2914 }
Robert Carrc3574f72016-03-24 12:19:32 -07002915 if (what & layer_state_t::eOverrideScalingModeChanged) {
2916 layer->setOverrideScalingMode(s.overrideScalingMode);
2917 // We don't trigger a traversal here because if no other state is
2918 // changed, we don't want this to cause any more work
2919 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920 }
2921 return flags;
2922}
2923
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002924status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002925 const String8& name,
2926 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002927 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002928 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2929 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002931 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002932 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002933 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002934 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002935 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002936
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002937 status_t result = NO_ERROR;
2938
2939 sp<Layer> layer;
2940
Cody Northropbc755282017-03-31 12:00:08 -06002941 String8 uniqueName = getUniqueLayerName(name);
2942
Mathias Agopian3165cc22012-08-08 19:42:09 -07002943 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2944 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002945 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002946 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002947 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002949 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002950 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002951 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002952 handle, gbp, &layer);
2953 break;
2954 default:
2955 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 break;
2957 }
2958
Dan Stoza7d89d062015-04-30 13:29:25 -07002959 if (result != NO_ERROR) {
2960 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002962
Albert Chaulk479c60c2017-01-27 14:21:34 -05002963 layer->setInfo(windowType, ownerUid);
2964
Robert Carr1f0a16a2016-10-24 16:27:39 -07002965 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002966 if (result != NO_ERROR) {
2967 return result;
2968 }
Irvelffc9efc2016-07-27 15:16:37 -07002969 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002970
2971 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002972 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Cody Northropbc755282017-03-31 12:00:08 -06002975String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
2976{
2977 bool matchFound = true;
2978 uint32_t dupeCounter = 0;
2979
2980 // Tack on our counter whether there is a hit or not, so everyone gets a tag
2981 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
2982
2983 // Loop over layers until we're sure there is no matching name
2984 while (matchFound) {
2985 matchFound = false;
2986 mDrawingState.traverseInZOrder([&](Layer* layer) {
2987 if (layer->getName() == uniqueName) {
2988 matchFound = true;
2989 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
2990 }
2991 });
2992 }
2993
2994 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
2995
2996 return uniqueName;
2997}
2998
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002999status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3000 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3001 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002{
3003 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003004 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003005 case PIXEL_FORMAT_TRANSPARENT:
3006 case PIXEL_FORMAT_TRANSLUCENT:
3007 format = PIXEL_FORMAT_RGBA_8888;
3008 break;
3009 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003010 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011 break;
3012 }
3013
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003014 *outLayer = new Layer(this, client, name, w, h, flags);
3015 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3016 if (err == NO_ERROR) {
3017 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003018 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003020
3021 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3022 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003023}
3024
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003025status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3026 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3027 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003029 *outLayer = new LayerDim(this, client, name, w, h, flags);
3030 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003031 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003032 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003033}
3034
Mathias Agopianac9fa422013-02-11 16:40:36 -08003035status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036{
Robert Carr9524cb32017-02-13 11:32:32 -08003037 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003038 status_t err = NO_ERROR;
3039 sp<Layer> l(client->getLayerUser(handle));
3040 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003041 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003042 err = removeLayer(l);
3043 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3044 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003045 }
3046 return err;
3047}
3048
Mathias Agopian13127d82013-03-05 17:47:11 -08003049status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003050{
Mathias Agopian67106042013-03-14 19:18:13 -07003051 // called by ~LayerCleaner() when all references to the IBinder (handle)
3052 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003053 sp<Layer> l = layer.promote();
3054 if (l == nullptr) {
3055 // The layer has already been removed, carry on
3056 return NO_ERROR;
3057 } if (l->getParent() != nullptr) {
3058 // If we have a parent, then we can continue to live as long as it does.
3059 return NO_ERROR;
3060 }
3061 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062}
3063
Mathias Agopianb60314a2012-04-10 22:09:54 -07003064// ---------------------------------------------------------------------------
3065
Andy McFadden13a082e2012-08-24 10:16:42 -07003066void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003067 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003068 Vector<ComposerState> state;
3069 Vector<DisplayState> displays;
3070 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003071 d.what = DisplayState::eDisplayProjectionChanged |
3072 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003073 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003074 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003075 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003076 d.frame.makeInvalid();
3077 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003078 d.width = 0;
3079 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003080 displays.add(d);
3081 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003082 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003083
Dan Stoza9e56aa02015-11-02 13:00:03 -08003084 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3085 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003086 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003087
Brian Andersond0010582017-03-07 13:20:31 -08003088 // Use phase of 0 since phase is not known.
3089 // Use latency of 0, which will snap to the ideal latency.
3090 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003091}
3092
3093void SurfaceFlinger::initializeDisplays() {
3094 class MessageScreenInitialized : public MessageBase {
3095 SurfaceFlinger* flinger;
3096 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003097 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003098 virtual bool handler() {
3099 flinger->onInitializeDisplays();
3100 return true;
3101 }
3102 };
3103 sp<MessageBase> msg = new MessageScreenInitialized(this);
3104 postMessageAsync(msg); // we may be called from main thread, use async message
3105}
3106
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003107void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3108 int mode) {
3109 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3110 this);
3111 int32_t type = hw->getDisplayType();
3112 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003113
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003114 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003115 return;
3116 }
3117
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003118 hw->setPowerMode(mode);
3119 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3120 ALOGW("Trying to set power mode for virtual display");
3121 return;
3122 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003123
Irvelffc9efc2016-07-27 15:16:37 -07003124 if (mInterceptor.isEnabled()) {
3125 Mutex::Autolock _l(mStateLock);
3126 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3127 if (idx < 0) {
3128 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3129 return;
3130 }
3131 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3132 }
3133
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003134 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003135 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003136 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003137 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3138 // FIXME: eventthread only knows about the main display right now
3139 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003140 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003141 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003143 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003144 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003145 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003146
3147 struct sched_param param = {0};
3148 param.sched_priority = 1;
3149 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3150 ALOGW("Couldn't set SCHED_FIFO on display on");
3151 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003152 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003153 // Turn off the display
3154 struct sched_param param = {0};
3155 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3156 ALOGW("Couldn't set SCHED_OTHER on display off");
3157 }
3158
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003159 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003160 disableHardwareVsync(true); // also cancels any in-progress resync
3161
Mathias Agopiancde87a32012-09-13 14:09:01 -07003162 // FIXME: eventthread only knows about the main display right now
3163 mEventThread->onScreenReleased();
3164 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003165
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003166 getHwComposer().setPowerMode(type, mode);
3167 mVisibleRegionsDirty = true;
3168 // from this point on, SF will stop drawing on this display
3169 } else {
3170 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003171 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003172}
3173
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003174void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3175 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003176 SurfaceFlinger& mFlinger;
3177 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003178 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003179 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003180 MessageSetPowerMode(SurfaceFlinger& flinger,
3181 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3182 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003183 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003184 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003185 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003186 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003187 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003188 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003189 ALOGW("Attempt to set power mode = %d for virtual display",
3190 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003191 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003192 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003193 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003194 return true;
3195 }
3196 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003197 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003198 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003199}
3200
3201// ---------------------------------------------------------------------------
3202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3204{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003206
Mathias Agopianbd115332013-04-18 16:41:04 -07003207 IPCThreadState* ipc = IPCThreadState::self();
3208 const int pid = ipc->getCallingPid();
3209 const int uid = ipc->getCallingUid();
3210 if ((uid != AID_SHELL) &&
3211 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003212 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003213 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003215 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003216 // (this would indicate SF is stuck, but we want to be able to
3217 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003218 status_t err = mStateLock.timedLock(s2ns(1));
3219 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003220 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003221 result.appendFormat(
3222 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3223 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003224 }
3225
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003226 bool dumpAll = true;
3227 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003228 size_t numArgs = args.size();
3229 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003230 if ((index < numArgs) &&
3231 (args[index] == String16("--list"))) {
3232 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003233 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003234 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003235 }
3236
3237 if ((index < numArgs) &&
3238 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003239 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003240 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003241 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003242 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003243
3244 if ((index < numArgs) &&
3245 (args[index] == String16("--latency-clear"))) {
3246 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003247 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003248 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003249 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003250
3251 if ((index < numArgs) &&
3252 (args[index] == String16("--dispsync"))) {
3253 index++;
3254 mPrimaryDispSync.dump(result);
3255 dumpAll = false;
3256 }
Dan Stozab90cf072015-03-05 11:05:59 -08003257
3258 if ((index < numArgs) &&
3259 (args[index] == String16("--static-screen"))) {
3260 index++;
3261 dumpStaticScreenStats(result);
3262 dumpAll = false;
3263 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003264
3265 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003266 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003267 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003268 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003269 dumpAll = false;
3270 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003271
3272 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3273 index++;
3274 dumpWideColorInfo(result);
3275 dumpAll = false;
3276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003278
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003279 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003280 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003281 }
3282
Mathias Agopian9795c422009-08-26 16:36:26 -07003283 if (locked) {
3284 mStateLock.unlock();
3285 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 }
3287 write(fd, result.string(), result.size());
3288 return NO_ERROR;
3289}
3290
Dan Stozac7014012014-02-14 15:03:43 -08003291void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3292 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003293{
Robert Carr2047fae2016-11-28 14:09:09 -08003294 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003295 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003296 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003297}
3298
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003299void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003300 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003301{
3302 String8 name;
3303 if (index < args.size()) {
3304 name = String8(args[index]);
3305 index++;
3306 }
3307
Dan Stoza9e56aa02015-11-02 13:00:03 -08003308 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3309 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003310 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003311
3312 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003313 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003314 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003315 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003316 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003317 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003318 }
Robert Carr2047fae2016-11-28 14:09:09 -08003319 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003320 }
3321}
3322
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003323void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003324 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003325{
3326 String8 name;
3327 if (index < args.size()) {
3328 name = String8(args[index]);
3329 index++;
3330 }
3331
Robert Carr2047fae2016-11-28 14:09:09 -08003332 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003333 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003334 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003335 }
Robert Carr2047fae2016-11-28 14:09:09 -08003336 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003337
Svetoslavd85084b2014-03-20 10:28:31 -07003338 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003339}
3340
Jamie Gennis6547ff42013-07-16 20:12:42 -07003341// This should only be called from the main thread. Otherwise it would need
3342// the lock and should use mCurrentState rather than mDrawingState.
3343void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003344 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003345 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003346 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003347
3348 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3349}
3350
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003351void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003352{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003353 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003354 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3355
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003356 if (isLayerTripleBufferingDisabled())
3357 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003358
3359 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003360 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003361 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003362 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003363 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3364 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003365 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003366}
3367
Dan Stozab90cf072015-03-05 11:05:59 -08003368void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3369{
3370 result.appendFormat("Static screen stats:\n");
3371 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3372 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3373 float percent = 100.0f *
3374 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3375 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3376 b + 1, bucketTimeSec, percent);
3377 }
3378 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3379 float percent = 100.0f *
3380 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3381 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3382 NUM_BUCKETS - 1, bucketTimeSec, percent);
3383}
3384
Dan Stozae77c7662016-05-13 11:37:28 -07003385void SurfaceFlinger::recordBufferingStats(const char* layerName,
3386 std::vector<OccupancyTracker::Segment>&& history) {
3387 Mutex::Autolock lock(mBufferingStatsMutex);
3388 auto& stats = mBufferingStats[layerName];
3389 for (const auto& segment : history) {
3390 if (!segment.usedThirdBuffer) {
3391 stats.twoBufferTime += segment.totalTime;
3392 }
3393 if (segment.occupancyAverage < 1.0f) {
3394 stats.doubleBufferedTime += segment.totalTime;
3395 } else if (segment.occupancyAverage < 2.0f) {
3396 stats.tripleBufferedTime += segment.totalTime;
3397 }
3398 ++stats.numSegments;
3399 stats.totalTime += segment.totalTime;
3400 }
3401}
3402
Brian Andersond6927fb2016-07-23 23:37:30 -07003403void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3404 result.appendFormat("Layer frame timestamps:\n");
3405
3406 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3407 const size_t count = currentLayers.size();
3408 for (size_t i=0 ; i<count ; i++) {
3409 currentLayers[i]->dumpFrameEvents(result);
3410 }
3411}
3412
Dan Stozae77c7662016-05-13 11:37:28 -07003413void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3414 result.append("Buffering stats:\n");
3415 result.append(" [Layer name] <Active time> <Two buffer> "
3416 "<Double buffered> <Triple buffered>\n");
3417 Mutex::Autolock lock(mBufferingStatsMutex);
3418 typedef std::tuple<std::string, float, float, float> BufferTuple;
3419 std::map<float, BufferTuple, std::greater<float>> sorted;
3420 for (const auto& statsPair : mBufferingStats) {
3421 const char* name = statsPair.first.c_str();
3422 const BufferingStats& stats = statsPair.second;
3423 if (stats.numSegments == 0) {
3424 continue;
3425 }
3426 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3427 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3428 stats.totalTime;
3429 float doubleBufferRatio = static_cast<float>(
3430 stats.doubleBufferedTime) / stats.totalTime;
3431 float tripleBufferRatio = static_cast<float>(
3432 stats.tripleBufferedTime) / stats.totalTime;
3433 sorted.insert({activeTime, {name, twoBufferRatio,
3434 doubleBufferRatio, tripleBufferRatio}});
3435 }
3436 for (const auto& sortedPair : sorted) {
3437 float activeTime = sortedPair.first;
3438 const BufferTuple& values = sortedPair.second;
3439 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3440 std::get<0>(values).c_str(), activeTime,
3441 std::get<1>(values), std::get<2>(values),
3442 std::get<3>(values));
3443 }
3444 result.append("\n");
3445}
3446
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003447void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3448 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3449
3450 // TODO: print out if wide-color mode is active or not
3451
3452 for (size_t d = 0; d < mDisplays.size(); d++) {
3453 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3454 int32_t hwcId = displayDevice->getHwcDisplayId();
3455 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3456 continue;
3457 }
3458
3459 result.appendFormat("Display %d color modes:\n", hwcId);
3460 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3461 for (auto&& mode : modes) {
3462 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3463 }
3464
3465 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3466 result.appendFormat(" Current color mode: %s (%d)\n",
3467 decodeColorMode(currentMode).c_str(), currentMode);
3468 }
3469 result.append("\n");
3470}
3471
Mathias Agopian74d211a2013-04-22 16:55:35 +02003472void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3473 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003474{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003475 bool colorize = false;
3476 if (index < args.size()
3477 && (args[index] == String16("--color"))) {
3478 colorize = true;
3479 index++;
3480 }
3481
3482 Colorizer colorizer(colorize);
3483
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003484 // figure out if we're stuck somewhere
3485 const nsecs_t now = systemTime();
3486 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3487 const nsecs_t inTransaction(mDebugInTransaction);
3488 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3489 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3490
3491 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003492 * Dump library configuration.
3493 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003494
3495 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003496 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003497 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003498 appendSfConfigString(result);
3499 appendUiConfigString(result);
3500 appendGuiConfigString(result);
3501 result.append("\n");
3502
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003503 result.append("\nWide-Color information:\n");
3504 dumpWideColorInfo(result);
3505
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003506 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003507 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003508 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003509 result.append(SyncFeatures::getInstance().toString());
3510 result.append("\n");
3511
Dan Stoza9e56aa02015-11-02 13:00:03 -08003512 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3513
Andy McFadden41d67d72014-04-25 16:58:34 -07003514 colorizer.bold(result);
3515 result.append("DispSync configuration: ");
3516 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003517 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003518 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003519 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003520 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003521 result.append("\n");
3522
Dan Stozab90cf072015-03-05 11:05:59 -08003523 // Dump static screen stats
3524 result.append("\n");
3525 dumpStaticScreenStats(result);
3526 result.append("\n");
3527
Dan Stozae77c7662016-05-13 11:37:28 -07003528 dumpBufferingStats(result);
3529
Andy McFadden4803b742012-09-24 19:07:20 -07003530 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003531 * Dump the visible layer list
3532 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003533 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003534 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003535 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003536 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003537 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003538 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003539
3540 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003541 * Dump Display state
3542 */
3543
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003544 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003545 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003546 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003547 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3548 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003549 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003550 }
3551
3552 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003553 * Dump SurfaceFlinger global state
3554 */
3555
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003556 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003557 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003558 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003559
Mathias Agopian888c8222012-08-04 21:10:38 -07003560 HWComposer& hwc(getHwComposer());
Polina Bondarenko80c02322017-04-10 10:15:42 +00003561 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003562
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003563 colorizer.bold(result);
3564 result.appendFormat("EGL implementation : %s\n",
3565 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3566 colorizer.reset(result);
3567 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003568 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003569
Mathias Agopian875d8e12013-06-07 15:35:48 -07003570 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003571
Mathias Agopian42977342012-08-05 00:40:46 -07003572 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003573 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3574 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003575 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003576 " last eglSwapBuffers() time: %f us\n"
3577 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003578 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003579 " refresh-rate : %f fps\n"
3580 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003581 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003582 " gpu_to_cpu_unsupported : %d\n"
3583 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003584 mLastSwapBufferTime/1000.0,
3585 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003586 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003587 1e9 / activeConfig->getVsyncPeriod(),
3588 activeConfig->getDpiX(),
3589 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003590 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003591
Mathias Agopian74d211a2013-04-22 16:55:35 +02003592 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003593 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003594
Mathias Agopian74d211a2013-04-22 16:55:35 +02003595 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003596 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003597
3598 /*
3599 * VSYNC state
3600 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003601 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003602 result.append("\n");
3603
3604 /*
3605 * HWC layer minidump
3606 */
3607 for (size_t d = 0; d < mDisplays.size(); d++) {
3608 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3609 int32_t hwcId = displayDevice->getHwcDisplayId();
3610 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3611 continue;
3612 }
3613
3614 result.appendFormat("Display %d HWC layers:\n", hwcId);
3615 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003616 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003617 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003618 });
Dan Stozae22aec72016-08-01 13:20:59 -07003619 result.append("\n");
3620 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003621
3622 /*
3623 * Dump HWComposer state
3624 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003625 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003626 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003627 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003628 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003629 result.appendFormat(" h/w composer %s\n",
3630 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003631 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003632
3633 /*
3634 * Dump gralloc state
3635 */
3636 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3637 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003638}
3639
Mathias Agopian13127d82013-03-05 17:47:11 -08003640const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003641SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003642 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003643 wp<IBinder> dpy;
3644 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3645 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3646 dpy = mDisplays.keyAt(i);
3647 break;
3648 }
3649 }
3650 if (dpy == NULL) {
3651 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3652 // Just use the primary display so we have something to return
3653 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3654 }
3655 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003656}
3657
Keun young Park63f165f2012-08-31 10:53:36 -07003658bool SurfaceFlinger::startDdmConnection()
3659{
3660 void* libddmconnection_dso =
3661 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3662 if (!libddmconnection_dso) {
3663 return false;
3664 }
3665 void (*DdmConnection_start)(const char* name);
3666 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003667 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003668 if (!DdmConnection_start) {
3669 dlclose(libddmconnection_dso);
3670 return false;
3671 }
3672 (*DdmConnection_start)(getServiceName());
3673 return true;
3674}
3675
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003676status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003677 switch (code) {
3678 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003679 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003681 case CLEAR_ANIMATION_FRAME_STATS:
3682 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003683 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003684 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003685 {
3686 // codes that require permission check
3687 IPCThreadState* ipc = IPCThreadState::self();
3688 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003689 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003690 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003691 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003692 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003693 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003695 break;
3696 }
Robert Carr1db73f62016-12-21 12:58:51 -08003697 /*
3698 * Calling setTransactionState is safe, because you need to have been
3699 * granted a reference to Client* and Handle* to do anything with it.
3700 *
3701 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3702 */
3703 case SET_TRANSACTION_STATE:
3704 case CREATE_SCOPED_CONNECTION:
3705 {
3706 return OK;
3707 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003708 case CAPTURE_SCREEN:
3709 {
3710 // codes that require permission check
3711 IPCThreadState* ipc = IPCThreadState::self();
3712 const int pid = ipc->getCallingPid();
3713 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003714 if ((uid != AID_GRAPHICS) &&
3715 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003716 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003717 return PERMISSION_DENIED;
3718 }
3719 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720 }
3721 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003722 return OK;
3723}
3724
3725status_t SurfaceFlinger::onTransact(
3726 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3727{
3728 status_t credentialCheck = CheckTransactCodeCredentials(code);
3729 if (credentialCheck != OK) {
3730 return credentialCheck;
3731 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3734 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003735 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003736 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003737 IPCThreadState* ipc = IPCThreadState::self();
3738 const int pid = ipc->getCallingPid();
3739 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003740 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003741 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003742 return PERMISSION_DENIED;
3743 }
3744 int n;
3745 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003746 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003747 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 return NO_ERROR;
3749 case 1002: // SHOW_UPDATES
3750 n = data.readInt32();
3751 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003752 invalidateHwcGeometry();
3753 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003754 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003756 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003757 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003758 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003759 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003760 setTransactionFlags(
3761 eTransactionNeeded|
3762 eDisplayTransactionNeeded|
3763 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003764 return NO_ERROR;
3765 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003766 case 1006:{ // send empty update
3767 signalRefresh();
3768 return NO_ERROR;
3769 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003770 case 1008: // toggle use of hw composer
3771 n = data.readInt32();
3772 mDebugDisableHWC = n ? 1 : 0;
3773 invalidateHwcGeometry();
3774 repaintEverything();
3775 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003776 case 1009: // toggle use of transform hint
3777 n = data.readInt32();
3778 mDebugDisableTransformHint = n ? 1 : 0;
3779 invalidateHwcGeometry();
3780 repaintEverything();
3781 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003783 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003784 reply->writeInt32(0);
3785 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003786 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003787 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003788 return NO_ERROR;
3789 case 1013: {
3790 Mutex::Autolock _l(mStateLock);
Polina Bondarenko80c02322017-04-10 10:15:42 +00003791 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003792 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003793 return NO_ERROR;
3794 }
3795 case 1014: {
3796 // daltonize
3797 n = data.readInt32();
3798 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003799 case 1:
3800 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3801 break;
3802 case 2:
3803 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3804 break;
3805 case 3:
3806 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3807 break;
3808 default:
3809 mDaltonizer.setType(ColorBlindnessType::None);
3810 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003811 }
3812 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003813 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003814 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003815 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003816 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003817 invalidateHwcGeometry();
3818 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003819 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003821 case 1015: {
3822 // apply a color matrix
3823 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003824 if (n) {
3825 // color matrix is sent as mat3 matrix followed by vec3
3826 // offset, then packed into a mat4 where the last row is
3827 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003828 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003829 for (size_t j = 0; j < 4; j++) {
3830 mColorMatrix[i][j] = data.readFloat();
3831 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003832 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003833 } else {
3834 mColorMatrix = mat4();
3835 }
3836 invalidateHwcGeometry();
3837 repaintEverything();
3838 return NO_ERROR;
3839 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003840 // This is an experimental interface
3841 // Needs to be shifted to proper binder interface when we productize
3842 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003843 n = data.readInt32();
3844 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003845 return NO_ERROR;
3846 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003847 case 1017: {
3848 n = data.readInt32();
3849 mForceFullDamage = static_cast<bool>(n);
3850 return NO_ERROR;
3851 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003852 case 1018: { // Modify Choreographer's phase offset
3853 n = data.readInt32();
3854 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3855 return NO_ERROR;
3856 }
3857 case 1019: { // Modify SurfaceFlinger's phase offset
3858 n = data.readInt32();
3859 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3860 return NO_ERROR;
3861 }
Irvel468051e2016-06-13 16:44:44 -07003862 case 1020: { // Layer updates interceptor
3863 n = data.readInt32();
3864 if (n) {
3865 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003866 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003867 }
3868 else{
3869 ALOGV("Interceptor disabled");
3870 mInterceptor.disable();
3871 }
3872 return NO_ERROR;
3873 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003874 case 1021: { // Disable HWC virtual displays
3875 n = data.readInt32();
3876 mUseHwcVirtualDisplays = !n;
3877 return NO_ERROR;
3878 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 }
3880 }
3881 return err;
3882}
3883
Mathias Agopian53331da2011-08-22 21:44:41 -07003884void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003885 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003886 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003887}
3888
Mathias Agopian59119e62010-10-11 12:37:43 -07003889// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003890// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003891// ---------------------------------------------------------------------------
3892
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003893/* The code below is here to handle b/8734824
3894 *
3895 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003896 * from the surfaceflinger thread to the calling binder thread, where they
3897 * are executed. This allows the calling thread in the calling process to be
3898 * reused and not depend on having "enough" binder threads to handle the
3899 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003900 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003901class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003902 /* Parts of GraphicProducerWrapper are run on two different threads,
3903 * communicating by sending messages via Looper but also by shared member
3904 * data. Coherence maintenance is subtle and in places implicit (ugh).
3905 *
3906 * Don't rely on Looper's sendMessage/handleMessage providing
3907 * release/acquire semantics for any data not actually in the Message.
3908 * Data going from surfaceflinger to binder threads needs to be
3909 * synchronized explicitly.
3910 *
3911 * Barrier open/wait do provide release/acquire semantics. This provides
3912 * implicit synchronization for data coming back from binder to
3913 * surfaceflinger threads.
3914 */
3915
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003916 sp<IGraphicBufferProducer> impl;
3917 sp<Looper> looper;
3918 status_t result;
3919 bool exitPending;
3920 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003921 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003922 uint32_t code;
3923 Parcel const* data;
3924 Parcel* reply;
3925
3926 enum {
3927 MSG_API_CALL,
3928 MSG_EXIT
3929 };
3930
3931 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003932 * Called on surfaceflinger thread. This is called by our "fake"
3933 * BpGraphicBufferProducer. We package the data and reply Parcel and
3934 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003935 */
3936 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003937 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003938 this->code = code;
3939 this->data = &data;
3940 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003941 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003942 // if we've exited, we run the message synchronously right here.
3943 // note (JH): as far as I can tell from looking at the code, this
3944 // never actually happens. if it does, i'm not sure if it happens
3945 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003946 handleMessage(Message(MSG_API_CALL));
3947 } else {
3948 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003949 // Prevent stores to this->{code, data, reply} from being
3950 // reordered later than the construction of Message.
3951 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003952 looper->sendMessage(this, Message(MSG_API_CALL));
3953 barrier.wait();
3954 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003955 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003956 }
3957
3958 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003959 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003960 * call the real BpGraphicBufferProducer.
3961 */
3962 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003963 int what = message.what;
3964 // Prevent reads below from happening before the read from Message
3965 atomic_thread_fence(memory_order_acquire);
3966 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003967 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003968 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003969 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003970 exitRequested = true;
3971 }
3972 }
3973
3974public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003975 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003976 : impl(impl),
3977 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003978 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003979 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003980 exitRequested(false),
3981 code(0),
3982 data(NULL),
3983 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003984 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003985
Jesse Hallb154c422014-07-13 12:47:02 -07003986 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003987 status_t waitForResponse() {
3988 do {
3989 looper->pollOnce(-1);
3990 } while (!exitRequested);
3991 return result;
3992 }
3993
Jesse Hallb154c422014-07-13 12:47:02 -07003994 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003995 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003996 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003997 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003998 // Ensure this->result is visible to the binder thread before it
3999 // handles the message.
4000 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004001 looper->sendMessage(this, Message(MSG_EXIT));
4002 }
4003};
4004
4005
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004006status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4007 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004008 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004009 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004010 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004011
4012 if (CC_UNLIKELY(display == 0))
4013 return BAD_VALUE;
4014
4015 if (CC_UNLIKELY(producer == 0))
4016 return BAD_VALUE;
4017
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004018 // if we have secure windows on this display, never allow the screen capture
4019 // unless the producer interface is local (i.e.: we can take a screenshot for
4020 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004021 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004022
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004023 // Convert to surfaceflinger's internal rotation type.
4024 Transform::orientation_flags rotationFlags;
4025 switch (rotation) {
4026 case ISurfaceComposer::eRotateNone:
4027 rotationFlags = Transform::ROT_0;
4028 break;
4029 case ISurfaceComposer::eRotate90:
4030 rotationFlags = Transform::ROT_90;
4031 break;
4032 case ISurfaceComposer::eRotate180:
4033 rotationFlags = Transform::ROT_180;
4034 break;
4035 case ISurfaceComposer::eRotate270:
4036 rotationFlags = Transform::ROT_270;
4037 break;
4038 default:
4039 rotationFlags = Transform::ROT_0;
4040 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4041 break;
4042 }
4043
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004044 class MessageCaptureScreen : public MessageBase {
4045 SurfaceFlinger* flinger;
4046 sp<IBinder> display;
4047 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004048 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004049 uint32_t reqWidth, reqHeight;
4050 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004051 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004052 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004053 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004054 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004055 public:
4056 MessageCaptureScreen(SurfaceFlinger* flinger,
4057 const sp<IBinder>& display,
4058 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004059 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004060 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004061 bool useIdentityTransform,
4062 Transform::orientation_flags rotation,
4063 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004064 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004065 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004066 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004067 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004068 rotation(rotation), result(PERMISSION_DENIED),
4069 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004070 {
4071 }
4072 status_t getResult() const {
4073 return result;
4074 }
4075 virtual bool handler() {
4076 Mutex::Autolock _l(flinger->mStateLock);
4077 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08004078 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004079 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004080 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004081 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004082 return true;
4083 }
4084 };
4085
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004086 // this creates a "fake" BBinder which will serve as a "fake" remote
4087 // binder to receive the marshaled calls and forward them to the
4088 // real remote (a BpGraphicBufferProducer)
4089 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4090
4091 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4092 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004093 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004094 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004095 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004096 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004097
4098 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004099 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004100 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004101 }
4102 return res;
4103}
4104
Mathias Agopian180f10d2013-04-10 22:55:41 -07004105
4106void SurfaceFlinger::renderScreenImplLocked(
4107 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004108 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004109 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004110 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004111{
4112 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004113 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004114
4115 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004116 const int32_t hw_w = hw->getWidth();
4117 const int32_t hw_h = hw->getHeight();
4118 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004119 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004120
Dan Stozac1879002014-05-22 15:59:05 -07004121 // if a default or invalid sourceCrop is passed in, set reasonable values
4122 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4123 !sourceCrop.isValid()) {
4124 sourceCrop.setLeftTop(Point(0, 0));
4125 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4126 }
4127
4128 // ensure that sourceCrop is inside screen
4129 if (sourceCrop.left < 0) {
4130 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4131 }
Dan Stozabe31f442014-06-11 11:20:54 -07004132 if (sourceCrop.right > hw_w) {
4133 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004134 }
4135 if (sourceCrop.top < 0) {
4136 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4137 }
Dan Stozabe31f442014-06-11 11:20:54 -07004138 if (sourceCrop.bottom > hw_h) {
4139 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004140 }
4141
Mathias Agopian180f10d2013-04-10 22:55:41 -07004142 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004143 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004144
4145 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004146 engine.setViewportAndProjection(
4147 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004148 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004149
4150 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004151 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004152
Robert Carr1f0a16a2016-10-24 16:27:39 -07004153 // We loop through the first level of layers without traversing,
4154 // as we need to interpret min/max layer Z in the top level Z space.
4155 for (const auto& layer : mDrawingState.layersSortedByZ) {
4156 if (layer->getLayerStack() != hw->getLayerStack()) {
4157 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004158 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004159 const Layer::State& state(layer->getDrawingState());
4160 if (state.z < minLayerZ || state.z > maxLayerZ) {
4161 continue;
4162 }
4163 layer->traverseInZOrder([&](Layer* layer) {
4164 if (!layer->isVisible()) {
4165 return;
4166 }
4167 if (filtering) layer->setFiltering(true);
4168 layer->draw(hw, useIdentityTransform);
4169 if (filtering) layer->setFiltering(false);
4170 });
4171 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004172
Mathias Agopian931bda12013-08-28 18:11:46 -07004173 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004174}
4175
4176
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004177status_t SurfaceFlinger::captureScreenImplLocked(
4178 const sp<const DisplayDevice>& hw,
4179 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004180 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004181 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004182 bool useIdentityTransform, Transform::orientation_flags rotation,
4183 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004184{
4185 ATRACE_CALL();
4186
Mathias Agopian180f10d2013-04-10 22:55:41 -07004187 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004188 uint32_t hw_w = hw->getWidth();
4189 uint32_t hw_h = hw->getHeight();
4190
4191 if (rotation & Transform::ROT_90) {
4192 std::swap(hw_w, hw_h);
4193 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004194
Mathias Agopian180f10d2013-04-10 22:55:41 -07004195 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4196 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4197 reqWidth, reqHeight, hw_w, hw_h);
4198 return BAD_VALUE;
4199 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004200
Mathias Agopian180f10d2013-04-10 22:55:41 -07004201 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4202 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4203
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004204 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004205 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004206 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004207 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4208 (state.z < minLayerZ || state.z > maxLayerZ)) {
4209 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004210 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004211 layer->traverseInZOrder([&](Layer *layer) {
4212 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4213 layer->isSecure());
4214 });
4215 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004216
4217 if (!isLocalScreenshot && secureLayerIsVisible) {
4218 ALOGW("FB is protected: PERMISSION_DENIED");
4219 return PERMISSION_DENIED;
4220 }
4221
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004222 // create a surface (because we're a producer, and we need to
4223 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004224 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004225
4226 // Put the screenshot Surface into async mode so that
4227 // Layer::headFenceHasSignaled will always return true and we'll latch the
4228 // first buffer regardless of whether or not its acquire fence has
4229 // signaled. This is needed to avoid a race condition in the rotation
4230 // animation. See b/30209608
4231 sur->setAsyncMode(true);
4232
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004233 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004234
Michael Lentine5a16a622015-05-21 13:48:24 -07004235 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4236 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004237 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4238 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004239
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004240 int err = 0;
4241 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004242 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004243 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4244 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004245
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004246 if (err == NO_ERROR) {
4247 ANativeWindowBuffer* buffer;
4248 /* TODO: Once we have the sync framework everywhere this can use
4249 * server-side waits on the fence that dequeueBuffer returns.
4250 */
4251 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4252 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004253 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004254 // create an EGLImage from the buffer so we can later
4255 // turn it into a texture
4256 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4257 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4258 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004259 // this binds the given EGLImage as a framebuffer for the
4260 // duration of this scope.
4261 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4262 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004263 // this will in fact render into our dequeued buffer
4264 // via an FBO, which means we didn't have to create
4265 // an EGLSurface and therefore we're not
4266 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004267 renderScreenImplLocked(
4268 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4269 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004270
Riley Andrews86639902014-08-15 12:27:24 -07004271 // Attempt to create a sync khr object that can produce a sync point. If that
4272 // isn't available, create a non-dupable sync object in the fallback path and
4273 // wait on it directly.
4274 EGLSyncKHR sync;
4275 if (!DEBUG_SCREENSHOTS) {
4276 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004277 // native fence fd will not be populated until flush() is done.
4278 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004279 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004280 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004281 }
Riley Andrews86639902014-08-15 12:27:24 -07004282 if (sync != EGL_NO_SYNC_KHR) {
4283 // get the sync fd
4284 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4285 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4286 ALOGW("captureScreen: failed to dup sync khr object");
4287 syncFd = -1;
4288 }
4289 eglDestroySyncKHR(mEGLDisplay, sync);
4290 } else {
4291 // fallback path
4292 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4293 if (sync != EGL_NO_SYNC_KHR) {
4294 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4295 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4296 EGLint eglErr = eglGetError();
4297 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4298 ALOGW("captureScreen: fence wait timed out");
4299 } else {
4300 ALOGW_IF(eglErr != EGL_SUCCESS,
4301 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4302 }
4303 eglDestroySyncKHR(mEGLDisplay, sync);
4304 } else {
4305 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4306 }
4307 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004308 if (DEBUG_SCREENSHOTS) {
4309 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4310 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4311 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4312 hw, minLayerZ, maxLayerZ);
4313 delete [] pixels;
4314 }
4315
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004316 } else {
4317 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4318 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004319 window->cancelBuffer(window, buffer, syncFd);
4320 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004321 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004322 // destroy our image
4323 eglDestroyImageKHR(mEGLDisplay, image);
4324 } else {
4325 result = BAD_VALUE;
4326 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004327 if (buffer) {
4328 // queueBuffer takes ownership of syncFd
4329 result = window->queueBuffer(window, buffer, syncFd);
4330 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004331 }
4332 } else {
4333 result = BAD_VALUE;
4334 }
4335 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4336 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004337
Mathias Agopian74c40c02010-09-29 13:02:36 -07004338 return result;
4339}
4340
Mathias Agopiand5556842013-09-19 17:08:37 -07004341void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004342 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004343 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004344 for (size_t y=0 ; y<h ; y++) {
4345 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4346 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004347 if (p[x] != 0xFF000000) return;
4348 }
4349 }
4350 ALOGE("*** we just took a black screenshot ***\n"
4351 "requested minz=%d, maxz=%d, layerStack=%d",
4352 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004353
Robert Carr2047fae2016-11-28 14:09:09 -08004354 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004355 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004356 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004357 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4358 state.z <= maxLayerZ) {
4359 layer->traverseInZOrder([&](Layer* layer) {
4360 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4361 layer->isVisible() ? '+' : '-',
4362 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004363 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004364 i++;
4365 });
4366 }
4367 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004368 }
4369}
4370
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004371// ---------------------------------------------------------------------------
4372
Robert Carr2047fae2016-11-28 14:09:09 -08004373void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4374 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004375}
4376
Robert Carr2047fae2016-11-28 14:09:09 -08004377void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4378 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004379}
4380
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004382
4383
4384#if defined(__gl_h_)
4385#error "don't include gl/gl.h in this file"
4386#endif
4387
4388#if defined(__gl2_h_)
4389#error "don't include gl2/gl2.h in this file"
4390#endif