blob: e137a784df9996934e1685770f6c0cb5e185dff5 [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>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopiana4912602012-07-12 14:25:33 -070079#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070080#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070081#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Mathias Agopianff2ed702013-09-01 21:36:12 -070083#include "Effects/Daltonizer.h"
84
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070087
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090089#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#define DISPLAY_COUNT 1
92
Mathias Agopianfee2b462013-07-03 12:34:01 -070093/*
94 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
95 * black pixels.
96 */
97#define DEBUG_SCREENSHOTS false
98
Mathias Agopianca088332013-03-28 17:44:13 -070099EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107// ---------------------------------------------------------------------------
108
Mathias Agopian99b49842011-06-27 16:05:52 -0700109const String16 sHardwareTest("android.permission.HARDWARE_TEST");
110const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
111const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
112const String16 sDump("android.permission.DUMP");
113
114// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800115int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
116int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700117bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700118int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700119bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800120uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800121bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800122bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800123int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600124bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700127 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700129 mTransactionPending(false),
130 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700131 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700132 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700133 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800134 mHwc(nullptr),
135 mRealHwc(nullptr),
136 mVrHwc(nullptr),
137 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800153 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700157 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700161 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800162 mNumLayers(0),
163 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800165 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800166
167 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
169
170 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
172
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700176 useContextPriority = getBool< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::useContextPriority>(false);
178
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700179 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
181
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700182 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
184
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
186 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
187
Steven Thomas050b2c82017-03-06 11:45:16 -0800188 // Vr flinger is only enabled on Daydream ready devices.
189 useVrFlinger = getBool< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::useVrFlinger>(false);
191
Fabien Sanglard1971b632017-03-10 14:50:03 -0800192 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
193 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
194
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195 hasWideColorDisplay =
196 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 // debugging stuff...
199 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700202 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 property_get("debug.sf.showupdates", value, "0");
205 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 property_get("debug.sf.ddms", value, "0");
208 mDebugDDMS = atoi(value);
209 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700210 if (!startDdmConnection()) {
211 // start failed, and DDMS debugging not enabled
212 mDebugDDMS = 0;
213 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700214 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700215 ALOGI_IF(mDebugRegion, "showupdates enabled");
216 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700217
218 property_get("debug.sf.disable_backpressure", value, "0");
219 mPropagateBackpressure = !atoi(value);
220 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700221
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800222 property_get("debug.sf.enable_hwc_vds", value, "0");
223 mUseHwcVirtualDisplays = atoi(value);
224 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800225
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800226 property_get("ro.sf.disable_triple_buffer", value, "1");
227 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800228 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700229
230 property_get("persist.sys.sf.color_saturation", value, "1.0");
231 mSaturation = atof(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232}
233
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800234void SurfaceFlinger::onFirstRef()
235{
236 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800237}
238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239SurfaceFlinger::~SurfaceFlinger()
240{
Mathias Agopiana4912602012-07-12 14:25:33 -0700241 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
242 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
243 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244}
245
Dan Stozac7014012014-02-14 15:03:43 -0800246void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247{
248 // the window manager died on us. prepare its eulogy.
249
Andy McFadden13a082e2012-08-24 10:16:42 -0700250 // restore initial conditions (default device unblank, etc)
251 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252
253 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700254 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800255}
256
Robert Carr1db73f62016-12-21 12:58:51 -0800257static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700258 status_t err = client->initCheck();
259 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800260 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 }
Robert Carr1db73f62016-12-21 12:58:51 -0800262 return nullptr;
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
266 return initClient(new Client(this));
267}
268
269sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
270 const sp<IGraphicBufferProducer>& gbp) {
271 if (authenticateSurfaceTexture(gbp) == false) {
272 return nullptr;
273 }
274 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
275 if (layer == nullptr) {
276 return nullptr;
277 }
278
279 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280}
281
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700282sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
283 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700284{
285 class DisplayToken : public BBinder {
286 sp<SurfaceFlinger> flinger;
287 virtual ~DisplayToken() {
288 // no more references, this display must be terminated
289 Mutex::Autolock _l(flinger->mStateLock);
290 flinger->mCurrentState.displays.removeItem(this);
291 flinger->setTransactionFlags(eDisplayTransactionNeeded);
292 }
293 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700294 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295 : flinger(flinger) {
296 }
297 };
298
299 sp<BBinder> token = new DisplayToken(this);
300
301 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700302 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700303 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700304 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700305 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700306 return token;
307}
308
Jesse Hall6c913be2013-08-08 12:15:49 -0700309void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
310 Mutex::Autolock _l(mStateLock);
311
312 ssize_t idx = mCurrentState.displays.indexOfKey(display);
313 if (idx < 0) {
314 ALOGW("destroyDisplay: invalid display token");
315 return;
316 }
317
318 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
319 if (!info.isVirtualDisplay()) {
320 ALOGE("destroyDisplay called for non-virtual display");
321 return;
322 }
Irvelffc9efc2016-07-27 15:16:37 -0700323 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700324 mCurrentState.displays.removeItemsAt(idx);
325 setTransactionFlags(eDisplayTransactionNeeded);
326}
327
Jesse Hall692c7232012-11-08 15:41:56 -0800328void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800329 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 ALOGW_IF(mBuiltinDisplays[type],
331 "Overwriting display token for display type %d", type);
332 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800333 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700334 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800335 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700336 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800337}
338
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700340 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
342 return NULL;
343 }
Jesse Hall692c7232012-11-08 15:41:56 -0800344 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345}
346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347void SurfaceFlinger::bootFinished()
348{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700349 if (mStartPropertySetThread->join() != NO_ERROR) {
350 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800351 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 const nsecs_t now = systemTime();
353 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000354 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700355 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700356
357 // wait patiently for the window manager death
358 const String16 name("window");
359 sp<IBinder> window(defaultServiceManager()->getService(name));
360 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700361 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700362 }
363
Steven Thomas050b2c82017-03-06 11:45:16 -0800364 if (mVrFlinger) {
365 mVrFlinger->OnBootFinished();
366 }
367
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700368 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700369 // formerly we would just kill the process, but we now ask it to exit so it
370 // can choose where to stop the animation.
371 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700372
373 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
374 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
375 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376}
377
Mathias Agopian3f844832013-08-07 21:24:32 -0700378void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700380 RenderEngine& engine;
381 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700382 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700383 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
384 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700385 }
386 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700388 return true;
389 }
390 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700391 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392}
393
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394class DispSyncSource : public VSyncSource, private DispSync::Callback {
395public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700396 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000397 const char* name) :
398 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700399 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700400 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000401 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
402 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700403 mDispSync(dispSync),
404 mCallbackMutex(),
405 mCallback(),
406 mVsyncMutex(),
407 mPhaseOffset(phaseOffset),
408 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700409
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 virtual ~DispSyncSource() {}
411
412 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700413 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000415 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error registering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700421 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700422 } else {
423 status_t err = mDispSync->removeEventListener(
424 static_cast<DispSync::Callback*>(this));
425 if (err != NO_ERROR) {
426 ALOGE("error unregistering vsync callback: %s (%d)",
427 strerror(-err), err);
428 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700431 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
433
434 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 mCallback = callback;
437 }
438
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 virtual void setPhaseOffset(nsecs_t phaseOffset) {
440 Mutex::Autolock lock(mVsyncMutex);
441
442 // Normalize phaseOffset to [0, period)
443 auto period = mDispSync->getPeriod();
444 phaseOffset %= period;
445 if (phaseOffset < 0) {
446 // If we're here, then phaseOffset is in (-period, 0). After this
447 // operation, it will be in (0, period)
448 phaseOffset += period;
449 }
450 mPhaseOffset = phaseOffset;
451
452 // If we're not enabled, we don't need to mess with the listeners
453 if (!mEnabled) {
454 return;
455 }
456
457 // Remove the listener with the old offset
458 status_t err = mDispSync->removeEventListener(
459 static_cast<DispSync::Callback*>(this));
460 if (err != NO_ERROR) {
461 ALOGE("error unregistering vsync callback: %s (%d)",
462 strerror(-err), err);
463 }
464
465 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000466 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 static_cast<DispSync::Callback*>(this));
468 if (err != NO_ERROR) {
469 ALOGE("error registering vsync callback: %s (%d)",
470 strerror(-err), err);
471 }
472 }
473
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474private:
475 virtual void onDispSyncEvent(nsecs_t when) {
476 sp<VSyncSource::Callback> callback;
477 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 callback = mCallback;
480
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700481 if (mTraceVsync) {
482 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700483 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700484 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485 }
486
487 if (callback != NULL) {
488 callback->onVSyncEvent(when);
489 }
490 }
491
Tim Murray4a4e4a22016-04-19 16:29:23 +0000492 const char* const mName;
493
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 int mValue;
495
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700496 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700497 const String8 mVsyncOnLabel;
498 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700501
502 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504
505 Mutex mVsyncMutex; // Protects the following
506 nsecs_t mPhaseOffset;
507 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508};
509
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700510class InjectVSyncSource : public VSyncSource {
511public:
512 InjectVSyncSource() {}
513
514 virtual ~InjectVSyncSource() {}
515
516 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
517 std::lock_guard<std::mutex> lock(mCallbackMutex);
518 mCallback = callback;
519 }
520
521 virtual void onInjectSyncEvent(nsecs_t when) {
522 std::lock_guard<std::mutex> lock(mCallbackMutex);
523 mCallback->onVSyncEvent(when);
524 }
525
526 virtual void setVSyncEnabled(bool) {}
527 virtual void setPhaseOffset(nsecs_t) {}
528
529private:
530 std::mutex mCallbackMutex; // Protects the following
531 sp<VSyncSource::Callback> mCallback;
532};
533
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534// Do not call property_set on main thread which will be blocked by init
535// Use StartPropertySetThread instead.
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 Murray22752852017-05-04 13:38:49 -0700558 // set EventThread and 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 }
Tim Murray22752852017-05-04 13:38:49 -0700564 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
565 ALOGE("Couldn't set SCHED_FIFO for EventThread");
566 }
Tim Murray41a38532016-06-22 12:42:10 -0700567
Dan Stoza9e56aa02015-11-02 13:00:03 -0800568 // Get a RenderEngine for the given display / config (can't fail)
569 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700570 HAL_PIXEL_FORMAT_RGBA_8888,
571 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800572 }
573
574 // Drop the state lock while we initialize the hardware composer. We drop
575 // the lock because on creation, it will call back into SurfaceFlinger to
576 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800577 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
578 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800579 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800580 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
582
Jesse Hall692c7232012-11-08 15:41:56 -0800583 Mutex::Autolock _l(mStateLock);
584
Steven Thomas050b2c82017-03-06 11:45:16 -0800585 if (useVrFlinger) {
586 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700587 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800588 mVrFlingerRequestsDisplay = requestDisplay;
589 signalTransaction();
590 };
591 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
592 vrFlingerRequestDisplayCallback);
593 if (!mVrFlinger) {
594 ALOGE("Failed to start vrflinger");
595 }
596 }
597
Mathias Agopian875d8e12013-06-07 15:35:48 -0700598 // retrieve the EGL context that was selected/created
599 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700600
Mathias Agopianda27af92012-09-13 18:17:13 -0700601 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
602 "couldn't create EGLContext");
603
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604 // make the GLContext current so that we can create textures when creating
605 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700606 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700607
Jamie Gennisd1700752013-10-14 12:22:52 -0700608 mEventControlThread = new EventControlThread(this);
609 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
610
Mathias Agopian92a979a2012-08-02 18:32:23 -0700611 // initialize our drawing state
612 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700613
Andy McFadden13a082e2012-08-24 10:16:42 -0700614 // set initial conditions (e.g. unblank default device)
615 initializeDisplays();
616
Dan Stoza4e637772016-07-28 13:31:51 -0700617 mRenderEngine->primeCache();
618
Wei Wangf9b05ee2017-07-19 20:59:39 -0700619 // Inform native graphics APIs whether the present timestamp is supported:
620 if (getHwComposer().hasCapability(
621 HWC2::Capability::PresentFenceIsNotReliable)) {
622 mStartPropertySetThread = new StartPropertySetThread(false);
623 } else {
624 mStartPropertySetThread = new StartPropertySetThread(true);
625 }
626
627 if (mStartPropertySetThread->Start() != NO_ERROR) {
628 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800629 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800630
Dan Stoza9e56aa02015-11-02 13:00:03 -0800631 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700632}
633
Mathias Agopiana67e4182012-06-19 17:26:12 -0700634void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800635 // Start boot animation service by setting a property mailbox
636 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700637 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800638 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700639 if (mStartPropertySetThread->join() != NO_ERROR) {
640 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800641 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700642}
643
Mathias Agopian875d8e12013-06-07 15:35:48 -0700644size_t SurfaceFlinger::getMaxTextureSize() const {
645 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700646}
647
Mathias Agopian875d8e12013-06-07 15:35:48 -0700648size_t SurfaceFlinger::getMaxViewportDims() const {
649 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700650}
651
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800652// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800653
Jamie Gennis582270d2011-08-17 18:19:00 -0700654bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800655 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800656 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800657 return authenticateSurfaceTextureLocked(bufferProducer);
658}
659
660bool SurfaceFlinger::authenticateSurfaceTextureLocked(
661 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800662 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700663 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800664}
665
Brian Anderson6b376712017-04-04 10:51:39 -0700666status_t SurfaceFlinger::getSupportedFrameTimestamps(
667 std::vector<FrameEvent>* outSupported) const {
668 *outSupported = {
669 FrameEvent::REQUESTED_PRESENT,
670 FrameEvent::ACQUIRE,
671 FrameEvent::LATCH,
672 FrameEvent::FIRST_REFRESH_START,
673 FrameEvent::LAST_REFRESH_START,
674 FrameEvent::GPU_COMPOSITION_DONE,
675 FrameEvent::DEQUEUE_READY,
676 FrameEvent::RELEASE,
677 };
678 if (!getHwComposer().hasCapability(
679 HWC2::Capability::PresentFenceIsNotReliable)) {
680 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
681 }
682 return NO_ERROR;
683}
684
Dan Stoza7f7da322014-05-02 15:26:25 -0700685status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
686 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700687 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700688 return BAD_VALUE;
689 }
690
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500691 if (!display.get())
692 return NAME_NOT_FOUND;
693
Jesse Hall692c7232012-11-08 15:41:56 -0800694 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700695 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800696 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700697 type = i;
698 break;
699 }
700 }
701
702 if (type < 0) {
703 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700704 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700705
Mathias Agopian8b736f12012-08-13 17:54:26 -0700706 // TODO: Not sure if display density should handled by SF any longer
707 class Density {
708 static int getDensityFromProperty(char const* propName) {
709 char property[PROPERTY_VALUE_MAX];
710 int density = 0;
711 if (property_get(propName, property, NULL) > 0) {
712 density = atoi(property);
713 }
714 return density;
715 }
716 public:
717 static int getEmuDensity() {
718 return getDensityFromProperty("qemu.sf.lcd_density"); }
719 static int getBuildDensity() {
720 return getDensityFromProperty("ro.sf.lcd_density"); }
721 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700722
Dan Stoza7f7da322014-05-02 15:26:25 -0700723 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700724
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700726 DisplayInfo info = DisplayInfo();
727
Dan Stoza9e56aa02015-11-02 13:00:03 -0800728 float xdpi = hwConfig->getDpiX();
729 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700730
731 if (type == DisplayDevice::DISPLAY_PRIMARY) {
732 // The density of the device is provided by a build property
733 float density = Density::getBuildDensity() / 160.0f;
734 if (density == 0) {
735 // the build doesn't provide a density -- this is wrong!
736 // use xdpi instead
737 ALOGE("ro.sf.lcd_density must be defined as a build property");
738 density = xdpi / 160.0f;
739 }
740 if (Density::getEmuDensity()) {
741 // if "qemu.sf.lcd_density" is specified, it overrides everything
742 xdpi = ydpi = density = Density::getEmuDensity();
743 density /= 160.0f;
744 }
745 info.density = density;
746
747 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000748 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
749 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700750 } else {
751 // TODO: where should this value come from?
752 static const int TV_DENSITY = 213;
753 info.density = TV_DENSITY / 160.0f;
754 info.orientation = 0;
755 }
756
Dan Stoza9e56aa02015-11-02 13:00:03 -0800757 info.w = hwConfig->getWidth();
758 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700759 info.xdpi = xdpi;
760 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800761 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900762 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800763
Andy McFadden91b2ca82014-06-13 14:04:23 -0700764 // This is how far in advance a buffer must be queued for
765 // presentation at a given time. If you want a buffer to appear
766 // on the screen at time N, you must submit the buffer before
767 // (N - presentationDeadline).
768 //
769 // Normally it's one full refresh period (to give SF a chance to
770 // latch the buffer), but this can be reduced by configuring a
771 // DispSync offset. Any additional delays introduced by the hardware
772 // composer or panel must be accounted for here.
773 //
774 // We add an additional 1ms to allow for processing time and
775 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800776 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800777 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700778
779 // All non-virtual displays are currently considered secure.
780 info.secure = true;
781
Michael Wright28f24d02016-07-12 13:30:53 -0700782 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783 }
784
Dan Stoza7f7da322014-05-02 15:26:25 -0700785 return NO_ERROR;
786}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700787
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800788status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700789 DisplayStatInfo* stats) {
790 if (stats == NULL) {
791 return BAD_VALUE;
792 }
793
794 // FIXME for now we always return stats for the primary display
795 memset(stats, 0, sizeof(*stats));
796 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
797 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
798 return NO_ERROR;
799}
800
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700801int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800802 if (display == NULL) {
803 ALOGE("%s : display is NULL", __func__);
804 return BAD_VALUE;
805 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700806
807 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700808 if (device != NULL) {
809 return device->getActiveConfig();
810 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700811
Dan Stoza24a42e92015-03-09 10:04:11 -0700812 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700813}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700814
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700815void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
816 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
817 this);
818 int32_t type = hw->getDisplayType();
819 int currentMode = hw->getActiveConfig();
820
821 if (mode == currentMode) {
822 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
823 return;
824 }
825
826 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
827 ALOGW("Trying to set config for virtual display");
828 return;
829 }
830
831 hw->setActiveConfig(mode);
832 getHwComposer().setActiveConfig(type, mode);
833}
834
835status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
836 class MessageSetActiveConfig: public MessageBase {
837 SurfaceFlinger& mFlinger;
838 sp<IBinder> mDisplay;
839 int mMode;
840 public:
841 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
842 int mode) :
843 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
844 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700845 Vector<DisplayInfo> configs;
846 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700847 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700848 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700849 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700850 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700851 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700852 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
853 if (hw == NULL) {
854 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700855 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700856 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
857 ALOGW("Attempt to set active config = %d for virtual display",
858 mMode);
859 } else {
860 mFlinger.setActiveConfigInternal(hw, mMode);
861 }
862 return true;
863 }
864 };
865 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
866 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700867 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700868}
Michael Wright28f24d02016-07-12 13:30:53 -0700869status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
870 Vector<android_color_mode_t>* outColorModes) {
871 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
872 return BAD_VALUE;
873 }
874
875 if (!display.get()) {
876 return NAME_NOT_FOUND;
877 }
878
879 int32_t type = NAME_NOT_FOUND;
880 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
881 if (display == mBuiltinDisplays[i]) {
882 type = i;
883 break;
884 }
885 }
886
887 if (type < 0) {
888 return type;
889 }
890
891 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
892 outColorModes->clear();
893 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
894
895 return NO_ERROR;
896}
897
898android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700899 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700900 if (device != nullptr) {
901 return device->getActiveColorMode();
902 }
903 return static_cast<android_color_mode_t>(BAD_VALUE);
904}
905
906void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
907 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700908 int32_t type = hw->getDisplayType();
909 android_color_mode_t currentMode = hw->getActiveColorMode();
910
911 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700912 return;
913 }
914
915 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
916 ALOGW("Trying to set config for virtual display");
917 return;
918 }
919
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600920 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
921 hw->getDisplayType());
922
Michael Wright28f24d02016-07-12 13:30:53 -0700923 hw->setActiveColorMode(mode);
924 getHwComposer().setActiveColorMode(type, mode);
925}
926
927
928status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
929 android_color_mode_t colorMode) {
930 class MessageSetActiveColorMode: public MessageBase {
931 SurfaceFlinger& mFlinger;
932 sp<IBinder> mDisplay;
933 android_color_mode_t mMode;
934 public:
935 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
936 android_color_mode_t mode) :
937 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
938 virtual bool handler() {
939 Vector<android_color_mode_t> modes;
940 mFlinger.getDisplayColorModes(mDisplay, &modes);
941 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
942 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600943 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
944 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700945 return true;
946 }
947 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
948 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600949 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
950 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700951 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600952 ALOGW("Attempt to set active color mode %s %d for virtual display",
953 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700954 } else {
955 mFlinger.setActiveColorModeInternal(hw, mMode);
956 }
957 return true;
958 }
959 };
960 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
961 postMessageSync(msg);
962 return NO_ERROR;
963}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700964
Svetoslavd85084b2014-03-20 10:28:31 -0700965status_t SurfaceFlinger::clearAnimationFrameStats() {
966 Mutex::Autolock _l(mStateLock);
967 mAnimFrameTracker.clearStats();
968 return NO_ERROR;
969}
970
971status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
972 Mutex::Autolock _l(mStateLock);
973 mAnimFrameTracker.getStats(outStats);
974 return NO_ERROR;
975}
976
Dan Stozac4f471e2016-03-24 09:31:08 -0700977status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
978 HdrCapabilities* outCapabilities) const {
979 Mutex::Autolock _l(mStateLock);
980
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700981 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700982 if (displayDevice == nullptr) {
983 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
984 return BAD_VALUE;
985 }
986
987 std::unique_ptr<HdrCapabilities> capabilities =
988 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
989 if (capabilities) {
990 std::swap(*outCapabilities, *capabilities);
991 } else {
992 return BAD_VALUE;
993 }
994
995 return NO_ERROR;
996}
997
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700998status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
999 if (enable == mInjectVSyncs) {
1000 return NO_ERROR;
1001 }
1002
1003 if (enable) {
1004 mInjectVSyncs = enable;
1005 ALOGV("VSync Injections enabled");
1006 if (mVSyncInjector.get() == nullptr) {
1007 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001008 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001009 }
1010 mEventQueue.setEventThread(mInjectorEventThread);
1011 } else {
1012 mInjectVSyncs = enable;
1013 ALOGV("VSync Injections disabled");
1014 mEventQueue.setEventThread(mSFEventThread);
1015 mVSyncInjector.clear();
1016 }
1017 return NO_ERROR;
1018}
1019
1020status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1021 if (!mInjectVSyncs) {
1022 ALOGE("VSync Injections not enabled");
1023 return BAD_VALUE;
1024 }
1025 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1026 ALOGV("Injecting VSync inside SurfaceFlinger");
1027 mVSyncInjector->onInjectSyncEvent(when);
1028 }
1029 return NO_ERROR;
1030}
1031
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001032// ----------------------------------------------------------------------------
1033
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001034sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1035 ISurfaceComposer::VsyncSource vsyncSource) {
1036 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1037 return mSFEventThread->createEventConnection();
1038 } else {
1039 return mEventThread->createEventConnection();
1040 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001041}
1042
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001044
1045void SurfaceFlinger::waitForEvent() {
1046 mEventQueue.waitMessage();
1047}
1048
1049void SurfaceFlinger::signalTransaction() {
1050 mEventQueue.invalidate();
1051}
1052
1053void SurfaceFlinger::signalLayerUpdate() {
1054 mEventQueue.invalidate();
1055}
1056
1057void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001058 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001059 mEventQueue.refresh();
1060}
1061
1062status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001063 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001064 return mEventQueue.postMessage(msg, reltime);
1065}
1066
1067status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001068 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001069 status_t res = mEventQueue.postMessage(msg, reltime);
1070 if (res == NO_ERROR) {
1071 msg->wait();
1072 }
1073 return res;
1074}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001076void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001077 do {
1078 waitForEvent();
1079 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001080}
1081
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082void SurfaceFlinger::enableHardwareVsync() {
1083 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001084 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001085 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001086 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1087 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001089 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001090}
1091
Jesse Hall948fe0c2013-10-14 12:56:09 -07001092void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093 Mutex::Autolock _l(mHWVsyncLock);
1094
Jesse Hall948fe0c2013-10-14 12:56:09 -07001095 if (makeAvailable) {
1096 mHWVsyncAvailable = true;
1097 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001098 // Hardware vsync is not currently available, so abort the resync
1099 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001100 return;
1101 }
1102
Dan Stoza9e56aa02015-11-02 13:00:03 -08001103 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1104 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105
1106 mPrimaryDispSync.reset();
1107 mPrimaryDispSync.setPeriod(period);
1108
1109 if (!mPrimaryHWVsyncEnabled) {
1110 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001111 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1112 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001113 mPrimaryHWVsyncEnabled = true;
1114 }
1115}
1116
Jesse Hall948fe0c2013-10-14 12:56:09 -07001117void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001118 Mutex::Autolock _l(mHWVsyncLock);
1119 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001120 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1121 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001122 mPrimaryDispSync.endResync();
1123 mPrimaryHWVsyncEnabled = false;
1124 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001125 if (makeUnavailable) {
1126 mHWVsyncAvailable = false;
1127 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001128}
1129
Tim Murray4a4e4a22016-04-19 16:29:23 +00001130void SurfaceFlinger::resyncWithRateLimit() {
1131 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001132
1133 // No explicit locking is needed here since EventThread holds a lock while calling this method
1134 static nsecs_t sLastResyncAttempted = 0;
1135 const nsecs_t now = systemTime();
1136 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001137 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001138 }
Dan Stoza57164302017-05-08 14:03:54 -07001139 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001140}
1141
Steven Thomas3cfac282017-02-06 12:29:30 -08001142void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1143 nsecs_t timestamp) {
1144 Mutex::Autolock lock(mStateLock);
1145 // Ignore any vsyncs from the non-active hardware composer.
1146 if (composer != mHwc) {
1147 return;
1148 }
1149
Jamie Gennisd1700752013-10-14 12:22:52 -07001150 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001151
Jamie Gennisd1700752013-10-14 12:22:52 -07001152 { // Scope for the lock
1153 Mutex::Autolock _l(mHWVsyncLock);
1154 if (type == 0 && mPrimaryHWVsyncEnabled) {
1155 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001156 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001157 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001158
1159 if (needsHwVsync) {
1160 enableHardwareVsync();
1161 } else {
1162 disableHardwareVsync(false);
1163 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001164}
1165
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001166void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001167 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001168 *compositorTiming = mCompositorTiming;
1169}
1170
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001171void SurfaceFlinger::createDefaultDisplayDevice() {
1172 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1173 wp<IBinder> token = mBuiltinDisplays[type];
1174
1175 // All non-virtual displays are currently considered secure.
1176 const bool isSecure = true;
1177
1178 sp<IGraphicBufferProducer> producer;
1179 sp<IGraphicBufferConsumer> consumer;
1180 BufferQueue::createBufferQueue(&producer, &consumer);
1181
1182 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1183
1184 bool hasWideColorModes = false;
1185 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1186 for (android_color_mode_t colorMode : modes) {
1187 switch (colorMode) {
1188 case HAL_COLOR_MODE_DISPLAY_P3:
1189 case HAL_COLOR_MODE_ADOBE_RGB:
1190 case HAL_COLOR_MODE_DCI_P3:
1191 hasWideColorModes = true;
1192 break;
1193 default:
1194 break;
1195 }
1196 }
1197 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1198 token, fbs, producer, mRenderEngine->getEGLConfig(),
1199 hasWideColorModes && hasWideColorDisplay);
1200 mDisplays.add(token, hw);
1201 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1202 if (hasWideColorModes && hasWideColorDisplay) {
1203 defaultColorMode = HAL_COLOR_MODE_SRGB;
1204 }
1205 setActiveColorModeInternal(hw, defaultColorMode);
1206}
1207
1208void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001210
1211 if (composer->isUsingVrComposer()) {
1212 // We handle initializing the primary display device for the VR
1213 // window manager hwc explicitly at the time of transition.
1214 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1215 ALOGE("External displays are not supported by the vr hardware composer.");
1216 }
1217 return;
1218 }
1219
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1221 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001222 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1223 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001224 } else {
1225 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001226 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001227 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001229 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001230 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1231 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001232 }
1233 setTransactionFlags(eDisplayTransactionNeeded);
1234
Andy McFadden9e9689c2012-10-10 18:17:51 -07001235 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001236 }
Mathias Agopian86303202012-07-24 22:46:10 -07001237}
1238
Steven Thomas3cfac282017-02-06 12:29:30 -08001239void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1240 Mutex::Autolock lock(mStateLock);
1241 if (composer == mHwc) {
1242 repaintEverything();
1243 } else {
1244 // This isn't from our current hardware composer. If it's a callback
1245 // from the real composer, forward the refresh request to vr
1246 // flinger. Otherwise ignore it.
1247 if (!composer->isUsingVrComposer()) {
1248 mVrFlinger->OnHardwareComposerRefresh();
1249 }
1250 }
1251}
1252
Dan Stoza9e56aa02015-11-02 13:00:03 -08001253void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001255 getHwComposer().setVsyncEnabled(disp,
1256 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001257}
1258
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001259// Note: it is assumed the caller holds |mStateLock| when this is called
1260void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001261 disableHardwareVsync(true);
1262 clearHwcLayers(mDrawingState.layersSortedByZ);
1263 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001264 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1265 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1266 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001267 // Clear the drawing state so that the logic inside of
1268 // handleTransactionLocked will fire. It will determine the delta between
1269 // mCurrentState and mDrawingState and re-apply all changes when we make the
1270 // transition.
1271 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001272 // Release virtual display hwcId during vr mode transition.
1273 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1274 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1275 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1276 displayDevice->disconnect(getHwComposer());
1277 }
1278 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001279 mDisplays.clear();
1280}
1281
Steven Thomas050b2c82017-03-06 11:45:16 -08001282void SurfaceFlinger::updateVrFlinger() {
1283 if (!mVrFlinger)
1284 return;
1285 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1286 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001287 return;
1288 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001289
Steven Thomas050b2c82017-03-06 11:45:16 -08001290 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001291 // Construct new HWComposer without holding any locks.
1292 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001293
1294 // Set up the event handlers. This step is neccessary to initialize the internal state of
1295 // the hardware composer object properly. Our callbacks are designed such that if they are
1296 // triggered between now and the point where the display is properly re-initialized, they
1297 // will not have any effect, so this is safe to do here, before the lock is aquired.
1298 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001299 ALOGV("Vr HWC created");
1300 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001301
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001302 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001303
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304 if (vrFlingerRequestsDisplay) {
1305 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307 mHwc = mVrHwc;
1308 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310 } else {
1311 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001312
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313 resetHwcLocked();
1314
1315 mHwc = mRealHwc;
1316 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001317 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001318
1319 mVisibleRegionsDirty = true;
1320 invalidateHwcGeometry();
1321
1322 // Explicitly re-initialize the primary display. This is because some other
1323 // parts of this class rely on the primary display always being available.
1324 createDefaultDisplayDevice();
1325
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001326 // Re-enable default display.
1327 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1328 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1329 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1330
1331 // Reset the timing values to account for the period of the swapped in HWC
1332 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1333 const nsecs_t period = activeConfig->getVsyncPeriod();
1334 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1335
1336 // Use phase of 0 since phase is not known.
1337 // Use latency of 0, which will snap to the ideal latency.
1338 setCompositorTimingSnapped(0, period, 0);
1339 });
1340 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001341
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342 android_atomic_or(1, &mRepaintEverything);
1343 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344}
1345
Mathias Agopian4fec8732012-06-29 14:12:52 -07001346void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001347 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001348 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001349 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001350 bool frameMissed = !mHadClientComposition &&
1351 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352 (mPreviousPresentFence->getSignalTime() ==
1353 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001354 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001355 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001356 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001357 signalLayerUpdate();
1358 break;
1359 }
1360
Steven Thomas050b2c82017-03-06 11:45:16 -08001361 // Now that we're going to make it to the handleMessageTransaction()
1362 // call below it's safe to call updateVrFlinger(), which will
1363 // potentially trigger a display handoff.
1364 updateVrFlinger();
1365
Dan Stoza6b9454d2014-11-07 16:00:59 -08001366 bool refreshNeeded = handleMessageTransaction();
1367 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001368 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001369 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001370 // Signal a refresh if a transaction modified the window state,
1371 // a new buffer was latched, or if HWC has requested a full
1372 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001373 signalRefresh();
1374 }
1375 break;
1376 }
1377 case MessageQueue::REFRESH: {
1378 handleMessageRefresh();
1379 break;
1380 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381 }
1382}
1383
Dan Stoza6b9454d2014-11-07 16:00:59 -08001384bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001385 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001386 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001387 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001388 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001389 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001390 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001391}
1392
Dan Stoza6b9454d2014-11-07 16:00:59 -08001393bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001394 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001395 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001396}
1397
1398void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001399 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001400
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001401 mRefreshPending = false;
1402
Pablo Ceballos40845df2016-01-25 17:41:15 -08001403 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001404
Brian Andersond6927fb2016-07-23 23:37:30 -07001405 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001406 rebuildLayerStacks();
1407 setUpHWComposer();
1408 doDebugFlashRegions();
1409 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001411
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001412 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001413
1414 mHadClientComposition = false;
1415 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1416 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1417 mHadClientComposition = mHadClientComposition ||
1418 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1419 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001420
Dan Stoza9e56aa02015-11-02 13:00:03 -08001421 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001422}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001423
Mathias Agopiancd60f992012-08-16 16:28:27 -07001424void SurfaceFlinger::doDebugFlashRegions()
1425{
1426 // is debugging enabled
1427 if (CC_LIKELY(!mDebugRegion))
1428 return;
1429
1430 const bool repaintEverything = mRepaintEverything;
1431 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1432 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001433 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001434 // transform the dirty region into this screen's coordinate space
1435 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1436 if (!dirtyRegion.isEmpty()) {
1437 // redraw the whole screen
1438 doComposeSurfaces(hw, Region(hw->bounds()));
1439
1440 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001442 RenderEngine& engine(getRenderEngine());
1443 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1444
Mathias Agopianda27af92012-09-13 18:17:13 -07001445 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001446 }
1447 }
1448 }
1449
1450 postFramebuffer();
1451
1452 if (mDebugRegion > 1) {
1453 usleep(mDebugRegion * 1000);
1454 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001455
Dan Stoza9e56aa02015-11-02 13:00:03 -08001456 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001457 auto& displayDevice = mDisplays[displayId];
1458 if (!displayDevice->isDisplayOn()) {
1459 continue;
1460 }
1461
1462 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001463 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1464 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001465 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466}
1467
Brian Andersond6927fb2016-07-23 23:37:30 -07001468void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001470 ATRACE_CALL();
1471 ALOGV("preComposition");
1472
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001474 mDrawingState.traverseInZOrder([&](Layer* layer) {
1475 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476 needExtraInvalidate = true;
1477 }
Robert Carr2047fae2016-11-28 14:09:09 -08001478 });
1479
Mathias Agopiancd60f992012-08-16 16:28:27 -07001480 if (needExtraInvalidate) {
1481 signalLayerUpdate();
1482 }
1483}
1484
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001485void SurfaceFlinger::updateCompositorTiming(
1486 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1487 std::shared_ptr<FenceTime>& presentFenceTime) {
1488 // Update queue of past composite+present times and determine the
1489 // most recently known composite to present latency.
1490 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1491 nsecs_t compositeToPresentLatency = -1;
1492 while (!mCompositePresentTimes.empty()) {
1493 CompositePresentTime& cpt = mCompositePresentTimes.front();
1494 // Cached values should have been updated before calling this method,
1495 // which helps avoid duplicate syscalls.
1496 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1497 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1498 break;
1499 }
1500 compositeToPresentLatency = displayTime - cpt.composite;
1501 mCompositePresentTimes.pop();
1502 }
1503
1504 // Don't let mCompositePresentTimes grow unbounded, just in case.
1505 while (mCompositePresentTimes.size() > 16) {
1506 mCompositePresentTimes.pop();
1507 }
1508
Brian Andersond0010582017-03-07 13:20:31 -08001509 setCompositorTimingSnapped(
1510 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1511}
1512
1513void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1514 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001515 // Integer division and modulo round toward 0 not -inf, so we need to
1516 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001517 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001518 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1519 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1520
Brian Andersond0010582017-03-07 13:20:31 -08001521 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1522 if (idealLatency <= 0) {
1523 idealLatency = vsyncInterval;
1524 }
1525
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001526 // Snap the latency to a value that removes scheduling jitter from the
1527 // composition and present times, which often have >1ms of jitter.
1528 // Reducing jitter is important if an app attempts to extrapolate
1529 // something (such as user input) to an accurate diasplay time.
1530 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1531 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001532 nsecs_t bias = vsyncInterval / 2;
1533 int64_t extraVsyncs =
1534 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1535 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1536 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537
Brian Andersond0010582017-03-07 13:20:31 -08001538 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1540 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001541 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542}
1543
1544void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 ATRACE_CALL();
1547 ALOGV("postComposition");
1548
Brian Anderson3546a3f2016-07-14 11:51:14 -07001549 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001550 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001551 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001552 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001553 }
1554
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001555 // |mStateLock| not needed as we are on the main thread
1556 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001557
1558 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1559 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1560 glCompositionDoneFenceTime =
1561 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1562 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1563 } else {
1564 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1565 }
1566 mGlCompositionDoneTimeline.updateSignalTimes();
1567
Brian Anderson4e606e32017-03-16 15:34:57 -07001568 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1569 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1570 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001571 mDisplayTimeline.updateSignalTimes();
1572
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1574 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1575
1576 // We use the refreshStartTime which might be sampled a little later than
1577 // when we started doing work for this frame, but that should be okay
1578 // since updateCompositorTiming has snapping logic.
1579 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001580 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001581 CompositorTiming compositorTiming;
1582 {
1583 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1584 compositorTiming = mCompositorTiming;
1585 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001586
Robert Carr2047fae2016-11-28 14:09:09 -08001587 mDrawingState.traverseInZOrder([&](Layer* layer) {
1588 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001589 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001590 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001591 recordBufferingStats(layer->getName().string(),
1592 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001593 }
Robert Carr2047fae2016-11-28 14:09:09 -08001594 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001595
Brian Anderson4e606e32017-03-16 15:34:57 -07001596 if (presentFence->isValid()) {
1597 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001598 enableHardwareVsync();
1599 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001600 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001601 }
1602 }
1603
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001604 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001605 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001606 enableHardwareVsync();
1607 }
1608 }
1609
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001610 if (mAnimCompositionPending) {
1611 mAnimCompositionPending = false;
1612
Brian Anderson4e606e32017-03-16 15:34:57 -07001613 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001614 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001615 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001616 } else {
1617 // The HWC doesn't support present fences, so use the refresh
1618 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001619 nsecs_t presentTime =
1620 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001621 mAnimFrameTracker.setActualPresentTime(presentTime);
1622 }
1623 mAnimFrameTracker.advanceFrame();
1624 }
Dan Stozab90cf072015-03-05 11:05:59 -08001625
1626 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1627 return;
1628 }
1629
1630 nsecs_t currentTime = systemTime();
1631 if (mHasPoweredOff) {
1632 mHasPoweredOff = false;
1633 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001634 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001636 if (numPeriods < NUM_BUCKETS - 1) {
1637 mFrameBuckets[numPeriods] += elapsedTime;
1638 } else {
1639 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1640 }
1641 mTotalTime += elapsedTime;
1642 }
1643 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001644}
1645
1646void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001647 ATRACE_CALL();
1648 ALOGV("rebuildLayerStacks");
1649
Mathias Agopiancd60f992012-08-16 16:28:27 -07001650 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001651 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1652 ATRACE_CALL();
1653 mVisibleRegionsDirty = false;
1654 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001655
Jeff Sharkey76488112017-02-27 14:15:18 -07001656 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1657 Region opaqueRegion;
1658 Region dirtyRegion;
1659 Vector<sp<Layer>> layersSortedByZ;
1660 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1661 const Transform& tr(displayDevice->getTransform());
1662 const Rect bounds(displayDevice->getBounds());
1663 if (displayDevice->isDisplayOn()) {
1664 computeVisibleRegions(
1665 displayDevice->getLayerStack(), dirtyRegion,
1666 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001667
Jeff Sharkey76488112017-02-27 14:15:18 -07001668 mDrawingState.traverseInZOrder([&](Layer* layer) {
1669 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1670 Region drawRegion(tr.transform(
1671 layer->visibleNonTransparentRegion));
1672 drawRegion.andSelf(bounds);
1673 if (!drawRegion.isEmpty()) {
1674 layersSortedByZ.add(layer);
1675 } else {
1676 // Clear out the HWC layer if this layer was
1677 // previously visible, but no longer is
1678 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1679 nullptr);
1680 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001681 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001682 // WM changes displayDevice->layerStack upon sleep/awake.
1683 // Here we make sure we delete the HWC layers even if
1684 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001685 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1686 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001687 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001688 });
1689 }
1690 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1691 displayDevice->undefinedRegion.set(bounds);
1692 displayDevice->undefinedRegion.subtractSelf(
1693 tr.transform(opaqueRegion));
1694 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001695 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001696 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001698
Romain Guy0147a172017-06-01 13:53:56 -07001699mat4 SurfaceFlinger::computeSaturationMatrix() const {
1700 if (mSaturation == 1.0f) {
1701 return mat4();
1702 }
1703
1704 // Rec.709 luma coefficients
1705 float3 luminance{0.213f, 0.715f, 0.072f};
1706 luminance *= 1.0f - mSaturation;
1707 return mat4(
1708 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1709 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1710 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1711 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1712 );
1713}
1714
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001715// pickColorMode translates a given dataspace into the best available color mode.
1716// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001717android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001718 switch (dataSpace) {
1719 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1720 // system expects.
1721 case HAL_DATASPACE_UNKNOWN:
1722 case HAL_DATASPACE_SRGB:
1723 case HAL_DATASPACE_V0_SRGB:
1724 return HAL_COLOR_MODE_SRGB;
1725 break;
1726
1727 case HAL_DATASPACE_DISPLAY_P3:
1728 return HAL_COLOR_MODE_DISPLAY_P3;
1729 break;
1730
1731 default:
1732 // TODO (courtneygo): Do we want to assert an error here?
1733 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1734 dataSpace);
1735 return HAL_COLOR_MODE_SRGB;
1736 break;
1737 }
1738}
1739
Romain Guy0147a172017-06-01 13:53:56 -07001740android_dataspace SurfaceFlinger::bestTargetDataSpace(
1741 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001742 // Only support sRGB and Display-P3 right now.
1743 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1744 return HAL_DATASPACE_DISPLAY_P3;
1745 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001746 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1747 return HAL_DATASPACE_DISPLAY_P3;
1748 }
1749 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1750 return HAL_DATASPACE_DISPLAY_P3;
1751 }
1752
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001753 return HAL_DATASPACE_V0_SRGB;
1754}
1755
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 ATRACE_CALL();
1758 ALOGV("setUpHWComposer");
1759
Jesse Hall028dc8f2013-08-20 16:35:32 -07001760 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001761 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1762 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1763 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1764
1765 // If nothing has changed (!dirty), don't recompose.
1766 // If something changed, but we don't currently have any visible layers,
1767 // and didn't when we last did a composition, then skip it this time.
1768 // The second rule does two things:
1769 // - When all layers are removed from a display, we'll emit one black
1770 // frame, then nothing more until we get new layers.
1771 // - When a display is created with a private layer stack, we won't
1772 // emit any black frames until a layer is added to the layer stack.
1773 bool mustRecompose = dirty && !(empty && wasEmpty);
1774
1775 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1776 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1777 mustRecompose ? "doing" : "skipping",
1778 dirty ? "+" : "-",
1779 empty ? "+" : "-",
1780 wasEmpty ? "+" : "-");
1781
Dan Stoza71433162014-02-04 16:22:36 -08001782 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001783
1784 if (mustRecompose) {
1785 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1786 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001787 }
1788
Dan Stoza9e56aa02015-11-02 13:00:03 -08001789 // build the h/w work list
1790 if (CC_UNLIKELY(mGeometryInvalid)) {
1791 mGeometryInvalid = false;
1792 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1793 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1794 const auto hwcId = displayDevice->getHwcDisplayId();
1795 if (hwcId >= 0) {
1796 const Vector<sp<Layer>>& currentLayers(
1797 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001798 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001799 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 if (!layer->hasHwcLayer(hwcId)) {
1801 auto hwcLayer = mHwc->createLayer(hwcId);
1802 if (hwcLayer) {
1803 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1804 } else {
1805 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001806 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001807 }
1808 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001809
Robert Carrae060832016-11-28 10:51:00 -08001810 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001811 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001813 }
1814 }
1815 }
1816 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817 }
Riley Andrews03414a12014-07-01 14:22:59 -07001818
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001819
Romain Guy0147a172017-06-01 13:53:56 -07001820 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001821
Dan Stoza9e56aa02015-11-02 13:00:03 -08001822 // Set the per-frame data
1823 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1824 auto& displayDevice = mDisplays[displayId];
1825 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001826
Dan Stoza9e56aa02015-11-02 13:00:03 -08001827 if (hwcId < 0) {
1828 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001829 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001830 if (colorMatrix != mPreviousColorMatrix) {
1831 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1832 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1833 "display %zd: %d", displayId, result);
1834 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001835 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1836 layer->setPerFrameData(displayDevice);
1837 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001838
1839 if (hasWideColorDisplay) {
1840 android_color_mode newColorMode;
1841 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1842
1843 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1844 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1845 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1846 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1847 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1848 }
1849 newColorMode = pickColorMode(newDataSpace);
1850
1851 setActiveColorModeInternal(displayDevice, newColorMode);
1852 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 }
1854
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001855 mPreviousColorMatrix = colorMatrix;
1856
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001858 auto& displayDevice = mDisplays[displayId];
1859 if (!displayDevice->isDisplayOn()) {
1860 continue;
1861 }
1862
1863 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001864 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1865 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001866 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001868
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869void SurfaceFlinger::doComposition() {
1870 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 ALOGV("doComposition");
1872
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001873 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001874 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001875 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001876 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877 // transform the dirty region into this screen's coordinate space
1878 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001879
1880 // repaint the framebuffer (if needed)
1881 doDisplayComposition(hw, dirtyRegion);
1882
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883 hw->dirtyRegion.clear();
1884 hw->flip(hw->swapRegion);
1885 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001886 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001887 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001888 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001889}
1890
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001891void SurfaceFlinger::postFramebuffer()
1892{
Mathias Agopian841cde52012-03-01 15:44:37 -08001893 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001895
Mathias Agopiana44b0412011-10-16 18:46:35 -07001896 const nsecs_t now = systemTime();
1897 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001898
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1900 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001901 if (!displayDevice->isDisplayOn()) {
1902 continue;
1903 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001904 const auto hwcId = displayDevice->getHwcDisplayId();
1905 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001906 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001907 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001908 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001909 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1911 sp<Fence> releaseFence = Fence::NO_FENCE;
1912 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1913 releaseFence = displayDevice->getClientTargetAcquireFence();
1914 } else {
1915 auto hwcLayer = layer->getHwcLayer(hwcId);
1916 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001917 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 layer->onLayerDisplayed(releaseFence);
1919 }
1920 if (hwcId >= 0) {
1921 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001922 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001923 }
1924
Mathias Agopiana44b0412011-10-16 18:46:35 -07001925 mLastSwapBufferTime = systemTime() - now;
1926 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001927
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001928 // |mStateLock| not needed as we are on the main thread
1929 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001930 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1931 logFrameStats();
1932 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001933}
1934
Mathias Agopian87baae12012-07-31 12:38:26 -07001935void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001936{
Mathias Agopian841cde52012-03-01 15:44:37 -08001937 ATRACE_CALL();
1938
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001939 // here we keep a copy of the drawing state (that is the state that's
1940 // going to be overwritten by handleTransactionLocked()) outside of
1941 // mStateLock so that the side-effects of the State assignment
1942 // don't happen with mStateLock held (which can cause deadlocks).
1943 State drawingState(mDrawingState);
1944
Mathias Agopianca4d3602011-05-19 15:38:14 -07001945 Mutex::Autolock _l(mStateLock);
1946 const nsecs_t now = systemTime();
1947 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001948
Mathias Agopianca4d3602011-05-19 15:38:14 -07001949 // Here we're guaranteed that some transaction flags are set
1950 // so we can call handleTransactionLocked() unconditionally.
1951 // We call getTransactionFlags(), which will also clear the flags,
1952 // with mStateLock held to guarantee that mCurrentState won't change
1953 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001954
Mathias Agopiane57f2922012-08-09 16:29:12 -07001955 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001956 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001957
Mathias Agopianca4d3602011-05-19 15:38:14 -07001958 mLastTransactionTime = systemTime() - now;
1959 mDebugInTransaction = 0;
1960 invalidateHwcGeometry();
1961 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001962}
1963
Mathias Agopian87baae12012-07-31 12:38:26 -07001964void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001965{
Dan Stoza7dde5992015-05-22 09:51:44 -07001966 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001967 mCurrentState.traverseInZOrder([](Layer* layer) {
1968 layer->notifyAvailableFrames();
1969 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001970
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971 /*
1972 * Traversal of the children
1973 * (perform the transaction for each of them if needed)
1974 */
1975
Mathias Agopian3559b072012-08-15 13:46:03 -07001976 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001977 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001978 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001979 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980
1981 const uint32_t flags = layer->doTransaction(0);
1982 if (flags & Layer::eVisibleRegion)
1983 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001984 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985 }
1986
1987 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001988 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989 */
1990
Mathias Agopiane57f2922012-08-09 16:29:12 -07001991 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001992 // here we take advantage of Vector's copy-on-write semantics to
1993 // improve performance by skipping the transaction entirely when
1994 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001995 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1996 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001997 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001998 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001999 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002000 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002001
2002 // find the displays that were removed
2003 // (ie: in drawing state but not in current state)
2004 // also handle displays that changed
2005 // (ie: displays that are in both lists)
2006 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002007 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2008 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002009 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002010 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002011 // Call makeCurrent() on the primary display so we can
2012 // be sure that nothing associated with this display
2013 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002014 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002015 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002016 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002017 if (hw != NULL)
2018 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002019 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002020 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002021 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002022 } else {
2023 ALOGW("trying to remove the main display");
2024 }
2025 } else {
2026 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002027 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002028 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002029 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2030 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002031 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002032 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002033 // recreating the DisplayDevice, so we just remove it
2034 // from the drawing state, so that it get re-added
2035 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002036 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002037 if (hw != NULL)
2038 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002039 mDisplays.removeItem(display);
2040 mDrawingState.displays.removeItemsAt(i);
2041 dc--; i--;
2042 // at this point we must loop to the next item
2043 continue;
2044 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002045
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002046 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002047 if (disp != NULL) {
2048 if (state.layerStack != draw[i].layerStack) {
2049 disp->setLayerStack(state.layerStack);
2050 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002051 if ((state.orientation != draw[i].orientation)
2052 || (state.viewport != draw[i].viewport)
2053 || (state.frame != draw[i].frame))
2054 {
2055 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002056 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002057 }
Michael Lentine47e45402014-07-18 15:34:25 -07002058 if (state.width != draw[i].width || state.height != draw[i].height) {
2059 disp->setDisplaySize(state.width, state.height);
2060 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002061 }
2062 }
2063 }
2064
2065 // find displays that were added
2066 // (ie: in current state but not in drawing state)
2067 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002068 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002069 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002070
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002071 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002072 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002073 sp<IGraphicBufferProducer> bqProducer;
2074 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002075 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002076
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002078 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002079 // Virtual displays without a surface are dormant:
2080 // they have external state (layer stack, projection,
2081 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002082 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002083
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002084 // Allow VR composer to use virtual displays.
2085 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002086 int width = 0;
2087 int status = state.surface->query(
2088 NATIVE_WINDOW_WIDTH, &width);
2089 ALOGE_IF(status != NO_ERROR,
2090 "Unable to query width (%d)", status);
2091 int height = 0;
2092 status = state.surface->query(
2093 NATIVE_WINDOW_HEIGHT, &height);
2094 ALOGE_IF(status != NO_ERROR,
2095 "Unable to query height (%d)", status);
2096 int intFormat = 0;
2097 status = state.surface->query(
2098 NATIVE_WINDOW_FORMAT, &intFormat);
2099 ALOGE_IF(status != NO_ERROR,
2100 "Unable to query format (%d)", status);
2101 auto format = static_cast<android_pixel_format_t>(
2102 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002103
Dan Stoza8cf150a2016-08-02 10:27:31 -07002104 mHwc->allocateVirtualDisplay(width, height, &format,
2105 &hwcId);
2106 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107
Dan Stoza5cf424b2016-05-20 14:02:39 -07002108 // TODO: Plumb requested format back up to consumer
2109
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 sp<VirtualDisplaySurface> vds =
2111 new VirtualDisplaySurface(*mHwc,
2112 hwcId, state.surface, bqProducer,
2113 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002114
2115 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002116 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002117 }
2118 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002119 ALOGE_IF(state.surface!=NULL,
2120 "adding a supported display, but rendering "
2121 "surface is provided (%p), ignoring it",
2122 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002123
2124 hwcId = state.type;
2125 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2126 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002127 }
2128
2129 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002130 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002131 sp<DisplayDevice> hw =
2132 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2133 dispSurface, producer,
2134 mRenderEngine->getEGLConfig(),
2135 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002136 hw->setLayerStack(state.layerStack);
2137 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002138 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002139 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002140 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002142 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002143 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002144 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002145 }
2146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002147 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002148 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149
Mathias Agopian84300952012-11-21 16:02:13 -08002150 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2151 // The transform hint might have changed for some layers
2152 // (either because a display has changed, or because a layer
2153 // as changed).
2154 //
2155 // Walk through all the layers in currentLayers,
2156 // and update their transform hint.
2157 //
2158 // If a layer is visible only on a single display, then that
2159 // display is used to calculate the hint, otherwise we use the
2160 // default display.
2161 //
2162 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2163 // the hint is set before we acquire a buffer from the surface texture.
2164 //
2165 // NOTE: layer transactions have taken place already, so we use their
2166 // drawing state. However, SurfaceFlinger's own transaction has not
2167 // happened yet, so we must use the current state layer list
2168 // (soon to become the drawing state list).
2169 //
2170 sp<const DisplayDevice> disp;
2171 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002172 bool first = true;
2173 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002174 // NOTE: we rely on the fact that layers are sorted by
2175 // layerStack first (so we don't have to traverse the list
2176 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002178 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002179 currentlayerStack = layerStack;
2180 // figure out if this layerstack is mirrored
2181 // (more than one display) if so, pick the default display,
2182 // if not, pick the only display it's on.
2183 disp.clear();
2184 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2185 sp<const DisplayDevice> hw(mDisplays[dpy]);
2186 if (hw->getLayerStack() == currentlayerStack) {
2187 if (disp == NULL) {
2188 disp = hw;
2189 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002190 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002191 break;
2192 }
2193 }
2194 }
2195 }
Chet Haase91d25932013-04-11 15:24:55 -07002196 if (disp == NULL) {
2197 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2198 // redraw after transform hint changes. See bug 8508397.
2199
2200 // could be null when this layer is using a layerStack
2201 // that is not visible on any display. Also can occur at
2202 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002203 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002204 }
Chet Haase91d25932013-04-11 15:24:55 -07002205 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002206
2207 first = false;
2208 });
Mathias Agopian84300952012-11-21 16:02:13 -08002209 }
2210
2211
Mathias Agopian3559b072012-08-15 13:46:03 -07002212 /*
2213 * Perform our own transaction if needed
2214 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002215
2216 if (mLayersAdded) {
2217 mLayersAdded = false;
2218 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002219 mVisibleRegionsDirty = true;
2220 }
2221
2222 // some layers might have been removed, so
2223 // we need to update the regions they're exposing.
2224 if (mLayersRemoved) {
2225 mLayersRemoved = false;
2226 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002227 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002228 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002229 // this layer is not visible anymore
2230 // TODO: we could traverse the tree from front to back and
2231 // compute the actual visible region
2232 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002233 Region visibleReg;
2234 visibleReg.set(layer->computeScreenBounds());
2235 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002236 }
Robert Carr2047fae2016-11-28 14:09:09 -08002237 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 }
2239
2240 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002241
2242 updateCursorAsync();
2243}
2244
2245void SurfaceFlinger::updateCursorAsync()
2246{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002247 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2248 auto& displayDevice = mDisplays[displayId];
2249 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002250 continue;
2251 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252
2253 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2254 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002255 }
2256 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002257}
2258
2259void SurfaceFlinger::commitTransaction()
2260{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002261 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002262 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002263 for (const auto& l : mLayersPendingRemoval) {
2264 recordBufferingStats(l->getName().string(),
2265 l->getOccupancyHistory(true));
2266 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002267 }
2268 mLayersPendingRemoval.clear();
2269 }
2270
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002271 // If this transaction is part of a window animation then the next frame
2272 // we composite should be considered an animation as well.
2273 mAnimCompositionPending = mAnimTransactionPending;
2274
Mathias Agopian4fec8732012-06-29 14:12:52 -07002275 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002276 mDrawingState.traverseInZOrder([](Layer* layer) {
2277 layer->commitChildList();
2278 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002279 mTransactionPending = false;
2280 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002281 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282}
2283
Robert Carr2047fae2016-11-28 14:09:09 -08002284void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002285 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286{
Mathias Agopian841cde52012-03-01 15:44:37 -08002287 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002288 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290 Region aboveOpaqueLayers;
2291 Region aboveCoveredLayers;
2292 Region dirty;
2293
Mathias Agopian87baae12012-07-31 12:38:26 -07002294 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295
Robert Carr2047fae2016-11-28 14:09:09 -08002296 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002298 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299
Jesse Hall01e29052013-02-19 16:13:35 -08002300 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002302 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002303
Mathias Agopianab028732010-03-16 16:41:46 -07002304 /*
2305 * opaqueRegion: area of a surface that is fully opaque.
2306 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002308
2309 /*
2310 * visibleRegion: area of a surface that is visible on screen
2311 * and not fully transparent. This is essentially the layer's
2312 * footprint minus the opaque regions above it.
2313 * Areas covered by a translucent surface are considered visible.
2314 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002316
2317 /*
2318 * coveredRegion: area of a surface that is covered by all
2319 * visible regions above it (which includes the translucent areas).
2320 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002322
Jesse Halla8026d22012-09-25 13:25:04 -07002323 /*
2324 * transparentRegion: area of a surface that is hinted to be completely
2325 * transparent. This is only used to tell when the layer has no visible
2326 * non-transparent regions and can be removed from the layer list. It
2327 * does not affect the visibleRegion of this layer or any layers
2328 * beneath it. The hint may not be correct if apps don't respect the
2329 * SurfaceView restrictions (which, sadly, some don't).
2330 */
2331 Region transparentRegion;
2332
Mathias Agopianab028732010-03-16 16:41:46 -07002333
2334 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002335 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002336 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002337 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002339 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002340 if (!visibleRegion.isEmpty()) {
2341 // Remove the transparent area from the visible region
2342 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002343 if (tr.preserveRects()) {
2344 // transform the transparent region
2345 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002346 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002347 // transformation too complex, can't do the
2348 // transparent region optimization.
2349 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002350 }
Mathias Agopianab028732010-03-16 16:41:46 -07002351 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352
Mathias Agopianab028732010-03-16 16:41:46 -07002353 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002354 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002355 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002356 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2357 // the opaque region is the layer's footprint
2358 opaqueRegion = visibleRegion;
2359 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 }
2361 }
2362
Mathias Agopianab028732010-03-16 16:41:46 -07002363 // Clip the covered region to the visible region
2364 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2365
2366 // Update aboveCoveredLayers for next (lower) layer
2367 aboveCoveredLayers.orSelf(visibleRegion);
2368
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 // subtract the opaque region covered by the layers above us
2370 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371
2372 // compute this layer's dirty region
2373 if (layer->contentDirty) {
2374 // we need to invalidate the whole region
2375 dirty = visibleRegion;
2376 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002377 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378 layer->contentDirty = false;
2379 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002380 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002381 * the exposed region consists of two components:
2382 * 1) what's VISIBLE now and was COVERED before
2383 * 2) what's EXPOSED now less what was EXPOSED before
2384 *
2385 * note that (1) is conservative, we start with the whole
2386 * visible region but only keep what used to be covered by
2387 * something -- which mean it may have been exposed.
2388 *
2389 * (2) handles areas that were not covered by anything but got
2390 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002391 */
Mathias Agopianab028732010-03-16 16:41:46 -07002392 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002393 const Region oldVisibleRegion = layer->visibleRegion;
2394 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002395 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2396 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397 }
2398 dirty.subtractSelf(aboveOpaqueLayers);
2399
2400 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002401 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402
Mathias Agopianab028732010-03-16 16:41:46 -07002403 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002405
Jesse Halla8026d22012-09-25 13:25:04 -07002406 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002407 layer->setVisibleRegion(visibleRegion);
2408 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002409 layer->setVisibleNonTransparentRegion(
2410 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002411 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412
Mathias Agopian87baae12012-07-31 12:38:26 -07002413 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414}
2415
Mathias Agopian87baae12012-07-31 12:38:26 -07002416void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2417 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002418 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002419 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2420 if (hw->getLayerStack() == layerStack) {
2421 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002422 }
2423 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002424}
2425
Dan Stoza6b9454d2014-11-07 16:00:59 -08002426bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 ALOGV("handlePageFlip");
2429
Brian Andersond6927fb2016-07-23 23:37:30 -07002430 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431
Mathias Agopian4fec8732012-06-29 14:12:52 -07002432 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002433 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002434 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002435
2436 // Store the set of layers that need updates. This set must not change as
2437 // buffers are being latched, as this could result in a deadlock.
2438 // Example: Two producers share the same command stream and:
2439 // 1.) Layer 0 is latched
2440 // 2.) Layer 0 gets a new frame
2441 // 2.) Layer 1 gets a new frame
2442 // 3.) Layer 1 is latched.
2443 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2444 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002445 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002446 if (layer->hasQueuedFrame()) {
2447 frameQueued = true;
2448 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002449 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002450 } else {
2451 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002452 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002453 } else {
2454 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002455 }
Robert Carr2047fae2016-11-28 14:09:09 -08002456 });
2457
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002459 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002460 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002461 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002462 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002463 newDataLatched = true;
2464 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002465 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002466
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002467 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002468
2469 // If we will need to wake up at some time in the future to deal with a
2470 // queued frame that shouldn't be displayed during this vsync period, wake
2471 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002472 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002473 signalLayerUpdate();
2474 }
2475
2476 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002477 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478}
2479
Mathias Agopianad456f92011-01-13 17:53:01 -08002480void SurfaceFlinger::invalidateHwcGeometry()
2481{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002483}
2484
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002485
Fabien Sanglard830b8472016-11-30 16:35:58 -08002486void SurfaceFlinger::doDisplayComposition(
2487 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002488 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489{
Dan Stoza71433162014-02-04 16:22:36 -08002490 // We only need to actually compose the display if:
2491 // 1) It is being handled by hardware composer, which may need this to
2492 // keep its virtual display state machine in sync, or
2493 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002494 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002495 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002497 return;
2498 }
2499
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 ALOGV("doDisplayComposition");
2501
Mathias Agopian87baae12012-07-31 12:38:26 -07002502 Region dirtyRegion(inDirtyRegion);
2503
Mathias Agopianb8a55602009-06-26 19:06:36 -07002504 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002505 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Fabien Sanglard830b8472016-11-30 16:35:58 -08002507 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002508 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002509 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2510 // takes a rectangle, we must make sure to update that whole
2511 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002512 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002513 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002514 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002515 // We need to redraw the rectangle that will be updated
2516 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002517 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002518 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002519 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002520 } else {
2521 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002522 dirtyRegion.set(displayDevice->bounds());
2523 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 }
2525 }
2526
Fabien Sanglard830b8472016-11-30 16:35:58 -08002527 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002529 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002530 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002531
2532 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002533 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534}
2535
Dan Stoza9e56aa02015-11-02 13:00:03 -08002536bool SurfaceFlinger::doComposeSurfaces(
2537 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002538{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002539 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002540
Dan Stoza9e56aa02015-11-02 13:00:03 -08002541 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002542
2543 mat4 oldColorMatrix;
2544 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2545 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2546 if (applyColorMatrix) {
2547 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2548 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2549 }
2550
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2552 if (hasClientComposition) {
2553 ALOGV("hasClientComposition");
2554
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002555#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002556 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002557 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002558#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002559 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002560 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002561 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002562 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002563
2564 // |mStateLock| not needed as we are on the main thread
2565 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002566 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2567 }
2568 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002569 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002570
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002571 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002572 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2573 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002574 // when using overlays, we assume a fully transparent framebuffer
2575 // NOTE: we could reduce how much we need to clear, for instance
2576 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002577 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002578 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002580 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002581 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002582 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002583
2584 // we remove the scissor part
2585 // we're left with the letterbox region
2586 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002588
2589 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002590 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002591
2592 // but limit it to the dirty region
2593 region.andSelf(dirty);
2594
Mathias Agopianb9494d52012-04-18 02:28:45 -07002595 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002596 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002597 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002599 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002600 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002601
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002603 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002604 // scissor on the main display. It should never be needed
2605 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 const Rect& bounds(displayDevice->getBounds());
2607 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002608 if (scissor != bounds) {
2609 // scissor doesn't match the screen's dimensions, so we
2610 // need to clear everything outside of it and enable
2611 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002612
Mathias Agopianf45c5102012-10-24 16:29:17 -07002613 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 const uint32_t height = displayDevice->getHeight();
2615 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002616 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002617 }
2618 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002619 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002620
Mathias Agopian85d751c2012-08-29 16:59:24 -07002621 /*
2622 * and then, render the layers targeted at the framebuffer
2623 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002624
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 ALOGV("Rendering client layers");
2626 const Transform& displayTransform = displayDevice->getTransform();
2627 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002628 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 bool firstLayer = true;
2630 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2631 const Region clip(dirty.intersect(
2632 displayTransform.transform(layer->visibleRegion)));
2633 ALOGV("Layer: %s", layer->getName().string());
2634 ALOGV(" Composition type: %s",
2635 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002636 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002637 switch (layer->getCompositionType(hwcId)) {
2638 case HWC2::Composition::Cursor:
2639 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002640 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002642 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2644 layer->isOpaque(state) && (state.alpha == 1.0f)
2645 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002646 // never clear the very first layer since we're
2647 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002648 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002649 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002650 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002651 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 case HWC2::Composition::Client: {
2653 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002654 break;
2655 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002657 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002658 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 } else {
2660 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002661 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002663 }
2664 } else {
2665 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002667 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002669 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002671 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002672 }
2673 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002674
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002675 if (applyColorMatrix) {
2676 getRenderEngine().setupColorTransform(oldColorMatrix);
2677 }
2678
Mathias Agopianf45c5102012-10-24 16:29:17 -07002679 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002681 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682}
2683
Fabien Sanglard830b8472016-11-30 16:35:58 -08002684void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2685 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002686 RenderEngine& engine(getRenderEngine());
2687 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688}
2689
Dan Stoza7d89d062015-04-30 13:29:25 -07002690status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002691 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002692 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 const sp<Layer>& lbc,
2694 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002695{
Dan Stoza7d89d062015-04-30 13:29:25 -07002696 // add this layer to the current state list
2697 {
2698 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002699 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002700 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2701 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002702 return NO_MEMORY;
2703 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 if (parent == nullptr) {
2705 mCurrentState.layersSortedByZ.add(lbc);
2706 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002707 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2708 ALOGE("addClientLayer called with a removed parent");
2709 return NAME_NOT_FOUND;
2710 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002711 parent->addChild(lbc);
2712 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002713
Dan Stoza7d89d062015-04-30 13:29:25 -07002714 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 mLayersAdded = true;
2716 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002717 }
2718
Mathias Agopian96f08192010-06-02 23:28:45 -07002719 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002720 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002721
Dan Stoza7d89d062015-04-30 13:29:25 -07002722 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002723}
2724
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002725status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002726 Mutex::Autolock _l(mStateLock);
2727
Robert Carr1f0a16a2016-10-24 16:27:39 -07002728 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002729 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002730 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002731 if (topLevelOnly) {
2732 return NO_ERROR;
2733 }
2734
Chia-I Wu98f1c102017-05-30 14:54:08 -07002735 sp<Layer> ancestor = p;
2736 while (ancestor->getParent() != nullptr) {
2737 ancestor = ancestor->getParent();
2738 }
2739 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2740 ALOGE("removeLayer called with a layer whose parent has been removed");
2741 return NAME_NOT_FOUND;
2742 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002743
2744 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002745 } else {
2746 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002747 }
2748
Robert Carr136e2f62017-02-08 17:54:29 -08002749 // As a matter of normal operation, the LayerCleaner will produce a second
2750 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2751 // so we will succeed in promoting it, but it's already been removed
2752 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2753 // otherwise something has gone wrong and we are leaking the layer.
2754 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2756 layer->getName().string(),
2757 (p != nullptr) ? p->getName().string() : "no-parent");
2758 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002759 } else if (index < 0) {
2760 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002761 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002762
2763 mLayersPendingRemoval.add(layer);
2764 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002765 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002766 setTransactionFlags(eTransactionNeeded);
2767 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768}
2769
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002770uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002771 return android_atomic_release_load(&mTransactionFlags);
2772}
2773
Mathias Agopian3f844832013-08-07 21:24:32 -07002774uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2776}
2777
Mathias Agopian3f844832013-08-07 21:24:32 -07002778uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2780 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002781 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 }
2783 return old;
2784}
2785
Mathias Agopian8b33f032012-07-24 20:43:54 -07002786void SurfaceFlinger::setTransactionState(
2787 const Vector<ComposerState>& state,
2788 const Vector<DisplayState>& displays,
2789 uint32_t flags)
2790{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002791 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002792 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002793 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002795 if (flags & eAnimation) {
2796 // For window updates that are part of an animation we must wait for
2797 // previous animation "frames" to be handled.
2798 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002799 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002800 if (CC_UNLIKELY(err != NO_ERROR)) {
2801 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002802 // caller after a few seconds.
2803 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2804 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002805 mAnimTransactionPending = false;
2806 break;
2807 }
2808 }
2809 }
2810
Mathias Agopiane57f2922012-08-09 16:29:12 -07002811 size_t count = displays.size();
2812 for (size_t i=0 ; i<count ; i++) {
2813 const DisplayState& s(displays[i]);
2814 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002815 }
2816
Mathias Agopiane57f2922012-08-09 16:29:12 -07002817 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002818 for (size_t i=0 ; i<count ; i++) {
2819 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002820 // Here we need to check that the interface we're given is indeed
2821 // one of our own. A malicious client could give us a NULL
2822 // IInterface, or one of its own or even one of our own but a
2823 // different type. All these situations would cause us to crash.
2824 //
2825 // NOTE: it would be better to use RTTI as we could directly check
2826 // that we have a Client*. however, RTTI is disabled in Android.
2827 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002828 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002829 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002830 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002831 sp<Client> client( static_cast<Client *>(s.client.get()) );
2832 transactionFlags |= setClientStateLocked(client, s.state);
2833 }
2834 }
2835 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002836 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002837
Robert Carr2a7dbb42016-05-24 11:41:28 -07002838 // If a synchronous transaction is explicitly requested without any changes,
2839 // force a transaction anyway. This can be used as a flush mechanism for
2840 // previous async transactions.
2841 if (transactionFlags == 0 && (flags & eSynchronous)) {
2842 transactionFlags = eTransactionNeeded;
2843 }
2844
Mathias Agopian386aa982011-11-07 21:58:03 -08002845 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002846 if (mInterceptor.isEnabled()) {
2847 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2848 }
Irvel468051e2016-06-13 16:44:44 -07002849
Mathias Agopian386aa982011-11-07 21:58:03 -08002850 // this triggers the transaction
2851 setTransactionFlags(transactionFlags);
2852
2853 // if this is a synchronous transaction, wait for it to take effect
2854 // before returning.
2855 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002856 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002857 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002858 if (flags & eAnimation) {
2859 mAnimTransactionPending = true;
2860 }
2861 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002862 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2863 if (CC_UNLIKELY(err != NO_ERROR)) {
2864 // just in case something goes wrong in SF, return to the
2865 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002866 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2867 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002868 break;
2869 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002870 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 }
2872}
2873
Mathias Agopiane57f2922012-08-09 16:29:12 -07002874uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2875{
Jesse Hall9a143922012-10-04 16:29:19 -07002876 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2877 if (dpyIdx < 0)
2878 return 0;
2879
Mathias Agopiane57f2922012-08-09 16:29:12 -07002880 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002881 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002882 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002883 const uint32_t what = s.what;
2884 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002885 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002886 disp.surface = s.surface;
2887 flags |= eDisplayTransactionNeeded;
2888 }
2889 }
2890 if (what & DisplayState::eLayerStackChanged) {
2891 if (disp.layerStack != s.layerStack) {
2892 disp.layerStack = s.layerStack;
2893 flags |= eDisplayTransactionNeeded;
2894 }
2895 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002896 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002897 if (disp.orientation != s.orientation) {
2898 disp.orientation = s.orientation;
2899 flags |= eDisplayTransactionNeeded;
2900 }
2901 if (disp.frame != s.frame) {
2902 disp.frame = s.frame;
2903 flags |= eDisplayTransactionNeeded;
2904 }
2905 if (disp.viewport != s.viewport) {
2906 disp.viewport = s.viewport;
2907 flags |= eDisplayTransactionNeeded;
2908 }
2909 }
Michael Lentine47e45402014-07-18 15:34:25 -07002910 if (what & DisplayState::eDisplaySizeChanged) {
2911 if (disp.width != s.width) {
2912 disp.width = s.width;
2913 flags |= eDisplayTransactionNeeded;
2914 }
2915 if (disp.height != s.height) {
2916 disp.height = s.height;
2917 flags |= eDisplayTransactionNeeded;
2918 }
2919 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920 }
2921 return flags;
2922}
2923
2924uint32_t SurfaceFlinger::setClientStateLocked(
2925 const sp<Client>& client,
2926 const layer_state_t& s)
2927{
2928 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002929 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002930 if (layer != 0) {
2931 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002932 bool geometryAppliesWithResize =
2933 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002934 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002935 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002936 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002937 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002938 }
2939 if (what & layer_state_t::eLayerChanged) {
2940 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941 const auto& p = layer->getParent();
2942 if (p == nullptr) {
2943 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2944 if (layer->setLayer(s.z) && idx >= 0) {
2945 mCurrentState.layersSortedByZ.removeAt(idx);
2946 mCurrentState.layersSortedByZ.add(layer);
2947 // we need traversal (state changed)
2948 // AND transaction (list changed)
2949 flags |= eTransactionNeeded|eTraversalNeeded;
2950 }
2951 } else {
2952 if (p->setChildLayer(layer, s.z)) {
2953 flags |= eTransactionNeeded|eTraversalNeeded;
2954 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002955 }
2956 }
Robert Carrdb66e622017-04-10 16:55:57 -07002957 if (what & layer_state_t::eRelativeLayerChanged) {
2958 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2959 flags |= eTransactionNeeded|eTraversalNeeded;
2960 }
2961 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002962 if (what & layer_state_t::eSizeChanged) {
2963 if (layer->setSize(s.w, s.h)) {
2964 flags |= eTraversalNeeded;
2965 }
2966 }
2967 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 flags |= eTraversalNeeded;
2970 }
2971 if (what & layer_state_t::eMatrixChanged) {
2972 if (layer->setMatrix(s.matrix))
2973 flags |= eTraversalNeeded;
2974 }
2975 if (what & layer_state_t::eTransparentRegionChanged) {
2976 if (layer->setTransparentRegionHint(s.transparentRegion))
2977 flags |= eTraversalNeeded;
2978 }
Dan Stoza23116082015-06-18 14:58:39 -07002979 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 if (layer->setFlags(s.flags, s.mask))
2981 flags |= eTraversalNeeded;
2982 }
2983 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002984 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002985 flags |= eTraversalNeeded;
2986 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002987 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002988 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002989 flags |= eTraversalNeeded;
2990 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002992 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 // We only allow setting layer stacks for top level layers,
2994 // everything else inherits layer stack from its parent.
2995 if (layer->hasParent()) {
2996 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2997 layer->getName().string());
2998 } else if (idx < 0) {
2999 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3000 "that also does not appear in the top level layer list. Something"
3001 " has gone wrong.", layer->getName().string());
3002 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003003 mCurrentState.layersSortedByZ.removeAt(idx);
3004 mCurrentState.layersSortedByZ.add(layer);
3005 // we need traversal (state changed)
3006 // AND transaction (list changed)
3007 flags |= eTransactionNeeded|eTraversalNeeded;
3008 }
3009 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003010 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003011 if (s.barrierHandle != nullptr) {
3012 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3013 } else if (s.barrierGbp != nullptr) {
3014 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3015 if (authenticateSurfaceTextureLocked(gbp)) {
3016 const auto& otherLayer =
3017 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3018 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3019 } else {
3020 ALOGE("Attempt to defer transaction to to an"
3021 " unrecognized GraphicBufferProducer");
3022 }
3023 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003024 // We don't trigger a traversal here because if no other state is
3025 // changed, we don't want this to cause any more work
3026 }
Robert Carr1db73f62016-12-21 12:58:51 -08003027 if (what & layer_state_t::eReparentChildren) {
3028 if (layer->reparentChildren(s.reparentHandle)) {
3029 flags |= eTransactionNeeded|eTraversalNeeded;
3030 }
3031 }
Robert Carr9524cb32017-02-13 11:32:32 -08003032 if (what & layer_state_t::eDetachChildren) {
3033 layer->detachChildren();
3034 }
Robert Carrc3574f72016-03-24 12:19:32 -07003035 if (what & layer_state_t::eOverrideScalingModeChanged) {
3036 layer->setOverrideScalingMode(s.overrideScalingMode);
3037 // We don't trigger a traversal here because if no other state is
3038 // changed, we don't want this to cause any more work
3039 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003040 }
3041 return flags;
3042}
3043
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003044status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003045 const String8& name,
3046 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003047 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003048 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3049 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003051 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003052 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003053 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003054 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003055 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003056
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003057 status_t result = NO_ERROR;
3058
3059 sp<Layer> layer;
3060
Cody Northropbc755282017-03-31 12:00:08 -06003061 String8 uniqueName = getUniqueLayerName(name);
3062
Mathias Agopian3165cc22012-08-08 19:42:09 -07003063 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3064 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003065 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003066 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003069 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003070 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003071 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003072 handle, gbp, &layer);
3073 break;
3074 default:
3075 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 break;
3077 }
3078
Dan Stoza7d89d062015-04-30 13:29:25 -07003079 if (result != NO_ERROR) {
3080 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003082
Albert Chaulk479c60c2017-01-27 14:21:34 -05003083 layer->setInfo(windowType, ownerUid);
3084
Robert Carr1f0a16a2016-10-24 16:27:39 -07003085 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003086 if (result != NO_ERROR) {
3087 return result;
3088 }
Irvelffc9efc2016-07-27 15:16:37 -07003089 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003090
3091 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003092 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093}
3094
Cody Northropbc755282017-03-31 12:00:08 -06003095String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3096{
3097 bool matchFound = true;
3098 uint32_t dupeCounter = 0;
3099
3100 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3101 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3102
3103 // Loop over layers until we're sure there is no matching name
3104 while (matchFound) {
3105 matchFound = false;
3106 mDrawingState.traverseInZOrder([&](Layer* layer) {
3107 if (layer->getName() == uniqueName) {
3108 matchFound = true;
3109 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3110 }
3111 });
3112 }
3113
3114 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3115
3116 return uniqueName;
3117}
3118
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003119status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3120 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3121 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122{
3123 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003124 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125 case PIXEL_FORMAT_TRANSPARENT:
3126 case PIXEL_FORMAT_TRANSLUCENT:
3127 format = PIXEL_FORMAT_RGBA_8888;
3128 break;
3129 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003130 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 break;
3132 }
3133
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003134 *outLayer = new Layer(this, client, name, w, h, flags);
3135 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3136 if (err == NO_ERROR) {
3137 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003138 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003140
3141 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3142 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143}
3144
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003145status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3146 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3147 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003149 *outLayer = new LayerDim(this, client, name, w, h, flags);
3150 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003151 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003152 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003153}
3154
Mathias Agopianac9fa422013-02-11 16:40:36 -08003155status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156{
Robert Carr9524cb32017-02-13 11:32:32 -08003157 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003158 status_t err = NO_ERROR;
3159 sp<Layer> l(client->getLayerUser(handle));
3160 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003161 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003162 err = removeLayer(l);
3163 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3164 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003165 }
3166 return err;
3167}
3168
Mathias Agopian13127d82013-03-05 17:47:11 -08003169status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003170{
Mathias Agopian67106042013-03-14 19:18:13 -07003171 // called by ~LayerCleaner() when all references to the IBinder (handle)
3172 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003173 sp<Layer> l = layer.promote();
3174 if (l == nullptr) {
3175 // The layer has already been removed, carry on
3176 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003177 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003178 // If we have a parent, then we can continue to live as long as it does.
3179 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180}
3181
Mathias Agopianb60314a2012-04-10 22:09:54 -07003182// ---------------------------------------------------------------------------
3183
Andy McFadden13a082e2012-08-24 10:16:42 -07003184void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003185 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003186 Vector<ComposerState> state;
3187 Vector<DisplayState> displays;
3188 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003189 d.what = DisplayState::eDisplayProjectionChanged |
3190 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003191 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003192 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003193 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003194 d.frame.makeInvalid();
3195 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003196 d.width = 0;
3197 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003198 displays.add(d);
3199 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003200 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003201
Dan Stoza9e56aa02015-11-02 13:00:03 -08003202 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003204 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003205
Brian Andersond0010582017-03-07 13:20:31 -08003206 // Use phase of 0 since phase is not known.
3207 // Use latency of 0, which will snap to the ideal latency.
3208 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003209}
3210
3211void SurfaceFlinger::initializeDisplays() {
3212 class MessageScreenInitialized : public MessageBase {
3213 SurfaceFlinger* flinger;
3214 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003215 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003216 virtual bool handler() {
3217 flinger->onInitializeDisplays();
3218 return true;
3219 }
3220 };
3221 sp<MessageBase> msg = new MessageScreenInitialized(this);
3222 postMessageAsync(msg); // we may be called from main thread, use async message
3223}
3224
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003225void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3226 int mode) {
3227 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3228 this);
3229 int32_t type = hw->getDisplayType();
3230 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003231
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003232 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003233 return;
3234 }
3235
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003236 hw->setPowerMode(mode);
3237 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3238 ALOGW("Trying to set power mode for virtual display");
3239 return;
3240 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003241
Irvelffc9efc2016-07-27 15:16:37 -07003242 if (mInterceptor.isEnabled()) {
3243 Mutex::Autolock _l(mStateLock);
3244 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3245 if (idx < 0) {
3246 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3247 return;
3248 }
3249 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3250 }
3251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003252 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003253 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003254 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003255 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3256 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003257 // FIXME: eventthread only knows about the main display right now
3258 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003259 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003260 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003262 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003263 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003264 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003265
3266 struct sched_param param = {0};
3267 param.sched_priority = 1;
3268 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3269 ALOGW("Couldn't set SCHED_FIFO on display on");
3270 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003271 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003272 // Turn off the display
3273 struct sched_param param = {0};
3274 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3275 ALOGW("Couldn't set SCHED_OTHER on display off");
3276 }
3277
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003278 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003279 disableHardwareVsync(true); // also cancels any in-progress resync
3280
Mathias Agopiancde87a32012-09-13 14:09:01 -07003281 // FIXME: eventthread only knows about the main display right now
3282 mEventThread->onScreenReleased();
3283 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003284
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003285 getHwComposer().setPowerMode(type, mode);
3286 mVisibleRegionsDirty = true;
3287 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003288 } else if (mode == HWC_POWER_MODE_DOZE ||
3289 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003290 // Update display while dozing
3291 getHwComposer().setPowerMode(type, mode);
3292 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3293 // FIXME: eventthread only knows about the main display right now
3294 mEventThread->onScreenAcquired();
3295 resyncToHardwareVsync(true);
3296 }
3297 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3298 // Leave display going to doze
3299 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3300 disableHardwareVsync(true); // also cancels any in-progress resync
3301 // FIXME: eventthread only knows about the main display right now
3302 mEventThread->onScreenReleased();
3303 }
3304 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003305 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003306 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003307 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003308 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003309}
3310
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003311void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3312 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003313 SurfaceFlinger& mFlinger;
3314 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003315 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003316 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003317 MessageSetPowerMode(SurfaceFlinger& flinger,
3318 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3319 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003320 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003321 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003322 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003323 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003324 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003325 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003326 ALOGW("Attempt to set power mode = %d for virtual display",
3327 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003328 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003329 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003330 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003331 return true;
3332 }
3333 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003334 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003335 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003336}
3337
3338// ---------------------------------------------------------------------------
3339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3341{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003343
Mathias Agopianbd115332013-04-18 16:41:04 -07003344 IPCThreadState* ipc = IPCThreadState::self();
3345 const int pid = ipc->getCallingPid();
3346 const int uid = ipc->getCallingUid();
3347 if ((uid != AID_SHELL) &&
3348 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003349 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003350 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003352 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003353 // (this would indicate SF is stuck, but we want to be able to
3354 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003355 status_t err = mStateLock.timedLock(s2ns(1));
3356 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003357 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003358 result.appendFormat(
3359 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3360 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003361 }
3362
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003363 bool dumpAll = true;
3364 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003365 size_t numArgs = args.size();
3366 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003367 if ((index < numArgs) &&
3368 (args[index] == String16("--list"))) {
3369 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003370 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003371 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003372 }
3373
3374 if ((index < numArgs) &&
3375 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003376 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003377 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003378 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003379 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003380
3381 if ((index < numArgs) &&
3382 (args[index] == String16("--latency-clear"))) {
3383 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003384 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003385 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003386 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003387
3388 if ((index < numArgs) &&
3389 (args[index] == String16("--dispsync"))) {
3390 index++;
3391 mPrimaryDispSync.dump(result);
3392 dumpAll = false;
3393 }
Dan Stozab90cf072015-03-05 11:05:59 -08003394
3395 if ((index < numArgs) &&
3396 (args[index] == String16("--static-screen"))) {
3397 index++;
3398 dumpStaticScreenStats(result);
3399 dumpAll = false;
3400 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003401
3402 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003403 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003404 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003405 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003406 dumpAll = false;
3407 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003408
3409 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3410 index++;
3411 dumpWideColorInfo(result);
3412 dumpAll = false;
3413 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003415
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003416 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003417 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003418 }
3419
Mathias Agopian9795c422009-08-26 16:36:26 -07003420 if (locked) {
3421 mStateLock.unlock();
3422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423 }
3424 write(fd, result.string(), result.size());
3425 return NO_ERROR;
3426}
3427
Dan Stozac7014012014-02-14 15:03:43 -08003428void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3429 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003430{
Robert Carr2047fae2016-11-28 14:09:09 -08003431 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003433 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003434}
3435
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003436void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003437 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438{
3439 String8 name;
3440 if (index < args.size()) {
3441 name = String8(args[index]);
3442 index++;
3443 }
3444
Dan Stoza9e56aa02015-11-02 13:00:03 -08003445 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3446 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003447 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003448
3449 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003450 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003451 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003452 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003453 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003454 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003455 }
Robert Carr2047fae2016-11-28 14:09:09 -08003456 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457 }
3458}
3459
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003460void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003461 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003462{
3463 String8 name;
3464 if (index < args.size()) {
3465 name = String8(args[index]);
3466 index++;
3467 }
3468
Robert Carr2047fae2016-11-28 14:09:09 -08003469 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003470 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003471 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003472 }
Robert Carr2047fae2016-11-28 14:09:09 -08003473 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003474
Svetoslavd85084b2014-03-20 10:28:31 -07003475 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003476}
3477
Jamie Gennis6547ff42013-07-16 20:12:42 -07003478// This should only be called from the main thread. Otherwise it would need
3479// the lock and should use mCurrentState rather than mDrawingState.
3480void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003481 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003482 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003483 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003484
3485 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3486}
3487
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003488void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003489{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003490 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003491 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3492
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003493 if (isLayerTripleBufferingDisabled())
3494 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003495
3496 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003497 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003498 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003499 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003500 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3501 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003502 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003503}
3504
Dan Stozab90cf072015-03-05 11:05:59 -08003505void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3506{
3507 result.appendFormat("Static screen stats:\n");
3508 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3509 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3510 float percent = 100.0f *
3511 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3512 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3513 b + 1, bucketTimeSec, percent);
3514 }
3515 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3516 float percent = 100.0f *
3517 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3518 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3519 NUM_BUCKETS - 1, bucketTimeSec, percent);
3520}
3521
Dan Stozae77c7662016-05-13 11:37:28 -07003522void SurfaceFlinger::recordBufferingStats(const char* layerName,
3523 std::vector<OccupancyTracker::Segment>&& history) {
3524 Mutex::Autolock lock(mBufferingStatsMutex);
3525 auto& stats = mBufferingStats[layerName];
3526 for (const auto& segment : history) {
3527 if (!segment.usedThirdBuffer) {
3528 stats.twoBufferTime += segment.totalTime;
3529 }
3530 if (segment.occupancyAverage < 1.0f) {
3531 stats.doubleBufferedTime += segment.totalTime;
3532 } else if (segment.occupancyAverage < 2.0f) {
3533 stats.tripleBufferedTime += segment.totalTime;
3534 }
3535 ++stats.numSegments;
3536 stats.totalTime += segment.totalTime;
3537 }
3538}
3539
Brian Andersond6927fb2016-07-23 23:37:30 -07003540void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3541 result.appendFormat("Layer frame timestamps:\n");
3542
3543 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3544 const size_t count = currentLayers.size();
3545 for (size_t i=0 ; i<count ; i++) {
3546 currentLayers[i]->dumpFrameEvents(result);
3547 }
3548}
3549
Dan Stozae77c7662016-05-13 11:37:28 -07003550void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3551 result.append("Buffering stats:\n");
3552 result.append(" [Layer name] <Active time> <Two buffer> "
3553 "<Double buffered> <Triple buffered>\n");
3554 Mutex::Autolock lock(mBufferingStatsMutex);
3555 typedef std::tuple<std::string, float, float, float> BufferTuple;
3556 std::map<float, BufferTuple, std::greater<float>> sorted;
3557 for (const auto& statsPair : mBufferingStats) {
3558 const char* name = statsPair.first.c_str();
3559 const BufferingStats& stats = statsPair.second;
3560 if (stats.numSegments == 0) {
3561 continue;
3562 }
3563 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3564 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3565 stats.totalTime;
3566 float doubleBufferRatio = static_cast<float>(
3567 stats.doubleBufferedTime) / stats.totalTime;
3568 float tripleBufferRatio = static_cast<float>(
3569 stats.tripleBufferedTime) / stats.totalTime;
3570 sorted.insert({activeTime, {name, twoBufferRatio,
3571 doubleBufferRatio, tripleBufferRatio}});
3572 }
3573 for (const auto& sortedPair : sorted) {
3574 float activeTime = sortedPair.first;
3575 const BufferTuple& values = sortedPair.second;
3576 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3577 std::get<0>(values).c_str(), activeTime,
3578 std::get<1>(values), std::get<2>(values),
3579 std::get<3>(values));
3580 }
3581 result.append("\n");
3582}
3583
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003584void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3585 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3586
3587 // TODO: print out if wide-color mode is active or not
3588
3589 for (size_t d = 0; d < mDisplays.size(); d++) {
3590 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3591 int32_t hwcId = displayDevice->getHwcDisplayId();
3592 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3593 continue;
3594 }
3595
3596 result.appendFormat("Display %d color modes:\n", hwcId);
3597 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3598 for (auto&& mode : modes) {
3599 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3600 }
3601
3602 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3603 result.appendFormat(" Current color mode: %s (%d)\n",
3604 decodeColorMode(currentMode).c_str(), currentMode);
3605 }
3606 result.append("\n");
3607}
3608
Mathias Agopian74d211a2013-04-22 16:55:35 +02003609void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3610 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003612 bool colorize = false;
3613 if (index < args.size()
3614 && (args[index] == String16("--color"))) {
3615 colorize = true;
3616 index++;
3617 }
3618
3619 Colorizer colorizer(colorize);
3620
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003621 // figure out if we're stuck somewhere
3622 const nsecs_t now = systemTime();
3623 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3624 const nsecs_t inTransaction(mDebugInTransaction);
3625 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3626 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3627
3628 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003629 * Dump library configuration.
3630 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003631
3632 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003633 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003634 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003635 appendSfConfigString(result);
3636 appendUiConfigString(result);
3637 appendGuiConfigString(result);
3638 result.append("\n");
3639
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003640 result.append("\nWide-Color information:\n");
3641 dumpWideColorInfo(result);
3642
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003643 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003644 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003645 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003646 result.append(SyncFeatures::getInstance().toString());
3647 result.append("\n");
3648
Dan Stoza9e56aa02015-11-02 13:00:03 -08003649 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3650
Andy McFadden41d67d72014-04-25 16:58:34 -07003651 colorizer.bold(result);
3652 result.append("DispSync configuration: ");
3653 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003654 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003655 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003656 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003657 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003658 result.append("\n");
3659
Dan Stozab90cf072015-03-05 11:05:59 -08003660 // Dump static screen stats
3661 result.append("\n");
3662 dumpStaticScreenStats(result);
3663 result.append("\n");
3664
Dan Stozae77c7662016-05-13 11:37:28 -07003665 dumpBufferingStats(result);
3666
Andy McFadden4803b742012-09-24 19:07:20 -07003667 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003668 * Dump the visible layer list
3669 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003670 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003671 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003672 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003673 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003674 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003675 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003676
3677 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003678 * Dump Display state
3679 */
3680
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003681 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003682 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003683 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003684 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3685 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003686 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003687 }
3688
3689 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003690 * Dump SurfaceFlinger global state
3691 */
3692
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003693 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003694 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003695 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003696
Mathias Agopian888c8222012-08-04 21:10:38 -07003697 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003698 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003699
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003700 colorizer.bold(result);
3701 result.appendFormat("EGL implementation : %s\n",
3702 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3703 colorizer.reset(result);
3704 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003705 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003706
Mathias Agopian875d8e12013-06-07 15:35:48 -07003707 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003708
Mathias Agopian42977342012-08-05 00:40:46 -07003709 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3711 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003712 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003713 " last eglSwapBuffers() time: %f us\n"
3714 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003715 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716 " refresh-rate : %f fps\n"
3717 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003718 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003719 " gpu_to_cpu_unsupported : %d\n"
3720 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003721 mLastSwapBufferTime/1000.0,
3722 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003723 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003724 1e9 / activeConfig->getVsyncPeriod(),
3725 activeConfig->getDpiX(),
3726 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003727 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003728
Mathias Agopian74d211a2013-04-22 16:55:35 +02003729 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003730 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731
Mathias Agopian74d211a2013-04-22 16:55:35 +02003732 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003733 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003734
3735 /*
3736 * VSYNC state
3737 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003738 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003739 result.append("\n");
3740
3741 /*
3742 * HWC layer minidump
3743 */
3744 for (size_t d = 0; d < mDisplays.size(); d++) {
3745 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3746 int32_t hwcId = displayDevice->getHwcDisplayId();
3747 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3748 continue;
3749 }
3750
3751 result.appendFormat("Display %d HWC layers:\n", hwcId);
3752 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003753 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003754 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003755 });
Dan Stozae22aec72016-08-01 13:20:59 -07003756 result.append("\n");
3757 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758
3759 /*
3760 * Dump HWComposer state
3761 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003762 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003764 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003765 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003766 result.appendFormat(" h/w composer %s\n",
3767 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003768 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003769
3770 /*
3771 * Dump gralloc state
3772 */
3773 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3774 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003775
3776 /*
3777 * Dump VrFlinger state if in use.
3778 */
3779 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3780 result.append("VrFlinger state:\n");
3781 result.append(mVrFlinger->Dump().c_str());
3782 result.append("\n");
3783 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784}
3785
Mathias Agopian13127d82013-03-05 17:47:11 -08003786const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003787SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003788 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003789 wp<IBinder> dpy;
3790 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3791 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3792 dpy = mDisplays.keyAt(i);
3793 break;
3794 }
3795 }
3796 if (dpy == NULL) {
3797 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3798 // Just use the primary display so we have something to return
3799 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3800 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003801 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003802}
3803
Keun young Park63f165f2012-08-31 10:53:36 -07003804bool SurfaceFlinger::startDdmConnection()
3805{
3806 void* libddmconnection_dso =
3807 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3808 if (!libddmconnection_dso) {
3809 return false;
3810 }
3811 void (*DdmConnection_start)(const char* name);
3812 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003813 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003814 if (!DdmConnection_start) {
3815 dlclose(libddmconnection_dso);
3816 return false;
3817 }
3818 (*DdmConnection_start)(getServiceName());
3819 return true;
3820}
3821
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003822status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 switch (code) {
3824 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003825 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003827 case CLEAR_ANIMATION_FRAME_STATS:
3828 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003829 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003830 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003831 {
3832 // codes that require permission check
3833 IPCThreadState* ipc = IPCThreadState::self();
3834 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003835 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003836 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003837 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003838 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003839 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003841 break;
3842 }
Robert Carr1db73f62016-12-21 12:58:51 -08003843 /*
3844 * Calling setTransactionState is safe, because you need to have been
3845 * granted a reference to Client* and Handle* to do anything with it.
3846 *
3847 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3848 */
3849 case SET_TRANSACTION_STATE:
3850 case CREATE_SCOPED_CONNECTION:
3851 {
3852 return OK;
3853 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003854 case CAPTURE_SCREEN:
3855 {
3856 // codes that require permission check
3857 IPCThreadState* ipc = IPCThreadState::self();
3858 const int pid = ipc->getCallingPid();
3859 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003860 if ((uid != AID_GRAPHICS) &&
3861 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003862 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003863 return PERMISSION_DENIED;
3864 }
3865 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 }
3867 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003868 return OK;
3869}
3870
3871status_t SurfaceFlinger::onTransact(
3872 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3873{
3874 status_t credentialCheck = CheckTransactCodeCredentials(code);
3875 if (credentialCheck != OK) {
3876 return credentialCheck;
3877 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003878
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3880 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003881 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003882 IPCThreadState* ipc = IPCThreadState::self();
3883 const int uid = ipc->getCallingUid();
3884 if (CC_UNLIKELY(uid != AID_SYSTEM
3885 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003886 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003887 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003888 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 return PERMISSION_DENIED;
3890 }
3891 int n;
3892 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003893 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003894 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003895 return NO_ERROR;
3896 case 1002: // SHOW_UPDATES
3897 n = data.readInt32();
3898 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003899 invalidateHwcGeometry();
3900 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003903 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003904 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003906 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003907 setTransactionFlags(
3908 eTransactionNeeded|
3909 eDisplayTransactionNeeded|
3910 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003911 return NO_ERROR;
3912 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003913 case 1006:{ // send empty update
3914 signalRefresh();
3915 return NO_ERROR;
3916 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003917 case 1008: // toggle use of hw composer
3918 n = data.readInt32();
3919 mDebugDisableHWC = n ? 1 : 0;
3920 invalidateHwcGeometry();
3921 repaintEverything();
3922 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003923 case 1009: // toggle use of transform hint
3924 n = data.readInt32();
3925 mDebugDisableTransformHint = n ? 1 : 0;
3926 invalidateHwcGeometry();
3927 repaintEverything();
3928 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003930 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 reply->writeInt32(0);
3932 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003933 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003934 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003935 return NO_ERROR;
3936 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003937 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003938 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003939 return NO_ERROR;
3940 }
3941 case 1014: {
3942 // daltonize
3943 n = data.readInt32();
3944 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003945 case 1:
3946 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3947 break;
3948 case 2:
3949 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3950 break;
3951 case 3:
3952 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3953 break;
3954 default:
3955 mDaltonizer.setType(ColorBlindnessType::None);
3956 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003957 }
3958 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003959 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003960 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003961 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003962 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003963 invalidateHwcGeometry();
3964 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003965 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003967 case 1015: {
3968 // apply a color matrix
3969 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003970 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003971 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003972 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003973 for (size_t j = 0; j < 4; j++) {
3974 mColorMatrix[i][j] = data.readFloat();
3975 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003976 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003977 } else {
3978 mColorMatrix = mat4();
3979 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003980
3981 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3982 // the division by w in the fragment shader
3983 float4 lastRow(transpose(mColorMatrix)[3]);
3984 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3985 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3986 }
3987
Alan Viverette9c5a3332013-09-12 20:04:35 -07003988 invalidateHwcGeometry();
3989 repaintEverything();
3990 return NO_ERROR;
3991 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003992 // This is an experimental interface
3993 // Needs to be shifted to proper binder interface when we productize
3994 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003995 n = data.readInt32();
3996 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003997 return NO_ERROR;
3998 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003999 case 1017: {
4000 n = data.readInt32();
4001 mForceFullDamage = static_cast<bool>(n);
4002 return NO_ERROR;
4003 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004004 case 1018: { // Modify Choreographer's phase offset
4005 n = data.readInt32();
4006 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4007 return NO_ERROR;
4008 }
4009 case 1019: { // Modify SurfaceFlinger's phase offset
4010 n = data.readInt32();
4011 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4012 return NO_ERROR;
4013 }
Irvel468051e2016-06-13 16:44:44 -07004014 case 1020: { // Layer updates interceptor
4015 n = data.readInt32();
4016 if (n) {
4017 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004018 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004019 }
4020 else{
4021 ALOGV("Interceptor disabled");
4022 mInterceptor.disable();
4023 }
4024 return NO_ERROR;
4025 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004026 case 1021: { // Disable HWC virtual displays
4027 n = data.readInt32();
4028 mUseHwcVirtualDisplays = !n;
4029 return NO_ERROR;
4030 }
Romain Guy0147a172017-06-01 13:53:56 -07004031 case 1022: { // Set saturation boost
4032 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4033
4034 invalidateHwcGeometry();
4035 repaintEverything();
4036 return NO_ERROR;
4037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 }
4039 }
4040 return err;
4041}
4042
Mathias Agopian53331da2011-08-22 21:44:41 -07004043void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004044 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004045 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004046}
4047
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004048// Checks that the requested width and height are valid and updates them to the display dimensions
4049// if they are set to 0
4050static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4051 Transform::orientation_flags rotation,
4052 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4053 // get screen geometry
4054 uint32_t displayWidth = displayDevice->getWidth();
4055 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004056
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004057 if (rotation & Transform::ROT_90) {
4058 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004059 }
4060
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004061 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4062 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4063 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4064 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004065 }
4066
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004067 if (*requestedWidth == 0) {
4068 *requestedWidth = displayWidth;
4069 }
4070 if (*requestedHeight == 0) {
4071 *requestedHeight = displayHeight;
4072 }
4073
4074 return NO_ERROR;
4075}
4076
4077// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4078class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004079public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004080 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4081 ~WindowDisconnector() {
4082 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004083 }
4084
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004085private:
4086 ANativeWindow* mWindow;
4087 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004088};
4089
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004090static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4091 uint32_t requestedHeight, bool hasWideColorDisplay,
4092 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4093 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4094 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4095
4096 int err = 0;
4097 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4098 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4099 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4100 err |= native_window_set_usage(window, usage);
4101
4102 if (hasWideColorDisplay) {
4103 err |= native_window_set_buffers_data_space(window,
4104 renderEngineUsesWideColor
4105 ? HAL_DATASPACE_DISPLAY_P3
4106 : HAL_DATASPACE_V0_SRGB);
4107 }
4108
4109 if (err != NO_ERROR) {
4110 return BAD_VALUE;
4111 }
4112
4113 /* TODO: Once we have the sync framework everywhere this can use
4114 * server-side waits on the fence that dequeueBuffer returns.
4115 */
4116 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4117 if (err != NO_ERROR) {
4118 return err;
4119 }
4120
4121 return NO_ERROR;
4122}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004123
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004124status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4125 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004126 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004127 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004128 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004129 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004130
4131 if (CC_UNLIKELY(display == 0))
4132 return BAD_VALUE;
4133
4134 if (CC_UNLIKELY(producer == 0))
4135 return BAD_VALUE;
4136
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004137 // if we have secure windows on this display, never allow the screen capture
4138 // unless the producer interface is local (i.e.: we can take a screenshot for
4139 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004140 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004141
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004142 // Convert to surfaceflinger's internal rotation type.
4143 Transform::orientation_flags rotationFlags;
4144 switch (rotation) {
4145 case ISurfaceComposer::eRotateNone:
4146 rotationFlags = Transform::ROT_0;
4147 break;
4148 case ISurfaceComposer::eRotate90:
4149 rotationFlags = Transform::ROT_90;
4150 break;
4151 case ISurfaceComposer::eRotate180:
4152 rotationFlags = Transform::ROT_180;
4153 break;
4154 case ISurfaceComposer::eRotate270:
4155 rotationFlags = Transform::ROT_270;
4156 break;
4157 default:
4158 rotationFlags = Transform::ROT_0;
4159 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4160 break;
4161 }
4162
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004163 { // Autolock scope
4164 Mutex::Autolock lock(mStateLock);
4165 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4166 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004167 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004168
4169 // create a surface (because we're a producer, and we need to
4170 // dequeue/queue a buffer)
4171 sp<Surface> surface = new Surface(producer, false);
4172
4173 // Put the screenshot Surface into async mode so that
4174 // Layer::headFenceHasSignaled will always return true and we'll latch the
4175 // first buffer regardless of whether or not its acquire fence has
4176 // signaled. This is needed to avoid a race condition in the rotation
4177 // animation. See b/30209608
4178 surface->setAsyncMode(true);
4179
4180 ANativeWindow* window = surface.get();
4181
4182 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4183 if (result != NO_ERROR) {
4184 return result;
4185 }
4186 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4187
4188 ANativeWindowBuffer* buffer = nullptr;
4189 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4190 getRenderEngine().usesWideColor(), &buffer);
4191 if (result != NO_ERROR) {
4192 return result;
4193 }
4194
4195 // This mutex protects syncFd and captureResult for communication of the return values from the
4196 // main thread back to this Binder thread
4197 std::mutex captureMutex;
4198 std::condition_variable captureCondition;
4199 std::unique_lock<std::mutex> captureLock(captureMutex);
4200 int syncFd = -1;
4201 std::optional<status_t> captureResult;
4202
4203 sp<LambdaMessage> message = new LambdaMessage([&]() {
4204 // If there is a refresh pending, bug out early and tell the binder thread to try again
4205 // after the refresh.
4206 if (mRefreshPending) {
4207 ATRACE_NAME("Skipping screenshot for now");
4208 std::unique_lock<std::mutex> captureLock(captureMutex);
4209 captureResult = std::make_optional<status_t>(EAGAIN);
4210 captureCondition.notify_one();
4211 return;
4212 }
4213
4214 status_t result = NO_ERROR;
4215 int fd = -1;
4216 {
4217 Mutex::Autolock _l(mStateLock);
4218 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4219 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4220 minLayerZ, maxLayerZ, useIdentityTransform,
4221 rotationFlags, isLocalScreenshot, &fd);
4222 }
4223
4224 {
4225 std::unique_lock<std::mutex> captureLock(captureMutex);
4226 syncFd = fd;
4227 captureResult = std::make_optional<status_t>(result);
4228 captureCondition.notify_one();
4229 }
4230 });
4231
4232 result = postMessageAsync(message);
4233 if (result == NO_ERROR) {
4234 captureCondition.wait(captureLock, [&]() { return captureResult; });
4235 while (*captureResult == EAGAIN) {
4236 captureResult.reset();
4237 result = postMessageAsync(message);
4238 if (result != NO_ERROR) {
4239 return result;
4240 }
4241 captureCondition.wait(captureLock, [&]() { return captureResult; });
4242 }
4243 result = *captureResult;
4244 }
4245
4246 if (result == NO_ERROR) {
4247 // queueBuffer takes ownership of syncFd
4248 result = window->queueBuffer(window, buffer, syncFd);
4249 }
4250
4251 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004252}
4253
Mathias Agopian180f10d2013-04-10 22:55:41 -07004254
4255void SurfaceFlinger::renderScreenImplLocked(
4256 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004257 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004258 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004259 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004260{
4261 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004262 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004263
4264 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004265 const int32_t hw_w = hw->getWidth();
4266 const int32_t hw_h = hw->getHeight();
4267 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004268 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004269
Dan Stozac1879002014-05-22 15:59:05 -07004270 // if a default or invalid sourceCrop is passed in, set reasonable values
4271 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4272 !sourceCrop.isValid()) {
4273 sourceCrop.setLeftTop(Point(0, 0));
4274 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4275 }
4276
4277 // ensure that sourceCrop is inside screen
4278 if (sourceCrop.left < 0) {
4279 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4280 }
Dan Stozabe31f442014-06-11 11:20:54 -07004281 if (sourceCrop.right > hw_w) {
4282 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004283 }
4284 if (sourceCrop.top < 0) {
4285 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4286 }
Dan Stozabe31f442014-06-11 11:20:54 -07004287 if (sourceCrop.bottom > hw_h) {
4288 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004289 }
4290
Romain Guy88d37dd2017-05-26 17:57:05 -07004291#ifdef USE_HWC2
4292 engine.setWideColor(hw->getWideColorSupport());
4293 engine.setColorMode(hw->getActiveColorMode());
4294#endif
4295
Mathias Agopian180f10d2013-04-10 22:55:41 -07004296 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004297 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004298
4299 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004300 engine.setViewportAndProjection(
4301 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004302 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004303
4304 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004305 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004306
Robert Carr1f0a16a2016-10-24 16:27:39 -07004307 // We loop through the first level of layers without traversing,
4308 // as we need to interpret min/max layer Z in the top level Z space.
4309 for (const auto& layer : mDrawingState.layersSortedByZ) {
4310 if (layer->getLayerStack() != hw->getLayerStack()) {
4311 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004312 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004313 const Layer::State& state(layer->getDrawingState());
4314 if (state.z < minLayerZ || state.z > maxLayerZ) {
4315 continue;
4316 }
Dan Stoza412903f2017-04-27 13:42:17 -07004317 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004318 if (!layer->isVisible()) {
4319 return;
4320 }
4321 if (filtering) layer->setFiltering(true);
4322 layer->draw(hw, useIdentityTransform);
4323 if (filtering) layer->setFiltering(false);
4324 });
4325 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004326
Mathias Agopian931bda12013-08-28 18:11:46 -07004327 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004328}
4329
Dan Stozaabcda352017-06-01 14:37:39 -07004330// A simple RAII class that holds an EGLImage and destroys it either:
4331// a) When the destroy() method is called
4332// b) When the object goes out of scope
4333class ImageHolder {
4334public:
4335 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4336 ~ImageHolder() { destroy(); }
4337
4338 void destroy() {
4339 if (mImage != EGL_NO_IMAGE_KHR) {
4340 eglDestroyImageKHR(mDisplay, mImage);
4341 mImage = EGL_NO_IMAGE_KHR;
4342 }
4343 }
4344
4345private:
4346 const EGLDisplay mDisplay;
4347 EGLImageKHR mImage;
4348};
4349
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004350status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4351 ANativeWindowBuffer* buffer, Rect sourceCrop,
4352 uint32_t reqWidth, uint32_t reqHeight,
4353 int32_t minLayerZ, int32_t maxLayerZ,
4354 bool useIdentityTransform,
4355 Transform::orientation_flags rotation,
4356 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004357 ATRACE_CALL();
4358
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004359 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004360 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004361 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004362 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4363 (state.z < minLayerZ || state.z > maxLayerZ)) {
4364 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004365 }
Dan Stoza412903f2017-04-27 13:42:17 -07004366 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004367 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4368 layer->isSecure());
4369 });
4370 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004371
4372 if (!isLocalScreenshot && secureLayerIsVisible) {
4373 ALOGW("FB is protected: PERMISSION_DENIED");
4374 return PERMISSION_DENIED;
4375 }
4376
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004377 int syncFd = -1;
4378 // create an EGLImage from the buffer so we can later
4379 // turn it into a texture
4380 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4381 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4382 if (image == EGL_NO_IMAGE_KHR) {
4383 return BAD_VALUE;
4384 }
4385
Dan Stozaabcda352017-06-01 14:37:39 -07004386 // This will automatically destroy the image if we return before calling its destroy method
4387 ImageHolder imageHolder(mEGLDisplay, image);
4388
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004389 // this binds the given EGLImage as a framebuffer for the
4390 // duration of this scope.
4391 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004392 if (imageBond.getStatus() != NO_ERROR) {
4393 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004394 return INVALID_OPERATION;
4395 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004396
Dan Stozaabcda352017-06-01 14:37:39 -07004397 // this will in fact render into our dequeued buffer
4398 // via an FBO, which means we didn't have to create
4399 // an EGLSurface and therefore we're not
4400 // dependent on the context's EGLConfig.
4401 renderScreenImplLocked(
4402 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4403 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004404
Dan Stozaabcda352017-06-01 14:37:39 -07004405 // Attempt to create a sync khr object that can produce a sync point. If that
4406 // isn't available, create a non-dupable sync object in the fallback path and
4407 // wait on it directly.
4408 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4409 if (!DEBUG_SCREENSHOTS) {
4410 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4411 // native fence fd will not be populated until flush() is done.
4412 getRenderEngine().flush();
4413 }
4414
4415 if (sync != EGL_NO_SYNC_KHR) {
4416 // get the sync fd
4417 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4418 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4419 ALOGW("captureScreen: failed to dup sync khr object");
4420 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004421 }
Dan Stozaabcda352017-06-01 14:37:39 -07004422 eglDestroySyncKHR(mEGLDisplay, sync);
4423 } else {
4424 // fallback path
4425 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004426 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004427 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4428 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4429 EGLint eglErr = eglGetError();
4430 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4431 ALOGW("captureScreen: fence wait timed out");
4432 } else {
4433 ALOGW_IF(eglErr != EGL_SUCCESS,
4434 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004435 }
4436 eglDestroySyncKHR(mEGLDisplay, sync);
4437 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004438 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004439 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004440 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004441 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004442
4443 if (DEBUG_SCREENSHOTS) {
4444 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4445 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4446 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4447 hw, minLayerZ, maxLayerZ);
4448 delete [] pixels;
4449 }
4450
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004451 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004452 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004453
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004454 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004455}
4456
Mathias Agopiand5556842013-09-19 17:08:37 -07004457void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004458 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004459 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004460 for (size_t y=0 ; y<h ; y++) {
4461 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4462 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004463 if (p[x] != 0xFF000000) return;
4464 }
4465 }
4466 ALOGE("*** we just took a black screenshot ***\n"
4467 "requested minz=%d, maxz=%d, layerStack=%d",
4468 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004469
Robert Carr2047fae2016-11-28 14:09:09 -08004470 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004471 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004472 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004473 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4474 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004475 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004476 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4477 layer->isVisible() ? '+' : '-',
4478 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004479 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004480 i++;
4481 });
4482 }
4483 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004484 }
4485}
4486
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004487// ---------------------------------------------------------------------------
4488
Dan Stoza412903f2017-04-27 13:42:17 -07004489void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4490 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004491}
4492
Dan Stoza412903f2017-04-27 13:42:17 -07004493void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4494 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004495}
4496
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004498
4499
4500#if defined(__gl_h_)
4501#error "don't include gl/gl.h in this file"
4502#endif
4503
4504#if defined(__gl2_h_)
4505#error "don't include gl2/gl2.h in this file"
4506#endif