blob: bcc30f62814235cf29ac4202318893a688ce7a8e [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
Saurabh Shahf4174532017-07-13 10:45:07 -0700198 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 // debugging stuff...
201 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700202
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700204 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700205
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206 property_get("debug.sf.showupdates", value, "0");
207 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700208
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700209 property_get("debug.sf.ddms", value, "0");
210 mDebugDDMS = atoi(value);
211 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700212 if (!startDdmConnection()) {
213 // start failed, and DDMS debugging not enabled
214 mDebugDDMS = 0;
215 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700216 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700217 ALOGI_IF(mDebugRegion, "showupdates enabled");
218 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700219
220 property_get("debug.sf.disable_backpressure", value, "0");
221 mPropagateBackpressure = !atoi(value);
222 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700223
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800224 property_get("debug.sf.enable_hwc_vds", value, "0");
225 mUseHwcVirtualDisplays = atoi(value);
226 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800228 property_get("ro.sf.disable_triple_buffer", value, "1");
229 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800230 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700231
Romain Guy11d63f42017-07-20 12:47:14 -0700232 // We should be reading 'persist.sys.sf.color_saturation' here
233 // but since /data may be encrypted, we need to wait until after vold
234 // comes online to attempt to read the property. The property is
235 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236}
237
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238void SurfaceFlinger::onFirstRef()
239{
240 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800241}
242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243SurfaceFlinger::~SurfaceFlinger()
244{
Mathias Agopiana4912602012-07-12 14:25:33 -0700245 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
246 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
247 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248}
249
Dan Stozac7014012014-02-14 15:03:43 -0800250void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251{
252 // the window manager died on us. prepare its eulogy.
253
Andy McFadden13a082e2012-08-24 10:16:42 -0700254 // restore initial conditions (default device unblank, etc)
255 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800256
257 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700258 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800259}
260
Robert Carr1db73f62016-12-21 12:58:51 -0800261static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700262 status_t err = client->initCheck();
263 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800264 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 }
Robert Carr1db73f62016-12-21 12:58:51 -0800266 return nullptr;
267}
268
269sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
270 return initClient(new Client(this));
271}
272
273sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
274 const sp<IGraphicBufferProducer>& gbp) {
275 if (authenticateSurfaceTexture(gbp) == false) {
276 return nullptr;
277 }
278 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
279 if (layer == nullptr) {
280 return nullptr;
281 }
282
283 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700286sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
287 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288{
289 class DisplayToken : public BBinder {
290 sp<SurfaceFlinger> flinger;
291 virtual ~DisplayToken() {
292 // no more references, this display must be terminated
293 Mutex::Autolock _l(flinger->mStateLock);
294 flinger->mCurrentState.displays.removeItem(this);
295 flinger->setTransactionFlags(eDisplayTransactionNeeded);
296 }
297 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700298 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 : flinger(flinger) {
300 }
301 };
302
303 sp<BBinder> token = new DisplayToken(this);
304
305 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700306 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700307 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700308 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700309 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700310 return token;
311}
312
Jesse Hall6c913be2013-08-08 12:15:49 -0700313void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
314 Mutex::Autolock _l(mStateLock);
315
316 ssize_t idx = mCurrentState.displays.indexOfKey(display);
317 if (idx < 0) {
318 ALOGW("destroyDisplay: invalid display token");
319 return;
320 }
321
322 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
323 if (!info.isVirtualDisplay()) {
324 ALOGE("destroyDisplay called for non-virtual display");
325 return;
326 }
Irvelffc9efc2016-07-27 15:16:37 -0700327 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700328 mCurrentState.displays.removeItemsAt(idx);
329 setTransactionFlags(eDisplayTransactionNeeded);
330}
331
Jesse Hall692c7232012-11-08 15:41:56 -0800332void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800333 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800334 ALOGW_IF(mBuiltinDisplays[type],
335 "Overwriting display token for display type %d", type);
336 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800337 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700338 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800339 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700340 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800341}
342
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700344 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
346 return NULL;
347 }
Jesse Hall692c7232012-11-08 15:41:56 -0800348 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351void SurfaceFlinger::bootFinished()
352{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700353 if (mStartPropertySetThread->join() != NO_ERROR) {
354 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356 const nsecs_t now = systemTime();
357 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000358 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700359
360 // wait patiently for the window manager death
361 const String16 name("window");
362 sp<IBinder> window(defaultServiceManager()->getService(name));
363 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700364 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700365 }
366
Steven Thomas050b2c82017-03-06 11:45:16 -0800367 if (mVrFlinger) {
368 mVrFlinger->OnBootFinished();
369 }
370
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700371 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700372 // formerly we would just kill the process, but we now ask it to exit so it
373 // can choose where to stop the animation.
374 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700375
376 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
377 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
378 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700379
Romain Guyc53d3552017-07-20 18:49:46 -0700380 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
381 mBootFinished = true;
382
Romain Guy11d63f42017-07-20 12:47:14 -0700383 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700384
385#ifdef USE_HWC2
386 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
387 if (hw->getWideColorSupport()) {
388 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
389 }
390#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700391 });
Romain Guyc53d3552017-07-20 18:49:46 -0700392 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian3f844832013-08-07 21:24:32 -0700395void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700396 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700397 RenderEngine& engine;
398 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700399 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700400 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
401 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700402 }
403 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700404 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700405 return true;
406 }
407 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700408 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700409}
410
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700411class DispSyncSource : public VSyncSource, private DispSync::Callback {
412public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700413 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000414 const char* name) :
415 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700416 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700417 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000418 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
419 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 mDispSync(dispSync),
421 mCallbackMutex(),
422 mCallback(),
423 mVsyncMutex(),
424 mPhaseOffset(phaseOffset),
425 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700426
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 virtual ~DispSyncSource() {}
428
429 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000432 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433 static_cast<DispSync::Callback*>(this));
434 if (err != NO_ERROR) {
435 ALOGE("error registering vsync callback: %s (%d)",
436 strerror(-err), err);
437 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700438 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 } else {
440 status_t err = mDispSync->removeEventListener(
441 static_cast<DispSync::Callback*>(this));
442 if (err != NO_ERROR) {
443 ALOGE("error unregistering vsync callback: %s (%d)",
444 strerror(-err), err);
445 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700446 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700448 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 }
450
451 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700452 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 mCallback = callback;
454 }
455
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700456 virtual void setPhaseOffset(nsecs_t phaseOffset) {
457 Mutex::Autolock lock(mVsyncMutex);
458
459 // Normalize phaseOffset to [0, period)
460 auto period = mDispSync->getPeriod();
461 phaseOffset %= period;
462 if (phaseOffset < 0) {
463 // If we're here, then phaseOffset is in (-period, 0). After this
464 // operation, it will be in (0, period)
465 phaseOffset += period;
466 }
467 mPhaseOffset = phaseOffset;
468
469 // If we're not enabled, we don't need to mess with the listeners
470 if (!mEnabled) {
471 return;
472 }
473
474 // Remove the listener with the old offset
475 status_t err = mDispSync->removeEventListener(
476 static_cast<DispSync::Callback*>(this));
477 if (err != NO_ERROR) {
478 ALOGE("error unregistering vsync callback: %s (%d)",
479 strerror(-err), err);
480 }
481
482 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000483 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700484 static_cast<DispSync::Callback*>(this));
485 if (err != NO_ERROR) {
486 ALOGE("error registering vsync callback: %s (%d)",
487 strerror(-err), err);
488 }
489 }
490
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491private:
492 virtual void onDispSyncEvent(nsecs_t when) {
493 sp<VSyncSource::Callback> callback;
494 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700495 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 callback = mCallback;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 if (mTraceVsync) {
499 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700500 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 }
503
504 if (callback != NULL) {
505 callback->onVSyncEvent(when);
506 }
507 }
508
Tim Murray4a4e4a22016-04-19 16:29:23 +0000509 const char* const mName;
510
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 int mValue;
512
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700514 const String8 mVsyncOnLabel;
515 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700516
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700518
519 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700521
522 Mutex mVsyncMutex; // Protects the following
523 nsecs_t mPhaseOffset;
524 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525};
526
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700527class InjectVSyncSource : public VSyncSource {
528public:
529 InjectVSyncSource() {}
530
531 virtual ~InjectVSyncSource() {}
532
533 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
534 std::lock_guard<std::mutex> lock(mCallbackMutex);
535 mCallback = callback;
536 }
537
538 virtual void onInjectSyncEvent(nsecs_t when) {
539 std::lock_guard<std::mutex> lock(mCallbackMutex);
540 mCallback->onVSyncEvent(when);
541 }
542
543 virtual void setVSyncEnabled(bool) {}
544 virtual void setPhaseOffset(nsecs_t) {}
545
546private:
547 std::mutex mCallbackMutex; // Protects the following
548 sp<VSyncSource::Callback> mCallback;
549};
550
Wei Wangf9b05ee2017-07-19 20:59:39 -0700551// Do not call property_set on main thread which will be blocked by init
552// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700554 ALOGI( "SurfaceFlinger's main thread ready to run. "
555 "Initializing graphics H/W...");
556
Romain Guyc53d3552017-07-20 18:49:46 -0700557 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900558
Dan Stoza9e56aa02015-11-02 13:00:03 -0800559 { // Autolock scope
560 Mutex::Autolock _l(mStateLock);
561
562 // initialize EGL for the default display
563 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
564 eglInitialize(mEGLDisplay, NULL, NULL);
565
566 // start the EventThread
567 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
568 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700569 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
571 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700572 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 mEventQueue.setEventThread(mSFEventThread);
574
Tim Murray22752852017-05-04 13:38:49 -0700575 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700576 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700577 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700578 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
579 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
580 }
Tim Murray22752852017-05-04 13:38:49 -0700581 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
582 ALOGE("Couldn't set SCHED_FIFO for EventThread");
583 }
Tim Murray41a38532016-06-22 12:42:10 -0700584
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585 // Get a RenderEngine for the given display / config (can't fail)
586 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700587 HAL_PIXEL_FORMAT_RGBA_8888,
588 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 }
590
591 // Drop the state lock while we initialize the hardware composer. We drop
592 // the lock because on creation, it will call back into SurfaceFlinger to
593 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800594 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
595 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800596 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800597 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
599
Jesse Hall692c7232012-11-08 15:41:56 -0800600 Mutex::Autolock _l(mStateLock);
601
Steven Thomas050b2c82017-03-06 11:45:16 -0800602 if (useVrFlinger) {
603 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700604 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800605 mVrFlingerRequestsDisplay = requestDisplay;
606 signalTransaction();
607 };
608 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
609 vrFlingerRequestDisplayCallback);
610 if (!mVrFlinger) {
611 ALOGE("Failed to start vrflinger");
612 }
613 }
614
Mathias Agopian875d8e12013-06-07 15:35:48 -0700615 // retrieve the EGL context that was selected/created
616 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700617
Mathias Agopianda27af92012-09-13 18:17:13 -0700618 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
619 "couldn't create EGLContext");
620
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621 // make the GLContext current so that we can create textures when creating
622 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700623 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700624
Jamie Gennisd1700752013-10-14 12:22:52 -0700625 mEventControlThread = new EventControlThread(this);
626 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
627
Mathias Agopian92a979a2012-08-02 18:32:23 -0700628 // initialize our drawing state
629 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700630
Andy McFadden13a082e2012-08-24 10:16:42 -0700631 // set initial conditions (e.g. unblank default device)
632 initializeDisplays();
633
Dan Stoza4e637772016-07-28 13:31:51 -0700634 mRenderEngine->primeCache();
635
Wei Wangf9b05ee2017-07-19 20:59:39 -0700636 // Inform native graphics APIs whether the present timestamp is supported:
637 if (getHwComposer().hasCapability(
638 HWC2::Capability::PresentFenceIsNotReliable)) {
639 mStartPropertySetThread = new StartPropertySetThread(false);
640 } else {
641 mStartPropertySetThread = new StartPropertySetThread(true);
642 }
643
644 if (mStartPropertySetThread->Start() != NO_ERROR) {
645 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800646 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800647
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700649}
650
Romain Guy11d63f42017-07-20 12:47:14 -0700651void SurfaceFlinger::readPersistentProperties() {
652 char value[PROPERTY_VALUE_MAX];
653
654 property_get("persist.sys.sf.color_saturation", value, "1.0");
655 mSaturation = atof(value);
656 ALOGV("Saturation is set to %.2f", mSaturation);
657}
658
Mathias Agopiana67e4182012-06-19 17:26:12 -0700659void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800660 // Start boot animation service by setting a property mailbox
661 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700662 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800663 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 if (mStartPropertySetThread->join() != NO_ERROR) {
665 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800666 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700667}
668
Mathias Agopian875d8e12013-06-07 15:35:48 -0700669size_t SurfaceFlinger::getMaxTextureSize() const {
670 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700671}
672
Mathias Agopian875d8e12013-06-07 15:35:48 -0700673size_t SurfaceFlinger::getMaxViewportDims() const {
674 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700675}
676
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800677// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800678
Jamie Gennis582270d2011-08-17 18:19:00 -0700679bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800680 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800681 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800682 return authenticateSurfaceTextureLocked(bufferProducer);
683}
684
685bool SurfaceFlinger::authenticateSurfaceTextureLocked(
686 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800687 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700688 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800689}
690
Brian Anderson6b376712017-04-04 10:51:39 -0700691status_t SurfaceFlinger::getSupportedFrameTimestamps(
692 std::vector<FrameEvent>* outSupported) const {
693 *outSupported = {
694 FrameEvent::REQUESTED_PRESENT,
695 FrameEvent::ACQUIRE,
696 FrameEvent::LATCH,
697 FrameEvent::FIRST_REFRESH_START,
698 FrameEvent::LAST_REFRESH_START,
699 FrameEvent::GPU_COMPOSITION_DONE,
700 FrameEvent::DEQUEUE_READY,
701 FrameEvent::RELEASE,
702 };
703 if (!getHwComposer().hasCapability(
704 HWC2::Capability::PresentFenceIsNotReliable)) {
705 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
706 }
707 return NO_ERROR;
708}
709
Dan Stoza7f7da322014-05-02 15:26:25 -0700710status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
711 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700712 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700713 return BAD_VALUE;
714 }
715
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500716 if (!display.get())
717 return NAME_NOT_FOUND;
718
Jesse Hall692c7232012-11-08 15:41:56 -0800719 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700720 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800721 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700722 type = i;
723 break;
724 }
725 }
726
727 if (type < 0) {
728 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700729 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700730
Mathias Agopian8b736f12012-08-13 17:54:26 -0700731 // TODO: Not sure if display density should handled by SF any longer
732 class Density {
733 static int getDensityFromProperty(char const* propName) {
734 char property[PROPERTY_VALUE_MAX];
735 int density = 0;
736 if (property_get(propName, property, NULL) > 0) {
737 density = atoi(property);
738 }
739 return density;
740 }
741 public:
742 static int getEmuDensity() {
743 return getDensityFromProperty("qemu.sf.lcd_density"); }
744 static int getBuildDensity() {
745 return getDensityFromProperty("ro.sf.lcd_density"); }
746 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700747
Dan Stoza7f7da322014-05-02 15:26:25 -0700748 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700749
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 DisplayInfo info = DisplayInfo();
752
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 float xdpi = hwConfig->getDpiX();
754 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700755
756 if (type == DisplayDevice::DISPLAY_PRIMARY) {
757 // The density of the device is provided by a build property
758 float density = Density::getBuildDensity() / 160.0f;
759 if (density == 0) {
760 // the build doesn't provide a density -- this is wrong!
761 // use xdpi instead
762 ALOGE("ro.sf.lcd_density must be defined as a build property");
763 density = xdpi / 160.0f;
764 }
765 if (Density::getEmuDensity()) {
766 // if "qemu.sf.lcd_density" is specified, it overrides everything
767 xdpi = ydpi = density = Density::getEmuDensity();
768 density /= 160.0f;
769 }
770 info.density = density;
771
772 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000773 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
774 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 } else {
776 // TODO: where should this value come from?
777 static const int TV_DENSITY = 213;
778 info.density = TV_DENSITY / 160.0f;
779 info.orientation = 0;
780 }
781
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 info.w = hwConfig->getWidth();
783 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700784 info.xdpi = xdpi;
785 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800786 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900787 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800788
Andy McFadden91b2ca82014-06-13 14:04:23 -0700789 // This is how far in advance a buffer must be queued for
790 // presentation at a given time. If you want a buffer to appear
791 // on the screen at time N, you must submit the buffer before
792 // (N - presentationDeadline).
793 //
794 // Normally it's one full refresh period (to give SF a chance to
795 // latch the buffer), but this can be reduced by configuring a
796 // DispSync offset. Any additional delays introduced by the hardware
797 // composer or panel must be accounted for here.
798 //
799 // We add an additional 1ms to allow for processing time and
800 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800802 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700803
804 // All non-virtual displays are currently considered secure.
805 info.secure = true;
806
Michael Wright28f24d02016-07-12 13:30:53 -0700807 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 }
809
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return NO_ERROR;
811}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700812
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800813status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700814 DisplayStatInfo* stats) {
815 if (stats == NULL) {
816 return BAD_VALUE;
817 }
818
819 // FIXME for now we always return stats for the primary display
820 memset(stats, 0, sizeof(*stats));
821 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
822 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
823 return NO_ERROR;
824}
825
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700826int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800827 if (display == NULL) {
828 ALOGE("%s : display is NULL", __func__);
829 return BAD_VALUE;
830 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700831
832 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700833 if (device != NULL) {
834 return device->getActiveConfig();
835 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700836
Dan Stoza24a42e92015-03-09 10:04:11 -0700837 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700838}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700839
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700840void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
841 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
842 this);
843 int32_t type = hw->getDisplayType();
844 int currentMode = hw->getActiveConfig();
845
846 if (mode == currentMode) {
847 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
848 return;
849 }
850
851 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
852 ALOGW("Trying to set config for virtual display");
853 return;
854 }
855
856 hw->setActiveConfig(mode);
857 getHwComposer().setActiveConfig(type, mode);
858}
859
860status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
861 class MessageSetActiveConfig: public MessageBase {
862 SurfaceFlinger& mFlinger;
863 sp<IBinder> mDisplay;
864 int mMode;
865 public:
866 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
867 int mode) :
868 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
869 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700870 Vector<DisplayInfo> configs;
871 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700872 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700873 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700874 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700875 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700876 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700877 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
878 if (hw == NULL) {
879 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700880 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700881 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
882 ALOGW("Attempt to set active config = %d for virtual display",
883 mMode);
884 } else {
885 mFlinger.setActiveConfigInternal(hw, mMode);
886 }
887 return true;
888 }
889 };
890 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
891 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700892 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700893}
Michael Wright28f24d02016-07-12 13:30:53 -0700894status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
895 Vector<android_color_mode_t>* outColorModes) {
896 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
897 return BAD_VALUE;
898 }
899
900 if (!display.get()) {
901 return NAME_NOT_FOUND;
902 }
903
904 int32_t type = NAME_NOT_FOUND;
905 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
906 if (display == mBuiltinDisplays[i]) {
907 type = i;
908 break;
909 }
910 }
911
912 if (type < 0) {
913 return type;
914 }
915
916 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
917 outColorModes->clear();
918 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
919
920 return NO_ERROR;
921}
922
923android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700924 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700925 if (device != nullptr) {
926 return device->getActiveColorMode();
927 }
928 return static_cast<android_color_mode_t>(BAD_VALUE);
929}
930
931void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
932 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700933 int32_t type = hw->getDisplayType();
934 android_color_mode_t currentMode = hw->getActiveColorMode();
935
936 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700937 return;
938 }
939
940 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
941 ALOGW("Trying to set config for virtual display");
942 return;
943 }
944
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600945 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
946 hw->getDisplayType());
947
Michael Wright28f24d02016-07-12 13:30:53 -0700948 hw->setActiveColorMode(mode);
949 getHwComposer().setActiveColorMode(type, mode);
950}
951
952
953status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
954 android_color_mode_t colorMode) {
955 class MessageSetActiveColorMode: public MessageBase {
956 SurfaceFlinger& mFlinger;
957 sp<IBinder> mDisplay;
958 android_color_mode_t mMode;
959 public:
960 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
961 android_color_mode_t mode) :
962 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
963 virtual bool handler() {
964 Vector<android_color_mode_t> modes;
965 mFlinger.getDisplayColorModes(mDisplay, &modes);
966 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
967 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600968 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
969 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700970 return true;
971 }
972 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
973 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600974 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
975 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700976 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600977 ALOGW("Attempt to set active color mode %s %d for virtual display",
978 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700979 } else {
980 mFlinger.setActiveColorModeInternal(hw, mMode);
981 }
982 return true;
983 }
984 };
985 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
986 postMessageSync(msg);
987 return NO_ERROR;
988}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700989
Svetoslavd85084b2014-03-20 10:28:31 -0700990status_t SurfaceFlinger::clearAnimationFrameStats() {
991 Mutex::Autolock _l(mStateLock);
992 mAnimFrameTracker.clearStats();
993 return NO_ERROR;
994}
995
996status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
997 Mutex::Autolock _l(mStateLock);
998 mAnimFrameTracker.getStats(outStats);
999 return NO_ERROR;
1000}
1001
Dan Stozac4f471e2016-03-24 09:31:08 -07001002status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1003 HdrCapabilities* outCapabilities) const {
1004 Mutex::Autolock _l(mStateLock);
1005
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001006 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001007 if (displayDevice == nullptr) {
1008 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1009 return BAD_VALUE;
1010 }
1011
1012 std::unique_ptr<HdrCapabilities> capabilities =
1013 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1014 if (capabilities) {
1015 std::swap(*outCapabilities, *capabilities);
1016 } else {
1017 return BAD_VALUE;
1018 }
1019
1020 return NO_ERROR;
1021}
1022
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001023status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1024 if (enable == mInjectVSyncs) {
1025 return NO_ERROR;
1026 }
1027
1028 if (enable) {
1029 mInjectVSyncs = enable;
1030 ALOGV("VSync Injections enabled");
1031 if (mVSyncInjector.get() == nullptr) {
1032 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001033 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001034 }
1035 mEventQueue.setEventThread(mInjectorEventThread);
1036 } else {
1037 mInjectVSyncs = enable;
1038 ALOGV("VSync Injections disabled");
1039 mEventQueue.setEventThread(mSFEventThread);
1040 mVSyncInjector.clear();
1041 }
1042 return NO_ERROR;
1043}
1044
1045status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1046 if (!mInjectVSyncs) {
1047 ALOGE("VSync Injections not enabled");
1048 return BAD_VALUE;
1049 }
1050 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1051 ALOGV("Injecting VSync inside SurfaceFlinger");
1052 mVSyncInjector->onInjectSyncEvent(when);
1053 }
1054 return NO_ERROR;
1055}
1056
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001057// ----------------------------------------------------------------------------
1058
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001059sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1060 ISurfaceComposer::VsyncSource vsyncSource) {
1061 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1062 return mSFEventThread->createEventConnection();
1063 } else {
1064 return mEventThread->createEventConnection();
1065 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001066}
1067
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001069
1070void SurfaceFlinger::waitForEvent() {
1071 mEventQueue.waitMessage();
1072}
1073
1074void SurfaceFlinger::signalTransaction() {
1075 mEventQueue.invalidate();
1076}
1077
1078void SurfaceFlinger::signalLayerUpdate() {
1079 mEventQueue.invalidate();
1080}
1081
1082void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001083 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001084 mEventQueue.refresh();
1085}
1086
1087status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001088 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001089 return mEventQueue.postMessage(msg, reltime);
1090}
1091
1092status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001093 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001094 status_t res = mEventQueue.postMessage(msg, reltime);
1095 if (res == NO_ERROR) {
1096 msg->wait();
1097 }
1098 return res;
1099}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001100
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001101void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001102 do {
1103 waitForEvent();
1104 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001105}
1106
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001107void SurfaceFlinger::enableHardwareVsync() {
1108 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001109 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001110 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;
Andy McFadden43601a22012-09-11 15:15:13 -07001114 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115}
1116
Jesse Hall948fe0c2013-10-14 12:56:09 -07001117void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001118 Mutex::Autolock _l(mHWVsyncLock);
1119
Jesse Hall948fe0c2013-10-14 12:56:09 -07001120 if (makeAvailable) {
1121 mHWVsyncAvailable = true;
1122 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001123 // Hardware vsync is not currently available, so abort the resync
1124 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001125 return;
1126 }
1127
Dan Stoza9e56aa02015-11-02 13:00:03 -08001128 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1129 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001130
1131 mPrimaryDispSync.reset();
1132 mPrimaryDispSync.setPeriod(period);
1133
1134 if (!mPrimaryHWVsyncEnabled) {
1135 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001136 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1137 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001138 mPrimaryHWVsyncEnabled = true;
1139 }
1140}
1141
Jesse Hall948fe0c2013-10-14 12:56:09 -07001142void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001143 Mutex::Autolock _l(mHWVsyncLock);
1144 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001145 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1146 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001147 mPrimaryDispSync.endResync();
1148 mPrimaryHWVsyncEnabled = false;
1149 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001150 if (makeUnavailable) {
1151 mHWVsyncAvailable = false;
1152 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001153}
1154
Tim Murray4a4e4a22016-04-19 16:29:23 +00001155void SurfaceFlinger::resyncWithRateLimit() {
1156 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001157
1158 // No explicit locking is needed here since EventThread holds a lock while calling this method
1159 static nsecs_t sLastResyncAttempted = 0;
1160 const nsecs_t now = systemTime();
1161 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001162 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001163 }
Dan Stoza57164302017-05-08 14:03:54 -07001164 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001165}
1166
Steven Thomas3cfac282017-02-06 12:29:30 -08001167void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1168 nsecs_t timestamp) {
1169 Mutex::Autolock lock(mStateLock);
1170 // Ignore any vsyncs from the non-active hardware composer.
1171 if (composer != mHwc) {
1172 return;
1173 }
1174
Jamie Gennisd1700752013-10-14 12:22:52 -07001175 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176
Jamie Gennisd1700752013-10-14 12:22:52 -07001177 { // Scope for the lock
1178 Mutex::Autolock _l(mHWVsyncLock);
1179 if (type == 0 && mPrimaryHWVsyncEnabled) {
1180 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001182 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001183
1184 if (needsHwVsync) {
1185 enableHardwareVsync();
1186 } else {
1187 disableHardwareVsync(false);
1188 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001189}
1190
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001191void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001192 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001193 *compositorTiming = mCompositorTiming;
1194}
1195
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001196void SurfaceFlinger::createDefaultDisplayDevice() {
1197 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1198 wp<IBinder> token = mBuiltinDisplays[type];
1199
1200 // All non-virtual displays are currently considered secure.
1201 const bool isSecure = true;
1202
1203 sp<IGraphicBufferProducer> producer;
1204 sp<IGraphicBufferConsumer> consumer;
1205 BufferQueue::createBufferQueue(&producer, &consumer);
1206
1207 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1208
1209 bool hasWideColorModes = false;
1210 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1211 for (android_color_mode_t colorMode : modes) {
1212 switch (colorMode) {
1213 case HAL_COLOR_MODE_DISPLAY_P3:
1214 case HAL_COLOR_MODE_ADOBE_RGB:
1215 case HAL_COLOR_MODE_DCI_P3:
1216 hasWideColorModes = true;
1217 break;
1218 default:
1219 break;
1220 }
1221 }
1222 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1223 token, fbs, producer, mRenderEngine->getEGLConfig(),
1224 hasWideColorModes && hasWideColorDisplay);
1225 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001226 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001227}
1228
1229void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001230 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001231
1232 if (composer->isUsingVrComposer()) {
1233 // We handle initializing the primary display device for the VR
1234 // window manager hwc explicitly at the time of transition.
1235 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1236 ALOGE("External displays are not supported by the vr hardware composer.");
1237 }
1238 return;
1239 }
1240
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1242 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001243 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1244 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001245 } else {
1246 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001247 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001248 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001250 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001251 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1252 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001253 }
1254 setTransactionFlags(eDisplayTransactionNeeded);
1255
Andy McFadden9e9689c2012-10-10 18:17:51 -07001256 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001257 }
Mathias Agopian86303202012-07-24 22:46:10 -07001258}
1259
Steven Thomas3cfac282017-02-06 12:29:30 -08001260void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1261 Mutex::Autolock lock(mStateLock);
1262 if (composer == mHwc) {
1263 repaintEverything();
1264 } else {
1265 // This isn't from our current hardware composer. If it's a callback
1266 // from the real composer, forward the refresh request to vr
1267 // flinger. Otherwise ignore it.
1268 if (!composer->isUsingVrComposer()) {
1269 mVrFlinger->OnHardwareComposerRefresh();
1270 }
1271 }
1272}
1273
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001276 getHwComposer().setVsyncEnabled(disp,
1277 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001278}
1279
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001280// Note: it is assumed the caller holds |mStateLock| when this is called
1281void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001282 disableHardwareVsync(true);
1283 clearHwcLayers(mDrawingState.layersSortedByZ);
1284 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001285 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1286 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1287 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001288 // Clear the drawing state so that the logic inside of
1289 // handleTransactionLocked will fire. It will determine the delta between
1290 // mCurrentState and mDrawingState and re-apply all changes when we make the
1291 // transition.
1292 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001293 // Release virtual display hwcId during vr mode transition.
1294 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1295 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1296 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1297 displayDevice->disconnect(getHwComposer());
1298 }
1299 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001300 mDisplays.clear();
1301}
1302
Steven Thomas050b2c82017-03-06 11:45:16 -08001303void SurfaceFlinger::updateVrFlinger() {
1304 if (!mVrFlinger)
1305 return;
1306 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1307 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001308 return;
1309 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310
Steven Thomas050b2c82017-03-06 11:45:16 -08001311 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001312 // Construct new HWComposer without holding any locks.
1313 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001314
1315 // Set up the event handlers. This step is neccessary to initialize the internal state of
1316 // the hardware composer object properly. Our callbacks are designed such that if they are
1317 // triggered between now and the point where the display is properly re-initialized, they
1318 // will not have any effect, so this is safe to do here, before the lock is aquired.
1319 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001320 ALOGV("Vr HWC created");
1321 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325 if (vrFlingerRequestsDisplay) {
1326 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328 mHwc = mVrHwc;
1329 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001330
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331 } else {
1332 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 resetHwcLocked();
1335
1336 mHwc = mRealHwc;
1337 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001338 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339
1340 mVisibleRegionsDirty = true;
1341 invalidateHwcGeometry();
1342
1343 // Explicitly re-initialize the primary display. This is because some other
1344 // parts of this class rely on the primary display always being available.
1345 createDefaultDisplayDevice();
1346
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001347 // Re-enable default display.
1348 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1349 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1350 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1351
1352 // Reset the timing values to account for the period of the swapped in HWC
1353 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1354 const nsecs_t period = activeConfig->getVsyncPeriod();
1355 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1356
1357 // Use phase of 0 since phase is not known.
1358 // Use latency of 0, which will snap to the ideal latency.
1359 setCompositorTimingSnapped(0, period, 0);
1360 });
1361 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001362
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001363 android_atomic_or(1, &mRepaintEverything);
1364 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365}
1366
Mathias Agopian4fec8732012-06-29 14:12:52 -07001367void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001368 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001369 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001370 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001371 bool frameMissed = !mHadClientComposition &&
1372 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001373 (mPreviousPresentFence->getSignalTime() ==
1374 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001375 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001376 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001377 signalLayerUpdate();
1378 break;
1379 }
1380
Steven Thomas050b2c82017-03-06 11:45:16 -08001381 // Now that we're going to make it to the handleMessageTransaction()
1382 // call below it's safe to call updateVrFlinger(), which will
1383 // potentially trigger a display handoff.
1384 updateVrFlinger();
1385
Dan Stoza6b9454d2014-11-07 16:00:59 -08001386 bool refreshNeeded = handleMessageTransaction();
1387 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001388 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001389 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001390 // Signal a refresh if a transaction modified the window state,
1391 // a new buffer was latched, or if HWC has requested a full
1392 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001393 signalRefresh();
1394 }
1395 break;
1396 }
1397 case MessageQueue::REFRESH: {
1398 handleMessageRefresh();
1399 break;
1400 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001401 }
1402}
1403
Dan Stoza6b9454d2014-11-07 16:00:59 -08001404bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001405 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001406 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001407 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001409 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001410 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001411}
1412
Dan Stoza6b9454d2014-11-07 16:00:59 -08001413bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001414 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001416}
1417
1418void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001420
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001421 mRefreshPending = false;
1422
Pablo Ceballos40845df2016-01-25 17:41:15 -08001423 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001424
Brian Andersond6927fb2016-07-23 23:37:30 -07001425 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001426 rebuildLayerStacks();
1427 setUpHWComposer();
1428 doDebugFlashRegions();
1429 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001431
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001432 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001433
1434 mHadClientComposition = false;
1435 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1436 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1437 mHadClientComposition = mHadClientComposition ||
1438 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1439 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001440
Dan Stoza9e56aa02015-11-02 13:00:03 -08001441 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001443
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444void SurfaceFlinger::doDebugFlashRegions()
1445{
1446 // is debugging enabled
1447 if (CC_LIKELY(!mDebugRegion))
1448 return;
1449
1450 const bool repaintEverything = mRepaintEverything;
1451 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1452 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001453 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001454 // transform the dirty region into this screen's coordinate space
1455 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1456 if (!dirtyRegion.isEmpty()) {
1457 // redraw the whole screen
1458 doComposeSurfaces(hw, Region(hw->bounds()));
1459
1460 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001461 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001462 RenderEngine& engine(getRenderEngine());
1463 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1464
Mathias Agopianda27af92012-09-13 18:17:13 -07001465 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466 }
1467 }
1468 }
1469
1470 postFramebuffer();
1471
1472 if (mDebugRegion > 1) {
1473 usleep(mDebugRegion * 1000);
1474 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001475
Dan Stoza9e56aa02015-11-02 13:00:03 -08001476 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001477 auto& displayDevice = mDisplays[displayId];
1478 if (!displayDevice->isDisplayOn()) {
1479 continue;
1480 }
1481
1482 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001483 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1484 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001485 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001486}
1487
Brian Andersond6927fb2016-07-23 23:37:30 -07001488void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001489{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001490 ATRACE_CALL();
1491 ALOGV("preComposition");
1492
Mathias Agopiancd60f992012-08-16 16:28:27 -07001493 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001494 mDrawingState.traverseInZOrder([&](Layer* layer) {
1495 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001496 needExtraInvalidate = true;
1497 }
Robert Carr2047fae2016-11-28 14:09:09 -08001498 });
1499
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500 if (needExtraInvalidate) {
1501 signalLayerUpdate();
1502 }
1503}
1504
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505void SurfaceFlinger::updateCompositorTiming(
1506 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1507 std::shared_ptr<FenceTime>& presentFenceTime) {
1508 // Update queue of past composite+present times and determine the
1509 // most recently known composite to present latency.
1510 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1511 nsecs_t compositeToPresentLatency = -1;
1512 while (!mCompositePresentTimes.empty()) {
1513 CompositePresentTime& cpt = mCompositePresentTimes.front();
1514 // Cached values should have been updated before calling this method,
1515 // which helps avoid duplicate syscalls.
1516 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1517 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1518 break;
1519 }
1520 compositeToPresentLatency = displayTime - cpt.composite;
1521 mCompositePresentTimes.pop();
1522 }
1523
1524 // Don't let mCompositePresentTimes grow unbounded, just in case.
1525 while (mCompositePresentTimes.size() > 16) {
1526 mCompositePresentTimes.pop();
1527 }
1528
Brian Andersond0010582017-03-07 13:20:31 -08001529 setCompositorTimingSnapped(
1530 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1531}
1532
1533void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1534 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535 // Integer division and modulo round toward 0 not -inf, so we need to
1536 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001537 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1539 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1540
Brian Andersond0010582017-03-07 13:20:31 -08001541 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1542 if (idealLatency <= 0) {
1543 idealLatency = vsyncInterval;
1544 }
1545
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 // Snap the latency to a value that removes scheduling jitter from the
1547 // composition and present times, which often have >1ms of jitter.
1548 // Reducing jitter is important if an app attempts to extrapolate
1549 // something (such as user input) to an accurate diasplay time.
1550 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1551 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001552 nsecs_t bias = vsyncInterval / 2;
1553 int64_t extraVsyncs =
1554 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1555 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1556 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557
Brian Andersond0010582017-03-07 13:20:31 -08001558 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1560 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001561 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562}
1563
1564void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001566 ATRACE_CALL();
1567 ALOGV("postComposition");
1568
Brian Anderson3546a3f2016-07-14 11:51:14 -07001569 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001570 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001571 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001572 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001573 }
1574
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001575 // |mStateLock| not needed as we are on the main thread
1576 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001577
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001578 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001579 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1580 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1581 glCompositionDoneFenceTime =
1582 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1583 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1584 } else {
1585 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1586 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001587
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001588 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001589 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1590 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1591 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001592
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1594 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1595
1596 // We use the refreshStartTime which might be sampled a little later than
1597 // when we started doing work for this frame, but that should be okay
1598 // since updateCompositorTiming has snapping logic.
1599 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001600 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001601 CompositorTiming compositorTiming;
1602 {
1603 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1604 compositorTiming = mCompositorTiming;
1605 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606
Robert Carr2047fae2016-11-28 14:09:09 -08001607 mDrawingState.traverseInZOrder([&](Layer* layer) {
1608 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001609 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001610 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001611 recordBufferingStats(layer->getName().string(),
1612 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001613 }
Robert Carr2047fae2016-11-28 14:09:09 -08001614 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001615
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001616 if (presentFenceTime->isValid()) {
1617 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001618 enableHardwareVsync();
1619 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001620 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001621 }
1622 }
1623
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001624 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001625 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001626 enableHardwareVsync();
1627 }
1628 }
1629
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001630 if (mAnimCompositionPending) {
1631 mAnimCompositionPending = false;
1632
Brian Anderson4e606e32017-03-16 15:34:57 -07001633 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001634 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001635 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001636 } else {
1637 // The HWC doesn't support present fences, so use the refresh
1638 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001639 nsecs_t presentTime =
1640 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001641 mAnimFrameTracker.setActualPresentTime(presentTime);
1642 }
1643 mAnimFrameTracker.advanceFrame();
1644 }
Dan Stozab90cf072015-03-05 11:05:59 -08001645
1646 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1647 return;
1648 }
1649
1650 nsecs_t currentTime = systemTime();
1651 if (mHasPoweredOff) {
1652 mHasPoweredOff = false;
1653 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001654 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001656 if (numPeriods < NUM_BUCKETS - 1) {
1657 mFrameBuckets[numPeriods] += elapsedTime;
1658 } else {
1659 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1660 }
1661 mTotalTime += elapsedTime;
1662 }
1663 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664}
1665
1666void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001667 ATRACE_CALL();
1668 ALOGV("rebuildLayerStacks");
1669
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001671 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1672 ATRACE_CALL();
1673 mVisibleRegionsDirty = false;
1674 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001675
Jeff Sharkey76488112017-02-27 14:15:18 -07001676 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1677 Region opaqueRegion;
1678 Region dirtyRegion;
1679 Vector<sp<Layer>> layersSortedByZ;
1680 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1681 const Transform& tr(displayDevice->getTransform());
1682 const Rect bounds(displayDevice->getBounds());
1683 if (displayDevice->isDisplayOn()) {
1684 computeVisibleRegions(
1685 displayDevice->getLayerStack(), dirtyRegion,
1686 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001687
Jeff Sharkey76488112017-02-27 14:15:18 -07001688 mDrawingState.traverseInZOrder([&](Layer* layer) {
1689 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1690 Region drawRegion(tr.transform(
1691 layer->visibleNonTransparentRegion));
1692 drawRegion.andSelf(bounds);
1693 if (!drawRegion.isEmpty()) {
1694 layersSortedByZ.add(layer);
1695 } else {
1696 // Clear out the HWC layer if this layer was
1697 // previously visible, but no longer is
1698 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1699 nullptr);
1700 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001701 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001702 // WM changes displayDevice->layerStack upon sleep/awake.
1703 // Here we make sure we delete the HWC layers even if
1704 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001705 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1706 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001707 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001708 });
1709 }
1710 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1711 displayDevice->undefinedRegion.set(bounds);
1712 displayDevice->undefinedRegion.subtractSelf(
1713 tr.transform(opaqueRegion));
1714 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001715 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001716 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001718
Romain Guy0147a172017-06-01 13:53:56 -07001719mat4 SurfaceFlinger::computeSaturationMatrix() const {
1720 if (mSaturation == 1.0f) {
1721 return mat4();
1722 }
1723
1724 // Rec.709 luma coefficients
1725 float3 luminance{0.213f, 0.715f, 0.072f};
1726 luminance *= 1.0f - mSaturation;
1727 return mat4(
1728 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1729 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1730 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1731 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1732 );
1733}
1734
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001735// pickColorMode translates a given dataspace into the best available color mode.
1736// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001737android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001738 switch (dataSpace) {
1739 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1740 // system expects.
1741 case HAL_DATASPACE_UNKNOWN:
1742 case HAL_DATASPACE_SRGB:
1743 case HAL_DATASPACE_V0_SRGB:
1744 return HAL_COLOR_MODE_SRGB;
1745 break;
1746
1747 case HAL_DATASPACE_DISPLAY_P3:
1748 return HAL_COLOR_MODE_DISPLAY_P3;
1749 break;
1750
1751 default:
1752 // TODO (courtneygo): Do we want to assert an error here?
1753 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1754 dataSpace);
1755 return HAL_COLOR_MODE_SRGB;
1756 break;
1757 }
1758}
1759
Romain Guy0147a172017-06-01 13:53:56 -07001760android_dataspace SurfaceFlinger::bestTargetDataSpace(
1761 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001762 // Only support sRGB and Display-P3 right now.
1763 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1764 return HAL_DATASPACE_DISPLAY_P3;
1765 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001766 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1767 return HAL_DATASPACE_DISPLAY_P3;
1768 }
1769 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1770 return HAL_DATASPACE_DISPLAY_P3;
1771 }
1772
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001773 return HAL_DATASPACE_V0_SRGB;
1774}
1775
Mathias Agopiancd60f992012-08-16 16:28:27 -07001776void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001777 ATRACE_CALL();
1778 ALOGV("setUpHWComposer");
1779
Jesse Hall028dc8f2013-08-20 16:35:32 -07001780 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001781 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1782 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1783 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1784
1785 // If nothing has changed (!dirty), don't recompose.
1786 // If something changed, but we don't currently have any visible layers,
1787 // and didn't when we last did a composition, then skip it this time.
1788 // The second rule does two things:
1789 // - When all layers are removed from a display, we'll emit one black
1790 // frame, then nothing more until we get new layers.
1791 // - When a display is created with a private layer stack, we won't
1792 // emit any black frames until a layer is added to the layer stack.
1793 bool mustRecompose = dirty && !(empty && wasEmpty);
1794
1795 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1796 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1797 mustRecompose ? "doing" : "skipping",
1798 dirty ? "+" : "-",
1799 empty ? "+" : "-",
1800 wasEmpty ? "+" : "-");
1801
Dan Stoza71433162014-02-04 16:22:36 -08001802 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001803
1804 if (mustRecompose) {
1805 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1806 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001807 }
1808
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 // build the h/w work list
1810 if (CC_UNLIKELY(mGeometryInvalid)) {
1811 mGeometryInvalid = false;
1812 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1813 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1814 const auto hwcId = displayDevice->getHwcDisplayId();
1815 if (hwcId >= 0) {
1816 const Vector<sp<Layer>>& currentLayers(
1817 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001818 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001819 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001820 if (!layer->hasHwcLayer(hwcId)) {
1821 auto hwcLayer = mHwc->createLayer(hwcId);
1822 if (hwcLayer) {
1823 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1824 } else {
1825 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001827 }
1828 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001829
Robert Carrae060832016-11-28 10:51:00 -08001830 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001831 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001833 }
1834 }
1835 }
1836 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001837 }
Riley Andrews03414a12014-07-01 14:22:59 -07001838
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001839
Romain Guy0147a172017-06-01 13:53:56 -07001840 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001841
Dan Stoza9e56aa02015-11-02 13:00:03 -08001842 // Set the per-frame data
1843 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1844 auto& displayDevice = mDisplays[displayId];
1845 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001846
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 if (hwcId < 0) {
1848 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001849 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001850 if (colorMatrix != mPreviousColorMatrix) {
1851 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1852 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1853 "display %zd: %d", displayId, result);
1854 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1856 layer->setPerFrameData(displayDevice);
1857 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001858
1859 if (hasWideColorDisplay) {
1860 android_color_mode newColorMode;
1861 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1862
1863 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1864 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1865 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1866 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1867 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1868 }
1869 newColorMode = pickColorMode(newDataSpace);
1870
Romain Guyc53d3552017-07-20 18:49:46 -07001871 // We want the color mode of the boot animation to match that of the bootloader
1872 // To achieve this we suppress color mode changes until after the boot animation
1873 if (mBootFinished) {
1874 setActiveColorModeInternal(displayDevice, newColorMode);
1875 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001876 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 }
1878
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001879 mPreviousColorMatrix = colorMatrix;
1880
Dan Stoza9e56aa02015-11-02 13:00:03 -08001881 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001882 auto& displayDevice = mDisplays[displayId];
1883 if (!displayDevice->isDisplayOn()) {
1884 continue;
1885 }
1886
1887 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1889 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001890 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001892
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893void SurfaceFlinger::doComposition() {
1894 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 ALOGV("doComposition");
1896
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001897 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001898 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001899 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001900 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901 // transform the dirty region into this screen's coordinate space
1902 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001903
1904 // repaint the framebuffer (if needed)
1905 doDisplayComposition(hw, dirtyRegion);
1906
Mathias Agopiancd60f992012-08-16 16:28:27 -07001907 hw->dirtyRegion.clear();
1908 hw->flip(hw->swapRegion);
1909 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001910 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001911 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001912 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001913}
1914
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001915void SurfaceFlinger::postFramebuffer()
1916{
Mathias Agopian841cde52012-03-01 15:44:37 -08001917 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001919
Mathias Agopiana44b0412011-10-16 18:46:35 -07001920 const nsecs_t now = systemTime();
1921 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001922
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1924 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001925 if (!displayDevice->isDisplayOn()) {
1926 continue;
1927 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 const auto hwcId = displayDevice->getHwcDisplayId();
1929 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001930 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001931 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001932 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001933 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1935 sp<Fence> releaseFence = Fence::NO_FENCE;
1936 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1937 releaseFence = displayDevice->getClientTargetAcquireFence();
1938 } else {
1939 auto hwcLayer = layer->getHwcLayer(hwcId);
1940 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001941 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 layer->onLayerDisplayed(releaseFence);
1943 }
1944 if (hwcId >= 0) {
1945 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001946 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001947 }
1948
Mathias Agopiana44b0412011-10-16 18:46:35 -07001949 mLastSwapBufferTime = systemTime() - now;
1950 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001951
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001952 // |mStateLock| not needed as we are on the main thread
1953 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001954 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1955 logFrameStats();
1956 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001957}
1958
Mathias Agopian87baae12012-07-31 12:38:26 -07001959void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001960{
Mathias Agopian841cde52012-03-01 15:44:37 -08001961 ATRACE_CALL();
1962
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001963 // here we keep a copy of the drawing state (that is the state that's
1964 // going to be overwritten by handleTransactionLocked()) outside of
1965 // mStateLock so that the side-effects of the State assignment
1966 // don't happen with mStateLock held (which can cause deadlocks).
1967 State drawingState(mDrawingState);
1968
Mathias Agopianca4d3602011-05-19 15:38:14 -07001969 Mutex::Autolock _l(mStateLock);
1970 const nsecs_t now = systemTime();
1971 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001972
Mathias Agopianca4d3602011-05-19 15:38:14 -07001973 // Here we're guaranteed that some transaction flags are set
1974 // so we can call handleTransactionLocked() unconditionally.
1975 // We call getTransactionFlags(), which will also clear the flags,
1976 // with mStateLock held to guarantee that mCurrentState won't change
1977 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001978
Mathias Agopiane57f2922012-08-09 16:29:12 -07001979 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001980 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001981
Mathias Agopianca4d3602011-05-19 15:38:14 -07001982 mLastTransactionTime = systemTime() - now;
1983 mDebugInTransaction = 0;
1984 invalidateHwcGeometry();
1985 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001986}
1987
Mathias Agopian87baae12012-07-31 12:38:26 -07001988void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001989{
Dan Stoza7dde5992015-05-22 09:51:44 -07001990 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001991 mCurrentState.traverseInZOrder([](Layer* layer) {
1992 layer->notifyAvailableFrames();
1993 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001994
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001995 /*
1996 * Traversal of the children
1997 * (perform the transaction for each of them if needed)
1998 */
1999
Mathias Agopian3559b072012-08-15 13:46:03 -07002000 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002001 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002002 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002003 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004
2005 const uint32_t flags = layer->doTransaction(0);
2006 if (flags & Layer::eVisibleRegion)
2007 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002008 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002009 }
2010
2011 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002012 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002013 */
2014
Mathias Agopiane57f2922012-08-09 16:29:12 -07002015 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002016 // here we take advantage of Vector's copy-on-write semantics to
2017 // improve performance by skipping the transaction entirely when
2018 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002019 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2020 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002021 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002022 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002023 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002024 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002025
2026 // find the displays that were removed
2027 // (ie: in drawing state but not in current state)
2028 // also handle displays that changed
2029 // (ie: displays that are in both lists)
2030 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002031 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2032 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002033 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002034 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002035 // Call makeCurrent() on the primary display so we can
2036 // be sure that nothing associated with this display
2037 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002038 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002039 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002040 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002041 if (hw != NULL)
2042 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002043 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002044 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002045 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002046 } else {
2047 ALOGW("trying to remove the main display");
2048 }
2049 } else {
2050 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002051 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002052 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002053 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2054 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002055 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002056 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002057 // recreating the DisplayDevice, so we just remove it
2058 // from the drawing state, so that it get re-added
2059 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002060 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002061 if (hw != NULL)
2062 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002063 mDisplays.removeItem(display);
2064 mDrawingState.displays.removeItemsAt(i);
2065 dc--; i--;
2066 // at this point we must loop to the next item
2067 continue;
2068 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002069
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002070 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002071 if (disp != NULL) {
2072 if (state.layerStack != draw[i].layerStack) {
2073 disp->setLayerStack(state.layerStack);
2074 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002075 if ((state.orientation != draw[i].orientation)
2076 || (state.viewport != draw[i].viewport)
2077 || (state.frame != draw[i].frame))
2078 {
2079 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002080 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002081 }
Michael Lentine47e45402014-07-18 15:34:25 -07002082 if (state.width != draw[i].width || state.height != draw[i].height) {
2083 disp->setDisplaySize(state.width, state.height);
2084 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002085 }
2086 }
2087 }
2088
2089 // find displays that were added
2090 // (ie: in current state but not in drawing state)
2091 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002092 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002093 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002094
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002095 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002096 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002097 sp<IGraphicBufferProducer> bqProducer;
2098 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002099 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002100
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002102 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002103 // Virtual displays without a surface are dormant:
2104 // they have external state (layer stack, projection,
2105 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002106 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002107
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002108 // Allow VR composer to use virtual displays.
2109 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002110 int width = 0;
2111 int status = state.surface->query(
2112 NATIVE_WINDOW_WIDTH, &width);
2113 ALOGE_IF(status != NO_ERROR,
2114 "Unable to query width (%d)", status);
2115 int height = 0;
2116 status = state.surface->query(
2117 NATIVE_WINDOW_HEIGHT, &height);
2118 ALOGE_IF(status != NO_ERROR,
2119 "Unable to query height (%d)", status);
2120 int intFormat = 0;
2121 status = state.surface->query(
2122 NATIVE_WINDOW_FORMAT, &intFormat);
2123 ALOGE_IF(status != NO_ERROR,
2124 "Unable to query format (%d)", status);
2125 auto format = static_cast<android_pixel_format_t>(
2126 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002127
Dan Stoza8cf150a2016-08-02 10:27:31 -07002128 mHwc->allocateVirtualDisplay(width, height, &format,
2129 &hwcId);
2130 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131
Dan Stoza5cf424b2016-05-20 14:02:39 -07002132 // TODO: Plumb requested format back up to consumer
2133
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134 sp<VirtualDisplaySurface> vds =
2135 new VirtualDisplaySurface(*mHwc,
2136 hwcId, state.surface, bqProducer,
2137 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002138
2139 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002140 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002141 }
2142 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002143 ALOGE_IF(state.surface!=NULL,
2144 "adding a supported display, but rendering "
2145 "surface is provided (%p), ignoring it",
2146 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002147
2148 hwcId = state.type;
2149 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2150 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002151 }
2152
2153 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002154 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002155 sp<DisplayDevice> hw =
2156 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2157 dispSurface, producer,
2158 mRenderEngine->getEGLConfig(),
2159 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002160 hw->setLayerStack(state.layerStack);
2161 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002162 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002163 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002164 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002166 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002167 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002168 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002169 }
2170 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002171 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002172 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173
Mathias Agopian84300952012-11-21 16:02:13 -08002174 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2175 // The transform hint might have changed for some layers
2176 // (either because a display has changed, or because a layer
2177 // as changed).
2178 //
2179 // Walk through all the layers in currentLayers,
2180 // and update their transform hint.
2181 //
2182 // If a layer is visible only on a single display, then that
2183 // display is used to calculate the hint, otherwise we use the
2184 // default display.
2185 //
2186 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2187 // the hint is set before we acquire a buffer from the surface texture.
2188 //
2189 // NOTE: layer transactions have taken place already, so we use their
2190 // drawing state. However, SurfaceFlinger's own transaction has not
2191 // happened yet, so we must use the current state layer list
2192 // (soon to become the drawing state list).
2193 //
2194 sp<const DisplayDevice> disp;
2195 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002196 bool first = true;
2197 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002198 // NOTE: we rely on the fact that layers are sorted by
2199 // layerStack first (so we don't have to traverse the list
2200 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002201 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002202 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002203 currentlayerStack = layerStack;
2204 // figure out if this layerstack is mirrored
2205 // (more than one display) if so, pick the default display,
2206 // if not, pick the only display it's on.
2207 disp.clear();
2208 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2209 sp<const DisplayDevice> hw(mDisplays[dpy]);
2210 if (hw->getLayerStack() == currentlayerStack) {
2211 if (disp == NULL) {
2212 disp = hw;
2213 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002214 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002215 break;
2216 }
2217 }
2218 }
2219 }
Chet Haase91d25932013-04-11 15:24:55 -07002220 if (disp == NULL) {
2221 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2222 // redraw after transform hint changes. See bug 8508397.
2223
2224 // could be null when this layer is using a layerStack
2225 // that is not visible on any display. Also can occur at
2226 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002227 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002228 }
Chet Haase91d25932013-04-11 15:24:55 -07002229 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002230
2231 first = false;
2232 });
Mathias Agopian84300952012-11-21 16:02:13 -08002233 }
2234
2235
Mathias Agopian3559b072012-08-15 13:46:03 -07002236 /*
2237 * Perform our own transaction if needed
2238 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002239
2240 if (mLayersAdded) {
2241 mLayersAdded = false;
2242 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002243 mVisibleRegionsDirty = true;
2244 }
2245
2246 // some layers might have been removed, so
2247 // we need to update the regions they're exposing.
2248 if (mLayersRemoved) {
2249 mLayersRemoved = false;
2250 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002251 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002252 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002253 // this layer is not visible anymore
2254 // TODO: we could traverse the tree from front to back and
2255 // compute the actual visible region
2256 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002257 Region visibleReg;
2258 visibleReg.set(layer->computeScreenBounds());
2259 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002260 }
Robert Carr2047fae2016-11-28 14:09:09 -08002261 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262 }
2263
2264 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002265
2266 updateCursorAsync();
2267}
2268
2269void SurfaceFlinger::updateCursorAsync()
2270{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002271 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2272 auto& displayDevice = mDisplays[displayId];
2273 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002274 continue;
2275 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002276
2277 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2278 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002279 }
2280 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002281}
2282
2283void SurfaceFlinger::commitTransaction()
2284{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002285 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002287 for (const auto& l : mLayersPendingRemoval) {
2288 recordBufferingStats(l->getName().string(),
2289 l->getOccupancyHistory(true));
2290 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002291 }
2292 mLayersPendingRemoval.clear();
2293 }
2294
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002295 // If this transaction is part of a window animation then the next frame
2296 // we composite should be considered an animation as well.
2297 mAnimCompositionPending = mAnimTransactionPending;
2298
Mathias Agopian4fec8732012-06-29 14:12:52 -07002299 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300 mDrawingState.traverseInZOrder([](Layer* layer) {
2301 layer->commitChildList();
2302 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002303 mTransactionPending = false;
2304 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002305 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306}
2307
Robert Carr2047fae2016-11-28 14:09:09 -08002308void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002309 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310{
Mathias Agopian841cde52012-03-01 15:44:37 -08002311 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314 Region aboveOpaqueLayers;
2315 Region aboveCoveredLayers;
2316 Region dirty;
2317
Mathias Agopian87baae12012-07-31 12:38:26 -07002318 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Robert Carr2047fae2016-11-28 14:09:09 -08002320 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002322 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323
Jesse Hall01e29052013-02-19 16:13:35 -08002324 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002325 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002326 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002327
Mathias Agopianab028732010-03-16 16:41:46 -07002328 /*
2329 * opaqueRegion: area of a surface that is fully opaque.
2330 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002332
2333 /*
2334 * visibleRegion: area of a surface that is visible on screen
2335 * and not fully transparent. This is essentially the layer's
2336 * footprint minus the opaque regions above it.
2337 * Areas covered by a translucent surface are considered visible.
2338 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002340
2341 /*
2342 * coveredRegion: area of a surface that is covered by all
2343 * visible regions above it (which includes the translucent areas).
2344 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002346
Jesse Halla8026d22012-09-25 13:25:04 -07002347 /*
2348 * transparentRegion: area of a surface that is hinted to be completely
2349 * transparent. This is only used to tell when the layer has no visible
2350 * non-transparent regions and can be removed from the layer list. It
2351 * does not affect the visibleRegion of this layer or any layers
2352 * beneath it. The hint may not be correct if apps don't respect the
2353 * SurfaceView restrictions (which, sadly, some don't).
2354 */
2355 Region transparentRegion;
2356
Mathias Agopianab028732010-03-16 16:41:46 -07002357
2358 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002359 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002360 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002361 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002363 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002364 if (!visibleRegion.isEmpty()) {
2365 // Remove the transparent area from the visible region
2366 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002367 if (tr.preserveRects()) {
2368 // transform the transparent region
2369 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002370 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002371 // transformation too complex, can't do the
2372 // transparent region optimization.
2373 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002374 }
Mathias Agopianab028732010-03-16 16:41:46 -07002375 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376
Mathias Agopianab028732010-03-16 16:41:46 -07002377 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002378 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002379 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002380 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2381 // the opaque region is the layer's footprint
2382 opaqueRegion = visibleRegion;
2383 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384 }
2385 }
2386
Mathias Agopianab028732010-03-16 16:41:46 -07002387 // Clip the covered region to the visible region
2388 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2389
2390 // Update aboveCoveredLayers for next (lower) layer
2391 aboveCoveredLayers.orSelf(visibleRegion);
2392
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393 // subtract the opaque region covered by the layers above us
2394 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395
2396 // compute this layer's dirty region
2397 if (layer->contentDirty) {
2398 // we need to invalidate the whole region
2399 dirty = visibleRegion;
2400 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002401 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402 layer->contentDirty = false;
2403 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002404 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002405 * the exposed region consists of two components:
2406 * 1) what's VISIBLE now and was COVERED before
2407 * 2) what's EXPOSED now less what was EXPOSED before
2408 *
2409 * note that (1) is conservative, we start with the whole
2410 * visible region but only keep what used to be covered by
2411 * something -- which mean it may have been exposed.
2412 *
2413 * (2) handles areas that were not covered by anything but got
2414 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002415 */
Mathias Agopianab028732010-03-16 16:41:46 -07002416 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002417 const Region oldVisibleRegion = layer->visibleRegion;
2418 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002419 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2420 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421 }
2422 dirty.subtractSelf(aboveOpaqueLayers);
2423
2424 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002425 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426
Mathias Agopianab028732010-03-16 16:41:46 -07002427 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002429
Jesse Halla8026d22012-09-25 13:25:04 -07002430 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 layer->setVisibleRegion(visibleRegion);
2432 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002433 layer->setVisibleNonTransparentRegion(
2434 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002435 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436
Mathias Agopian87baae12012-07-31 12:38:26 -07002437 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438}
2439
Mathias Agopian87baae12012-07-31 12:38:26 -07002440void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2441 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002442 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002443 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2444 if (hw->getLayerStack() == layerStack) {
2445 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002446 }
2447 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002448}
2449
Dan Stoza6b9454d2014-11-07 16:00:59 -08002450bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002452 ALOGV("handlePageFlip");
2453
Brian Andersond6927fb2016-07-23 23:37:30 -07002454 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Mathias Agopian4fec8732012-06-29 14:12:52 -07002456 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002457 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002458 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002459
2460 // Store the set of layers that need updates. This set must not change as
2461 // buffers are being latched, as this could result in a deadlock.
2462 // Example: Two producers share the same command stream and:
2463 // 1.) Layer 0 is latched
2464 // 2.) Layer 0 gets a new frame
2465 // 2.) Layer 1 gets a new frame
2466 // 3.) Layer 1 is latched.
2467 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2468 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002469 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002470 if (layer->hasQueuedFrame()) {
2471 frameQueued = true;
2472 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002473 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002474 } else {
2475 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002476 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002477 } else {
2478 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002479 }
Robert Carr2047fae2016-11-28 14:09:09 -08002480 });
2481
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002483 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002484 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002485 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002486 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002487 newDataLatched = true;
2488 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002489 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002490
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002491 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002492
2493 // If we will need to wake up at some time in the future to deal with a
2494 // queued frame that shouldn't be displayed during this vsync period, wake
2495 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002496 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002497 signalLayerUpdate();
2498 }
2499
2500 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002501 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502}
2503
Mathias Agopianad456f92011-01-13 17:53:01 -08002504void SurfaceFlinger::invalidateHwcGeometry()
2505{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002506 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002507}
2508
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002509
Fabien Sanglard830b8472016-11-30 16:35:58 -08002510void SurfaceFlinger::doDisplayComposition(
2511 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002512 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513{
Dan Stoza71433162014-02-04 16:22:36 -08002514 // We only need to actually compose the display if:
2515 // 1) It is being handled by hardware composer, which may need this to
2516 // keep its virtual display state machine in sync, or
2517 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002518 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002519 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002520 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002521 return;
2522 }
2523
Dan Stoza9e56aa02015-11-02 13:00:03 -08002524 ALOGV("doDisplayComposition");
2525
Mathias Agopian87baae12012-07-31 12:38:26 -07002526 Region dirtyRegion(inDirtyRegion);
2527
Mathias Agopianb8a55602009-06-26 19:06:36 -07002528 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002529 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530
Fabien Sanglard830b8472016-11-30 16:35:58 -08002531 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002532 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002533 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2534 // takes a rectangle, we must make sure to update that whole
2535 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002536 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002537 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002538 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002539 // We need to redraw the rectangle that will be updated
2540 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002541 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002542 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002543 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002544 } else {
2545 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002546 dirtyRegion.set(displayDevice->bounds());
2547 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548 }
2549 }
2550
Fabien Sanglard830b8472016-11-30 16:35:58 -08002551 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002553 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002554 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002555
2556 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002557 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558}
2559
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560bool SurfaceFlinger::doComposeSurfaces(
2561 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002562{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002563 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002564
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002566
2567 mat4 oldColorMatrix;
2568 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2569 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2570 if (applyColorMatrix) {
2571 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2572 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2573 }
2574
Dan Stoza9e56aa02015-11-02 13:00:03 -08002575 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2576 if (hasClientComposition) {
2577 ALOGV("hasClientComposition");
2578
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002579#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002580 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002581 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002582#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002583 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002584 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002586 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002587
2588 // |mStateLock| not needed as we are on the main thread
2589 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002590 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2591 }
2592 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002593 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002594
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002595 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2597 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002598 // when using overlays, we assume a fully transparent framebuffer
2599 // NOTE: we could reduce how much we need to clear, for instance
2600 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002601 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002602 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002604 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002605 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002607
2608 // we remove the scissor part
2609 // we're left with the letterbox region
2610 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002612
2613 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002615
2616 // but limit it to the dirty region
2617 region.andSelf(dirty);
2618
Mathias Agopianb9494d52012-04-18 02:28:45 -07002619 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002620 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002621 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002622 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002623 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002624 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002625
Dan Stoza9e56aa02015-11-02 13:00:03 -08002626 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002627 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002628 // scissor on the main display. It should never be needed
2629 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 const Rect& bounds(displayDevice->getBounds());
2631 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002632 if (scissor != bounds) {
2633 // scissor doesn't match the screen's dimensions, so we
2634 // need to clear everything outside of it and enable
2635 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002636
Mathias Agopianf45c5102012-10-24 16:29:17 -07002637 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002638 const uint32_t height = displayDevice->getHeight();
2639 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002640 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002641 }
2642 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002643 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002644
Mathias Agopian85d751c2012-08-29 16:59:24 -07002645 /*
2646 * and then, render the layers targeted at the framebuffer
2647 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002648
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 ALOGV("Rendering client layers");
2650 const Transform& displayTransform = displayDevice->getTransform();
2651 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002652 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002653 bool firstLayer = true;
2654 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2655 const Region clip(dirty.intersect(
2656 displayTransform.transform(layer->visibleRegion)));
2657 ALOGV("Layer: %s", layer->getName().string());
2658 ALOGV(" Composition type: %s",
2659 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002660 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 switch (layer->getCompositionType(hwcId)) {
2662 case HWC2::Composition::Cursor:
2663 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002664 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002666 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2668 layer->isOpaque(state) && (state.alpha == 1.0f)
2669 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002670 // never clear the very first layer since we're
2671 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002672 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002673 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002674 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002676 case HWC2::Composition::Client: {
2677 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002678 break;
2679 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002681 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002682 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002683 } else {
2684 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002685 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002687 }
2688 } else {
2689 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002691 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002693 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002695 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002696 }
2697 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002698
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002699 if (applyColorMatrix) {
2700 getRenderEngine().setupColorTransform(oldColorMatrix);
2701 }
2702
Mathias Agopianf45c5102012-10-24 16:29:17 -07002703 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002705 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706}
2707
Fabien Sanglard830b8472016-11-30 16:35:58 -08002708void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2709 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002710 RenderEngine& engine(getRenderEngine());
2711 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Dan Stoza7d89d062015-04-30 13:29:25 -07002714status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002715 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002716 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 const sp<Layer>& lbc,
2718 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002719{
Dan Stoza7d89d062015-04-30 13:29:25 -07002720 // add this layer to the current state list
2721 {
2722 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002724 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2725 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002726 return NO_MEMORY;
2727 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002728 if (parent == nullptr) {
2729 mCurrentState.layersSortedByZ.add(lbc);
2730 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002731 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2732 ALOGE("addClientLayer called with a removed parent");
2733 return NAME_NOT_FOUND;
2734 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 parent->addChild(lbc);
2736 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002737
Dan Stoza7d89d062015-04-30 13:29:25 -07002738 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 mLayersAdded = true;
2740 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002741 }
2742
Mathias Agopian96f08192010-06-02 23:28:45 -07002743 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002744 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002745
Dan Stoza7d89d062015-04-30 13:29:25 -07002746 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002747}
2748
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002749status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002750 Mutex::Autolock _l(mStateLock);
2751
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002753 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002754 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002755 if (topLevelOnly) {
2756 return NO_ERROR;
2757 }
2758
Chia-I Wu98f1c102017-05-30 14:54:08 -07002759 sp<Layer> ancestor = p;
2760 while (ancestor->getParent() != nullptr) {
2761 ancestor = ancestor->getParent();
2762 }
2763 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2764 ALOGE("removeLayer called with a layer whose parent has been removed");
2765 return NAME_NOT_FOUND;
2766 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002767
2768 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002769 } else {
2770 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002771 }
2772
Robert Carr136e2f62017-02-08 17:54:29 -08002773 // As a matter of normal operation, the LayerCleaner will produce a second
2774 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2775 // so we will succeed in promoting it, but it's already been removed
2776 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2777 // otherwise something has gone wrong and we are leaking the layer.
2778 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002779 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2780 layer->getName().string(),
2781 (p != nullptr) ? p->getName().string() : "no-parent");
2782 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002783 } else if (index < 0) {
2784 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002785 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786
2787 mLayersPendingRemoval.add(layer);
2788 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002789 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 setTransactionFlags(eTransactionNeeded);
2791 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792}
2793
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002794uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002795 return android_atomic_release_load(&mTransactionFlags);
2796}
2797
Mathias Agopian3f844832013-08-07 21:24:32 -07002798uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2800}
2801
Mathias Agopian3f844832013-08-07 21:24:32 -07002802uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2804 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002805 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 }
2807 return old;
2808}
2809
Mathias Agopian8b33f032012-07-24 20:43:54 -07002810void SurfaceFlinger::setTransactionState(
2811 const Vector<ComposerState>& state,
2812 const Vector<DisplayState>& displays,
2813 uint32_t flags)
2814{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002815 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002816 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002817 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002818
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002819 if (flags & eAnimation) {
2820 // For window updates that are part of an animation we must wait for
2821 // previous animation "frames" to be handled.
2822 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002823 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002824 if (CC_UNLIKELY(err != NO_ERROR)) {
2825 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002826 // caller after a few seconds.
2827 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2828 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002829 mAnimTransactionPending = false;
2830 break;
2831 }
2832 }
2833 }
2834
Mathias Agopiane57f2922012-08-09 16:29:12 -07002835 size_t count = displays.size();
2836 for (size_t i=0 ; i<count ; i++) {
2837 const DisplayState& s(displays[i]);
2838 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002839 }
2840
Mathias Agopiane57f2922012-08-09 16:29:12 -07002841 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002842 for (size_t i=0 ; i<count ; i++) {
2843 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002844 // Here we need to check that the interface we're given is indeed
2845 // one of our own. A malicious client could give us a NULL
2846 // IInterface, or one of its own or even one of our own but a
2847 // different type. All these situations would cause us to crash.
2848 //
2849 // NOTE: it would be better to use RTTI as we could directly check
2850 // that we have a Client*. however, RTTI is disabled in Android.
2851 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002852 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002853 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002854 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002855 sp<Client> client( static_cast<Client *>(s.client.get()) );
2856 transactionFlags |= setClientStateLocked(client, s.state);
2857 }
2858 }
2859 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002860 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002861
Robert Carr2a7dbb42016-05-24 11:41:28 -07002862 // If a synchronous transaction is explicitly requested without any changes,
2863 // force a transaction anyway. This can be used as a flush mechanism for
2864 // previous async transactions.
2865 if (transactionFlags == 0 && (flags & eSynchronous)) {
2866 transactionFlags = eTransactionNeeded;
2867 }
2868
Mathias Agopian386aa982011-11-07 21:58:03 -08002869 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002870 if (mInterceptor.isEnabled()) {
2871 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2872 }
Irvel468051e2016-06-13 16:44:44 -07002873
Mathias Agopian386aa982011-11-07 21:58:03 -08002874 // this triggers the transaction
2875 setTransactionFlags(transactionFlags);
2876
2877 // if this is a synchronous transaction, wait for it to take effect
2878 // before returning.
2879 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002880 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002881 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002882 if (flags & eAnimation) {
2883 mAnimTransactionPending = true;
2884 }
2885 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002886 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2887 if (CC_UNLIKELY(err != NO_ERROR)) {
2888 // just in case something goes wrong in SF, return to the
2889 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002890 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2891 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002892 break;
2893 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002894 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 }
2896}
2897
Mathias Agopiane57f2922012-08-09 16:29:12 -07002898uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2899{
Jesse Hall9a143922012-10-04 16:29:19 -07002900 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2901 if (dpyIdx < 0)
2902 return 0;
2903
Mathias Agopiane57f2922012-08-09 16:29:12 -07002904 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002905 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002906 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002907 const uint32_t what = s.what;
2908 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002909 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910 disp.surface = s.surface;
2911 flags |= eDisplayTransactionNeeded;
2912 }
2913 }
2914 if (what & DisplayState::eLayerStackChanged) {
2915 if (disp.layerStack != s.layerStack) {
2916 disp.layerStack = s.layerStack;
2917 flags |= eDisplayTransactionNeeded;
2918 }
2919 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002920 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002921 if (disp.orientation != s.orientation) {
2922 disp.orientation = s.orientation;
2923 flags |= eDisplayTransactionNeeded;
2924 }
2925 if (disp.frame != s.frame) {
2926 disp.frame = s.frame;
2927 flags |= eDisplayTransactionNeeded;
2928 }
2929 if (disp.viewport != s.viewport) {
2930 disp.viewport = s.viewport;
2931 flags |= eDisplayTransactionNeeded;
2932 }
2933 }
Michael Lentine47e45402014-07-18 15:34:25 -07002934 if (what & DisplayState::eDisplaySizeChanged) {
2935 if (disp.width != s.width) {
2936 disp.width = s.width;
2937 flags |= eDisplayTransactionNeeded;
2938 }
2939 if (disp.height != s.height) {
2940 disp.height = s.height;
2941 flags |= eDisplayTransactionNeeded;
2942 }
2943 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002944 }
2945 return flags;
2946}
2947
2948uint32_t SurfaceFlinger::setClientStateLocked(
2949 const sp<Client>& client,
2950 const layer_state_t& s)
2951{
2952 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002953 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002954 if (layer != 0) {
2955 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002956 bool geometryAppliesWithResize =
2957 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002958 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002959 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002960 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002961 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002962 }
2963 if (what & layer_state_t::eLayerChanged) {
2964 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002965 const auto& p = layer->getParent();
2966 if (p == nullptr) {
2967 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2968 if (layer->setLayer(s.z) && idx >= 0) {
2969 mCurrentState.layersSortedByZ.removeAt(idx);
2970 mCurrentState.layersSortedByZ.add(layer);
2971 // we need traversal (state changed)
2972 // AND transaction (list changed)
2973 flags |= eTransactionNeeded|eTraversalNeeded;
2974 }
2975 } else {
2976 if (p->setChildLayer(layer, s.z)) {
2977 flags |= eTransactionNeeded|eTraversalNeeded;
2978 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002979 }
2980 }
Robert Carrdb66e622017-04-10 16:55:57 -07002981 if (what & layer_state_t::eRelativeLayerChanged) {
2982 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2983 flags |= eTransactionNeeded|eTraversalNeeded;
2984 }
2985 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002986 if (what & layer_state_t::eSizeChanged) {
2987 if (layer->setSize(s.w, s.h)) {
2988 flags |= eTraversalNeeded;
2989 }
2990 }
2991 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002993 flags |= eTraversalNeeded;
2994 }
2995 if (what & layer_state_t::eMatrixChanged) {
2996 if (layer->setMatrix(s.matrix))
2997 flags |= eTraversalNeeded;
2998 }
2999 if (what & layer_state_t::eTransparentRegionChanged) {
3000 if (layer->setTransparentRegionHint(s.transparentRegion))
3001 flags |= eTraversalNeeded;
3002 }
Dan Stoza23116082015-06-18 14:58:39 -07003003 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004 if (layer->setFlags(s.flags, s.mask))
3005 flags |= eTraversalNeeded;
3006 }
3007 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003008 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003009 flags |= eTraversalNeeded;
3010 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003011 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003012 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003013 flags |= eTraversalNeeded;
3014 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003015 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003016 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003017 // We only allow setting layer stacks for top level layers,
3018 // everything else inherits layer stack from its parent.
3019 if (layer->hasParent()) {
3020 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3021 layer->getName().string());
3022 } else if (idx < 0) {
3023 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3024 "that also does not appear in the top level layer list. Something"
3025 " has gone wrong.", layer->getName().string());
3026 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003027 mCurrentState.layersSortedByZ.removeAt(idx);
3028 mCurrentState.layersSortedByZ.add(layer);
3029 // we need traversal (state changed)
3030 // AND transaction (list changed)
3031 flags |= eTransactionNeeded|eTraversalNeeded;
3032 }
3033 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003034 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003035 if (s.barrierHandle != nullptr) {
3036 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3037 } else if (s.barrierGbp != nullptr) {
3038 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3039 if (authenticateSurfaceTextureLocked(gbp)) {
3040 const auto& otherLayer =
3041 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3042 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3043 } else {
3044 ALOGE("Attempt to defer transaction to to an"
3045 " unrecognized GraphicBufferProducer");
3046 }
3047 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003048 // We don't trigger a traversal here because if no other state is
3049 // changed, we don't want this to cause any more work
3050 }
Robert Carr1db73f62016-12-21 12:58:51 -08003051 if (what & layer_state_t::eReparentChildren) {
3052 if (layer->reparentChildren(s.reparentHandle)) {
3053 flags |= eTransactionNeeded|eTraversalNeeded;
3054 }
3055 }
Robert Carr9524cb32017-02-13 11:32:32 -08003056 if (what & layer_state_t::eDetachChildren) {
3057 layer->detachChildren();
3058 }
Robert Carrc3574f72016-03-24 12:19:32 -07003059 if (what & layer_state_t::eOverrideScalingModeChanged) {
3060 layer->setOverrideScalingMode(s.overrideScalingMode);
3061 // We don't trigger a traversal here because if no other state is
3062 // changed, we don't want this to cause any more work
3063 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 }
3065 return flags;
3066}
3067
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003068status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003069 const String8& name,
3070 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003071 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003072 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3073 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003075 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003076 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003077 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003078 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003079 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003080
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003081 status_t result = NO_ERROR;
3082
3083 sp<Layer> layer;
3084
Cody Northropbc755282017-03-31 12:00:08 -06003085 String8 uniqueName = getUniqueLayerName(name);
3086
Mathias Agopian3165cc22012-08-08 19:42:09 -07003087 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3088 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003089 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003090 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003091 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003093 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003094 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003095 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003096 handle, gbp, &layer);
3097 break;
3098 default:
3099 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100 break;
3101 }
3102
Dan Stoza7d89d062015-04-30 13:29:25 -07003103 if (result != NO_ERROR) {
3104 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003106
Albert Chaulk479c60c2017-01-27 14:21:34 -05003107 layer->setInfo(windowType, ownerUid);
3108
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003110 if (result != NO_ERROR) {
3111 return result;
3112 }
Irvelffc9efc2016-07-27 15:16:37 -07003113 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003114
3115 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003116 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117}
3118
Cody Northropbc755282017-03-31 12:00:08 -06003119String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3120{
3121 bool matchFound = true;
3122 uint32_t dupeCounter = 0;
3123
3124 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3125 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3126
3127 // Loop over layers until we're sure there is no matching name
3128 while (matchFound) {
3129 matchFound = false;
3130 mDrawingState.traverseInZOrder([&](Layer* layer) {
3131 if (layer->getName() == uniqueName) {
3132 matchFound = true;
3133 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3134 }
3135 });
3136 }
3137
3138 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3139
3140 return uniqueName;
3141}
3142
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003143status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3144 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3145 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146{
3147 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003148 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 case PIXEL_FORMAT_TRANSPARENT:
3150 case PIXEL_FORMAT_TRANSLUCENT:
3151 format = PIXEL_FORMAT_RGBA_8888;
3152 break;
3153 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003154 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 break;
3156 }
3157
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003158 *outLayer = new Layer(this, client, name, w, h, flags);
3159 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3160 if (err == NO_ERROR) {
3161 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003162 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003164
3165 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3166 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167}
3168
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003169status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3170 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3171 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003173 *outLayer = new LayerDim(this, client, name, w, h, flags);
3174 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003175 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003176 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003177}
3178
Mathias Agopianac9fa422013-02-11 16:40:36 -08003179status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180{
Robert Carr9524cb32017-02-13 11:32:32 -08003181 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003182 status_t err = NO_ERROR;
3183 sp<Layer> l(client->getLayerUser(handle));
3184 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003185 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003186 err = removeLayer(l);
3187 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3188 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003189 }
3190 return err;
3191}
3192
Mathias Agopian13127d82013-03-05 17:47:11 -08003193status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003194{
Mathias Agopian67106042013-03-14 19:18:13 -07003195 // called by ~LayerCleaner() when all references to the IBinder (handle)
3196 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003197 sp<Layer> l = layer.promote();
3198 if (l == nullptr) {
3199 // The layer has already been removed, carry on
3200 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003201 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003202 // If we have a parent, then we can continue to live as long as it does.
3203 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204}
3205
Mathias Agopianb60314a2012-04-10 22:09:54 -07003206// ---------------------------------------------------------------------------
3207
Andy McFadden13a082e2012-08-24 10:16:42 -07003208void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003209 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003210 Vector<ComposerState> state;
3211 Vector<DisplayState> displays;
3212 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003213 d.what = DisplayState::eDisplayProjectionChanged |
3214 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003215 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003216 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003217 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003218 d.frame.makeInvalid();
3219 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003220 d.width = 0;
3221 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003222 displays.add(d);
3223 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003224 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003225
Dan Stoza9e56aa02015-11-02 13:00:03 -08003226 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3227 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003228 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003229
Brian Andersond0010582017-03-07 13:20:31 -08003230 // Use phase of 0 since phase is not known.
3231 // Use latency of 0, which will snap to the ideal latency.
3232 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003233}
3234
3235void SurfaceFlinger::initializeDisplays() {
3236 class MessageScreenInitialized : public MessageBase {
3237 SurfaceFlinger* flinger;
3238 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003239 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003240 virtual bool handler() {
3241 flinger->onInitializeDisplays();
3242 return true;
3243 }
3244 };
3245 sp<MessageBase> msg = new MessageScreenInitialized(this);
3246 postMessageAsync(msg); // we may be called from main thread, use async message
3247}
3248
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003249void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3250 int mode) {
3251 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3252 this);
3253 int32_t type = hw->getDisplayType();
3254 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003255
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003256 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003257 return;
3258 }
3259
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003260 hw->setPowerMode(mode);
3261 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3262 ALOGW("Trying to set power mode for virtual display");
3263 return;
3264 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003265
Irvelffc9efc2016-07-27 15:16:37 -07003266 if (mInterceptor.isEnabled()) {
3267 Mutex::Autolock _l(mStateLock);
3268 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3269 if (idx < 0) {
3270 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3271 return;
3272 }
3273 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3274 }
3275
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003276 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003277 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003278 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003279 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3280 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003281 // FIXME: eventthread only knows about the main display right now
3282 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003283 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003285
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003286 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003287 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003288 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003289
3290 struct sched_param param = {0};
3291 param.sched_priority = 1;
3292 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3293 ALOGW("Couldn't set SCHED_FIFO on display on");
3294 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003295 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003296 // Turn off the display
3297 struct sched_param param = {0};
3298 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3299 ALOGW("Couldn't set SCHED_OTHER on display off");
3300 }
3301
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003302 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003303 disableHardwareVsync(true); // also cancels any in-progress resync
3304
Mathias Agopiancde87a32012-09-13 14:09:01 -07003305 // FIXME: eventthread only knows about the main display right now
3306 mEventThread->onScreenReleased();
3307 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003308
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003309 getHwComposer().setPowerMode(type, mode);
3310 mVisibleRegionsDirty = true;
3311 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003312 } else if (mode == HWC_POWER_MODE_DOZE ||
3313 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003314 // Update display while dozing
3315 getHwComposer().setPowerMode(type, mode);
3316 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3317 // FIXME: eventthread only knows about the main display right now
3318 mEventThread->onScreenAcquired();
3319 resyncToHardwareVsync(true);
3320 }
3321 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3322 // Leave display going to doze
3323 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3324 disableHardwareVsync(true); // also cancels any in-progress resync
3325 // FIXME: eventthread only knows about the main display right now
3326 mEventThread->onScreenReleased();
3327 }
3328 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003329 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003330 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003331 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003332 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003333}
3334
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003335void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3336 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003337 SurfaceFlinger& mFlinger;
3338 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003339 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003340 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003341 MessageSetPowerMode(SurfaceFlinger& flinger,
3342 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3343 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003344 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003345 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003346 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003347 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003348 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003349 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003350 ALOGW("Attempt to set power mode = %d for virtual display",
3351 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003352 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003354 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003355 return true;
3356 }
3357 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003358 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003359 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003360}
3361
3362// ---------------------------------------------------------------------------
3363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3365{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003367
Mathias Agopianbd115332013-04-18 16:41:04 -07003368 IPCThreadState* ipc = IPCThreadState::self();
3369 const int pid = ipc->getCallingPid();
3370 const int uid = ipc->getCallingUid();
3371 if ((uid != AID_SHELL) &&
3372 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003373 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003374 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003376 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003377 // (this would indicate SF is stuck, but we want to be able to
3378 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003379 status_t err = mStateLock.timedLock(s2ns(1));
3380 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003381 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003382 result.appendFormat(
3383 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3384 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003385 }
3386
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003387 bool dumpAll = true;
3388 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003389 size_t numArgs = args.size();
3390 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003391 if ((index < numArgs) &&
3392 (args[index] == String16("--list"))) {
3393 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003394 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003395 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003396 }
3397
3398 if ((index < numArgs) &&
3399 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003400 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003401 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003402 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003404
3405 if ((index < numArgs) &&
3406 (args[index] == String16("--latency-clear"))) {
3407 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003408 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003409 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003410 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003411
3412 if ((index < numArgs) &&
3413 (args[index] == String16("--dispsync"))) {
3414 index++;
3415 mPrimaryDispSync.dump(result);
3416 dumpAll = false;
3417 }
Dan Stozab90cf072015-03-05 11:05:59 -08003418
3419 if ((index < numArgs) &&
3420 (args[index] == String16("--static-screen"))) {
3421 index++;
3422 dumpStaticScreenStats(result);
3423 dumpAll = false;
3424 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003425
3426 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003427 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003428 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003429 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003430 dumpAll = false;
3431 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003432
3433 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3434 index++;
3435 dumpWideColorInfo(result);
3436 dumpAll = false;
3437 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003439
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003440 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003441 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003442 }
3443
Mathias Agopian9795c422009-08-26 16:36:26 -07003444 if (locked) {
3445 mStateLock.unlock();
3446 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003447 }
3448 write(fd, result.string(), result.size());
3449 return NO_ERROR;
3450}
3451
Dan Stozac7014012014-02-14 15:03:43 -08003452void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3453 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003454{
Robert Carr2047fae2016-11-28 14:09:09 -08003455 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003456 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003457 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003458}
3459
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003460void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003461 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003462{
3463 String8 name;
3464 if (index < args.size()) {
3465 name = String8(args[index]);
3466 index++;
3467 }
3468
Dan Stoza9e56aa02015-11-02 13:00:03 -08003469 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3470 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003471 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003472
3473 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003474 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003475 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003476 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003477 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003478 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003479 }
Robert Carr2047fae2016-11-28 14:09:09 -08003480 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003481 }
3482}
3483
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003484void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003485 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003486{
3487 String8 name;
3488 if (index < args.size()) {
3489 name = String8(args[index]);
3490 index++;
3491 }
3492
Robert Carr2047fae2016-11-28 14:09:09 -08003493 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003494 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003495 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003496 }
Robert Carr2047fae2016-11-28 14:09:09 -08003497 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003498
Svetoslavd85084b2014-03-20 10:28:31 -07003499 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003500}
3501
Jamie Gennis6547ff42013-07-16 20:12:42 -07003502// This should only be called from the main thread. Otherwise it would need
3503// the lock and should use mCurrentState rather than mDrawingState.
3504void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003505 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003506 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003507 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003508
3509 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3510}
3511
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003512void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003513{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003514 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003515 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3516
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003517 if (isLayerTripleBufferingDisabled())
3518 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003519
3520 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003521 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003522 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003523 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003524 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3525 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003526 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003527}
3528
Dan Stozab90cf072015-03-05 11:05:59 -08003529void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3530{
3531 result.appendFormat("Static screen stats:\n");
3532 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3533 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3534 float percent = 100.0f *
3535 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3536 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3537 b + 1, bucketTimeSec, percent);
3538 }
3539 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3540 float percent = 100.0f *
3541 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3542 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3543 NUM_BUCKETS - 1, bucketTimeSec, percent);
3544}
3545
Dan Stozae77c7662016-05-13 11:37:28 -07003546void SurfaceFlinger::recordBufferingStats(const char* layerName,
3547 std::vector<OccupancyTracker::Segment>&& history) {
3548 Mutex::Autolock lock(mBufferingStatsMutex);
3549 auto& stats = mBufferingStats[layerName];
3550 for (const auto& segment : history) {
3551 if (!segment.usedThirdBuffer) {
3552 stats.twoBufferTime += segment.totalTime;
3553 }
3554 if (segment.occupancyAverage < 1.0f) {
3555 stats.doubleBufferedTime += segment.totalTime;
3556 } else if (segment.occupancyAverage < 2.0f) {
3557 stats.tripleBufferedTime += segment.totalTime;
3558 }
3559 ++stats.numSegments;
3560 stats.totalTime += segment.totalTime;
3561 }
3562}
3563
Brian Andersond6927fb2016-07-23 23:37:30 -07003564void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3565 result.appendFormat("Layer frame timestamps:\n");
3566
3567 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3568 const size_t count = currentLayers.size();
3569 for (size_t i=0 ; i<count ; i++) {
3570 currentLayers[i]->dumpFrameEvents(result);
3571 }
3572}
3573
Dan Stozae77c7662016-05-13 11:37:28 -07003574void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3575 result.append("Buffering stats:\n");
3576 result.append(" [Layer name] <Active time> <Two buffer> "
3577 "<Double buffered> <Triple buffered>\n");
3578 Mutex::Autolock lock(mBufferingStatsMutex);
3579 typedef std::tuple<std::string, float, float, float> BufferTuple;
3580 std::map<float, BufferTuple, std::greater<float>> sorted;
3581 for (const auto& statsPair : mBufferingStats) {
3582 const char* name = statsPair.first.c_str();
3583 const BufferingStats& stats = statsPair.second;
3584 if (stats.numSegments == 0) {
3585 continue;
3586 }
3587 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3588 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3589 stats.totalTime;
3590 float doubleBufferRatio = static_cast<float>(
3591 stats.doubleBufferedTime) / stats.totalTime;
3592 float tripleBufferRatio = static_cast<float>(
3593 stats.tripleBufferedTime) / stats.totalTime;
3594 sorted.insert({activeTime, {name, twoBufferRatio,
3595 doubleBufferRatio, tripleBufferRatio}});
3596 }
3597 for (const auto& sortedPair : sorted) {
3598 float activeTime = sortedPair.first;
3599 const BufferTuple& values = sortedPair.second;
3600 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3601 std::get<0>(values).c_str(), activeTime,
3602 std::get<1>(values), std::get<2>(values),
3603 std::get<3>(values));
3604 }
3605 result.append("\n");
3606}
3607
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003608void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3609 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3610
3611 // TODO: print out if wide-color mode is active or not
3612
3613 for (size_t d = 0; d < mDisplays.size(); d++) {
3614 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3615 int32_t hwcId = displayDevice->getHwcDisplayId();
3616 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3617 continue;
3618 }
3619
3620 result.appendFormat("Display %d color modes:\n", hwcId);
3621 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3622 for (auto&& mode : modes) {
3623 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3624 }
3625
3626 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3627 result.appendFormat(" Current color mode: %s (%d)\n",
3628 decodeColorMode(currentMode).c_str(), currentMode);
3629 }
3630 result.append("\n");
3631}
3632
Mathias Agopian74d211a2013-04-22 16:55:35 +02003633void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3634 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003635{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003636 bool colorize = false;
3637 if (index < args.size()
3638 && (args[index] == String16("--color"))) {
3639 colorize = true;
3640 index++;
3641 }
3642
3643 Colorizer colorizer(colorize);
3644
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003645 // figure out if we're stuck somewhere
3646 const nsecs_t now = systemTime();
3647 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3648 const nsecs_t inTransaction(mDebugInTransaction);
3649 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3650 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3651
3652 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003653 * Dump library configuration.
3654 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003655
3656 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003657 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003658 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003659 appendSfConfigString(result);
3660 appendUiConfigString(result);
3661 appendGuiConfigString(result);
3662 result.append("\n");
3663
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003664 result.append("\nWide-Color information:\n");
3665 dumpWideColorInfo(result);
3666
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003667 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003668 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003669 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003670 result.append(SyncFeatures::getInstance().toString());
3671 result.append("\n");
3672
Dan Stoza9e56aa02015-11-02 13:00:03 -08003673 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3674
Andy McFadden41d67d72014-04-25 16:58:34 -07003675 colorizer.bold(result);
3676 result.append("DispSync configuration: ");
3677 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003678 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003679 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003680 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003681 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003682 result.append("\n");
3683
Dan Stozab90cf072015-03-05 11:05:59 -08003684 // Dump static screen stats
3685 result.append("\n");
3686 dumpStaticScreenStats(result);
3687 result.append("\n");
3688
Dan Stozae77c7662016-05-13 11:37:28 -07003689 dumpBufferingStats(result);
3690
Andy McFadden4803b742012-09-24 19:07:20 -07003691 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003692 * Dump the visible layer list
3693 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003694 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003695 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003696 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003697 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003698 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003699 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003700
3701 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003702 * Dump Display state
3703 */
3704
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003705 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003706 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003707 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003708 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3709 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003710 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003711 }
3712
3713 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003714 * Dump SurfaceFlinger global state
3715 */
3716
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003717 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003718 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003719 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003720
Mathias Agopian888c8222012-08-04 21:10:38 -07003721 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003722 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003723
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003724 colorizer.bold(result);
3725 result.appendFormat("EGL implementation : %s\n",
3726 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3727 colorizer.reset(result);
3728 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003729 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003730
Mathias Agopian875d8e12013-06-07 15:35:48 -07003731 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003732
Mathias Agopian42977342012-08-05 00:40:46 -07003733 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3735 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003736 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003737 " last eglSwapBuffers() time: %f us\n"
3738 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003739 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003740 " refresh-rate : %f fps\n"
3741 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003742 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003743 " gpu_to_cpu_unsupported : %d\n"
3744 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003745 mLastSwapBufferTime/1000.0,
3746 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003747 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003748 1e9 / activeConfig->getVsyncPeriod(),
3749 activeConfig->getDpiX(),
3750 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003751 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752
Mathias Agopian74d211a2013-04-22 16:55:35 +02003753 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003754 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003755
Mathias Agopian74d211a2013-04-22 16:55:35 +02003756 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758
3759 /*
3760 * VSYNC state
3761 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003762 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003763 result.append("\n");
3764
3765 /*
3766 * HWC layer minidump
3767 */
3768 for (size_t d = 0; d < mDisplays.size(); d++) {
3769 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3770 int32_t hwcId = displayDevice->getHwcDisplayId();
3771 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3772 continue;
3773 }
3774
3775 result.appendFormat("Display %d HWC layers:\n", hwcId);
3776 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003777 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003778 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003779 });
Dan Stozae22aec72016-08-01 13:20:59 -07003780 result.append("\n");
3781 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003782
3783 /*
3784 * Dump HWComposer state
3785 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003786 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003787 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003788 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003789 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003790 result.appendFormat(" h/w composer %s\n",
3791 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003792 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003793
3794 /*
3795 * Dump gralloc state
3796 */
3797 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3798 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003799
3800 /*
3801 * Dump VrFlinger state if in use.
3802 */
3803 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3804 result.append("VrFlinger state:\n");
3805 result.append(mVrFlinger->Dump().c_str());
3806 result.append("\n");
3807 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003808}
3809
Mathias Agopian13127d82013-03-05 17:47:11 -08003810const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003811SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003812 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003813 wp<IBinder> dpy;
3814 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3815 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3816 dpy = mDisplays.keyAt(i);
3817 break;
3818 }
3819 }
3820 if (dpy == NULL) {
3821 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3822 // Just use the primary display so we have something to return
3823 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3824 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003825 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003826}
3827
Keun young Park63f165f2012-08-31 10:53:36 -07003828bool SurfaceFlinger::startDdmConnection()
3829{
3830 void* libddmconnection_dso =
3831 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3832 if (!libddmconnection_dso) {
3833 return false;
3834 }
3835 void (*DdmConnection_start)(const char* name);
3836 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003837 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003838 if (!DdmConnection_start) {
3839 dlclose(libddmconnection_dso);
3840 return false;
3841 }
3842 (*DdmConnection_start)(getServiceName());
3843 return true;
3844}
3845
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003846status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847 switch (code) {
3848 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003849 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003850 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003851 case CLEAR_ANIMATION_FRAME_STATS:
3852 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003854 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855 {
3856 // codes that require permission check
3857 IPCThreadState* ipc = IPCThreadState::self();
3858 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003859 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003860 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003861 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003862 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003863 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003864 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003865 break;
3866 }
Robert Carr1db73f62016-12-21 12:58:51 -08003867 /*
3868 * Calling setTransactionState is safe, because you need to have been
3869 * granted a reference to Client* and Handle* to do anything with it.
3870 *
3871 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3872 */
3873 case SET_TRANSACTION_STATE:
3874 case CREATE_SCOPED_CONNECTION:
3875 {
3876 return OK;
3877 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003878 case CAPTURE_SCREEN:
3879 {
3880 // codes that require permission check
3881 IPCThreadState* ipc = IPCThreadState::self();
3882 const int pid = ipc->getCallingPid();
3883 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003884 if ((uid != AID_GRAPHICS) &&
3885 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003886 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003887 return PERMISSION_DENIED;
3888 }
3889 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003890 }
3891 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003892 return OK;
3893}
3894
3895status_t SurfaceFlinger::onTransact(
3896 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3897{
3898 status_t credentialCheck = CheckTransactCodeCredentials(code);
3899 if (credentialCheck != OK) {
3900 return credentialCheck;
3901 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003902
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3904 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003905 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003906 IPCThreadState* ipc = IPCThreadState::self();
3907 const int uid = ipc->getCallingUid();
3908 if (CC_UNLIKELY(uid != AID_SYSTEM
3909 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003910 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003911 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003912 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003913 return PERMISSION_DENIED;
3914 }
3915 int n;
3916 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003917 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003918 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 return NO_ERROR;
3920 case 1002: // SHOW_UPDATES
3921 n = data.readInt32();
3922 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003923 invalidateHwcGeometry();
3924 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003927 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003928 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003930 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003931 setTransactionFlags(
3932 eTransactionNeeded|
3933 eDisplayTransactionNeeded|
3934 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003935 return NO_ERROR;
3936 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003937 case 1006:{ // send empty update
3938 signalRefresh();
3939 return NO_ERROR;
3940 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003941 case 1008: // toggle use of hw composer
3942 n = data.readInt32();
3943 mDebugDisableHWC = n ? 1 : 0;
3944 invalidateHwcGeometry();
3945 repaintEverything();
3946 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003947 case 1009: // toggle use of transform hint
3948 n = data.readInt32();
3949 mDebugDisableTransformHint = n ? 1 : 0;
3950 invalidateHwcGeometry();
3951 repaintEverything();
3952 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003953 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003954 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955 reply->writeInt32(0);
3956 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003957 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003958 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003959 return NO_ERROR;
3960 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003961 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003962 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003963 return NO_ERROR;
3964 }
3965 case 1014: {
3966 // daltonize
3967 n = data.readInt32();
3968 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003969 case 1:
3970 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3971 break;
3972 case 2:
3973 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3974 break;
3975 case 3:
3976 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3977 break;
3978 default:
3979 mDaltonizer.setType(ColorBlindnessType::None);
3980 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003981 }
3982 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003983 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003984 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003985 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003986 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003987 invalidateHwcGeometry();
3988 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003989 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003991 case 1015: {
3992 // apply a color matrix
3993 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003994 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003995 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003996 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003997 for (size_t j = 0; j < 4; j++) {
3998 mColorMatrix[i][j] = data.readFloat();
3999 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004000 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004001 } else {
4002 mColorMatrix = mat4();
4003 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004004
4005 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4006 // the division by w in the fragment shader
4007 float4 lastRow(transpose(mColorMatrix)[3]);
4008 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4009 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4010 }
4011
Alan Viverette9c5a3332013-09-12 20:04:35 -07004012 invalidateHwcGeometry();
4013 repaintEverything();
4014 return NO_ERROR;
4015 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004016 // This is an experimental interface
4017 // Needs to be shifted to proper binder interface when we productize
4018 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004019 n = data.readInt32();
4020 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004021 return NO_ERROR;
4022 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004023 case 1017: {
4024 n = data.readInt32();
4025 mForceFullDamage = static_cast<bool>(n);
4026 return NO_ERROR;
4027 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004028 case 1018: { // Modify Choreographer's phase offset
4029 n = data.readInt32();
4030 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4031 return NO_ERROR;
4032 }
4033 case 1019: { // Modify SurfaceFlinger's phase offset
4034 n = data.readInt32();
4035 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4036 return NO_ERROR;
4037 }
Irvel468051e2016-06-13 16:44:44 -07004038 case 1020: { // Layer updates interceptor
4039 n = data.readInt32();
4040 if (n) {
4041 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004042 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004043 }
4044 else{
4045 ALOGV("Interceptor disabled");
4046 mInterceptor.disable();
4047 }
4048 return NO_ERROR;
4049 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004050 case 1021: { // Disable HWC virtual displays
4051 n = data.readInt32();
4052 mUseHwcVirtualDisplays = !n;
4053 return NO_ERROR;
4054 }
Romain Guy0147a172017-06-01 13:53:56 -07004055 case 1022: { // Set saturation boost
4056 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4057
4058 invalidateHwcGeometry();
4059 repaintEverything();
4060 return NO_ERROR;
4061 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 }
4063 }
4064 return err;
4065}
4066
Mathias Agopian53331da2011-08-22 21:44:41 -07004067void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004068 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004069 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004070}
4071
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004072// Checks that the requested width and height are valid and updates them to the display dimensions
4073// if they are set to 0
4074static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4075 Transform::orientation_flags rotation,
4076 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4077 // get screen geometry
4078 uint32_t displayWidth = displayDevice->getWidth();
4079 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004080
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004081 if (rotation & Transform::ROT_90) {
4082 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004083 }
4084
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004085 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4086 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4087 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4088 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004089 }
4090
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004091 if (*requestedWidth == 0) {
4092 *requestedWidth = displayWidth;
4093 }
4094 if (*requestedHeight == 0) {
4095 *requestedHeight = displayHeight;
4096 }
4097
4098 return NO_ERROR;
4099}
4100
4101// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4102class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004103public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004104 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4105 ~WindowDisconnector() {
4106 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004107 }
4108
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004109private:
4110 ANativeWindow* mWindow;
4111 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004112};
4113
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004114static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4115 uint32_t requestedHeight, bool hasWideColorDisplay,
4116 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4117 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4118 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4119
4120 int err = 0;
4121 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4122 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4123 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4124 err |= native_window_set_usage(window, usage);
4125
4126 if (hasWideColorDisplay) {
4127 err |= native_window_set_buffers_data_space(window,
4128 renderEngineUsesWideColor
4129 ? HAL_DATASPACE_DISPLAY_P3
4130 : HAL_DATASPACE_V0_SRGB);
4131 }
4132
4133 if (err != NO_ERROR) {
4134 return BAD_VALUE;
4135 }
4136
4137 /* TODO: Once we have the sync framework everywhere this can use
4138 * server-side waits on the fence that dequeueBuffer returns.
4139 */
4140 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4141 if (err != NO_ERROR) {
4142 return err;
4143 }
4144
4145 return NO_ERROR;
4146}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004147
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004148status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4149 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004150 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004151 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004152 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004153 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004154
4155 if (CC_UNLIKELY(display == 0))
4156 return BAD_VALUE;
4157
4158 if (CC_UNLIKELY(producer == 0))
4159 return BAD_VALUE;
4160
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004161 // if we have secure windows on this display, never allow the screen capture
4162 // unless the producer interface is local (i.e.: we can take a screenshot for
4163 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004164 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004165
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004166 // Convert to surfaceflinger's internal rotation type.
4167 Transform::orientation_flags rotationFlags;
4168 switch (rotation) {
4169 case ISurfaceComposer::eRotateNone:
4170 rotationFlags = Transform::ROT_0;
4171 break;
4172 case ISurfaceComposer::eRotate90:
4173 rotationFlags = Transform::ROT_90;
4174 break;
4175 case ISurfaceComposer::eRotate180:
4176 rotationFlags = Transform::ROT_180;
4177 break;
4178 case ISurfaceComposer::eRotate270:
4179 rotationFlags = Transform::ROT_270;
4180 break;
4181 default:
4182 rotationFlags = Transform::ROT_0;
4183 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4184 break;
4185 }
4186
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004187 { // Autolock scope
4188 Mutex::Autolock lock(mStateLock);
4189 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4190 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004191 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004192
4193 // create a surface (because we're a producer, and we need to
4194 // dequeue/queue a buffer)
4195 sp<Surface> surface = new Surface(producer, false);
4196
4197 // Put the screenshot Surface into async mode so that
4198 // Layer::headFenceHasSignaled will always return true and we'll latch the
4199 // first buffer regardless of whether or not its acquire fence has
4200 // signaled. This is needed to avoid a race condition in the rotation
4201 // animation. See b/30209608
4202 surface->setAsyncMode(true);
4203
4204 ANativeWindow* window = surface.get();
4205
4206 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4207 if (result != NO_ERROR) {
4208 return result;
4209 }
4210 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4211
4212 ANativeWindowBuffer* buffer = nullptr;
4213 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4214 getRenderEngine().usesWideColor(), &buffer);
4215 if (result != NO_ERROR) {
4216 return result;
4217 }
4218
4219 // This mutex protects syncFd and captureResult for communication of the return values from the
4220 // main thread back to this Binder thread
4221 std::mutex captureMutex;
4222 std::condition_variable captureCondition;
4223 std::unique_lock<std::mutex> captureLock(captureMutex);
4224 int syncFd = -1;
4225 std::optional<status_t> captureResult;
4226
4227 sp<LambdaMessage> message = new LambdaMessage([&]() {
4228 // If there is a refresh pending, bug out early and tell the binder thread to try again
4229 // after the refresh.
4230 if (mRefreshPending) {
4231 ATRACE_NAME("Skipping screenshot for now");
4232 std::unique_lock<std::mutex> captureLock(captureMutex);
4233 captureResult = std::make_optional<status_t>(EAGAIN);
4234 captureCondition.notify_one();
4235 return;
4236 }
4237
4238 status_t result = NO_ERROR;
4239 int fd = -1;
4240 {
4241 Mutex::Autolock _l(mStateLock);
4242 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4243 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4244 minLayerZ, maxLayerZ, useIdentityTransform,
4245 rotationFlags, isLocalScreenshot, &fd);
4246 }
4247
4248 {
4249 std::unique_lock<std::mutex> captureLock(captureMutex);
4250 syncFd = fd;
4251 captureResult = std::make_optional<status_t>(result);
4252 captureCondition.notify_one();
4253 }
4254 });
4255
4256 result = postMessageAsync(message);
4257 if (result == NO_ERROR) {
4258 captureCondition.wait(captureLock, [&]() { return captureResult; });
4259 while (*captureResult == EAGAIN) {
4260 captureResult.reset();
4261 result = postMessageAsync(message);
4262 if (result != NO_ERROR) {
4263 return result;
4264 }
4265 captureCondition.wait(captureLock, [&]() { return captureResult; });
4266 }
4267 result = *captureResult;
4268 }
4269
4270 if (result == NO_ERROR) {
4271 // queueBuffer takes ownership of syncFd
4272 result = window->queueBuffer(window, buffer, syncFd);
4273 }
4274
4275 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004276}
4277
Mathias Agopian180f10d2013-04-10 22:55:41 -07004278
4279void SurfaceFlinger::renderScreenImplLocked(
4280 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004281 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004282 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004283 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004284{
4285 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004286 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004287
4288 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004289 const int32_t hw_w = hw->getWidth();
4290 const int32_t hw_h = hw->getHeight();
4291 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004292 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004293
Dan Stozac1879002014-05-22 15:59:05 -07004294 // if a default or invalid sourceCrop is passed in, set reasonable values
4295 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4296 !sourceCrop.isValid()) {
4297 sourceCrop.setLeftTop(Point(0, 0));
4298 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4299 }
4300
4301 // ensure that sourceCrop is inside screen
4302 if (sourceCrop.left < 0) {
4303 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4304 }
Dan Stozabe31f442014-06-11 11:20:54 -07004305 if (sourceCrop.right > hw_w) {
4306 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004307 }
4308 if (sourceCrop.top < 0) {
4309 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4310 }
Dan Stozabe31f442014-06-11 11:20:54 -07004311 if (sourceCrop.bottom > hw_h) {
4312 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004313 }
4314
Romain Guy88d37dd2017-05-26 17:57:05 -07004315#ifdef USE_HWC2
4316 engine.setWideColor(hw->getWideColorSupport());
4317 engine.setColorMode(hw->getActiveColorMode());
4318#endif
4319
Mathias Agopian180f10d2013-04-10 22:55:41 -07004320 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004321 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004322
4323 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004324 engine.setViewportAndProjection(
4325 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004326 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004327
4328 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004329 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004330
Robert Carr1f0a16a2016-10-24 16:27:39 -07004331 // We loop through the first level of layers without traversing,
4332 // as we need to interpret min/max layer Z in the top level Z space.
4333 for (const auto& layer : mDrawingState.layersSortedByZ) {
4334 if (layer->getLayerStack() != hw->getLayerStack()) {
4335 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004336 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004337 const Layer::State& state(layer->getDrawingState());
4338 if (state.z < minLayerZ || state.z > maxLayerZ) {
4339 continue;
4340 }
Dan Stoza412903f2017-04-27 13:42:17 -07004341 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004342 if (!layer->isVisible()) {
4343 return;
4344 }
4345 if (filtering) layer->setFiltering(true);
4346 layer->draw(hw, useIdentityTransform);
4347 if (filtering) layer->setFiltering(false);
4348 });
4349 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004350
Mathias Agopian931bda12013-08-28 18:11:46 -07004351 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004352}
4353
Dan Stozaabcda352017-06-01 14:37:39 -07004354// A simple RAII class that holds an EGLImage and destroys it either:
4355// a) When the destroy() method is called
4356// b) When the object goes out of scope
4357class ImageHolder {
4358public:
4359 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4360 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004361
Dan Stozaabcda352017-06-01 14:37:39 -07004362 void destroy() {
4363 if (mImage != EGL_NO_IMAGE_KHR) {
4364 eglDestroyImageKHR(mDisplay, mImage);
4365 mImage = EGL_NO_IMAGE_KHR;
4366 }
4367 }
4368
4369private:
4370 const EGLDisplay mDisplay;
4371 EGLImageKHR mImage;
4372};
4373
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004374status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4375 ANativeWindowBuffer* buffer, Rect sourceCrop,
4376 uint32_t reqWidth, uint32_t reqHeight,
4377 int32_t minLayerZ, int32_t maxLayerZ,
4378 bool useIdentityTransform,
4379 Transform::orientation_flags rotation,
4380 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004381 ATRACE_CALL();
4382
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004383 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004384 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004385 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004386 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4387 (state.z < minLayerZ || state.z > maxLayerZ)) {
4388 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004389 }
Dan Stoza412903f2017-04-27 13:42:17 -07004390 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004391 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4392 layer->isSecure());
4393 });
4394 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004395
4396 if (!isLocalScreenshot && secureLayerIsVisible) {
4397 ALOGW("FB is protected: PERMISSION_DENIED");
4398 return PERMISSION_DENIED;
4399 }
4400
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004401 int syncFd = -1;
4402 // create an EGLImage from the buffer so we can later
4403 // turn it into a texture
4404 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4405 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4406 if (image == EGL_NO_IMAGE_KHR) {
4407 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004408 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004409
Dan Stozaabcda352017-06-01 14:37:39 -07004410 // This will automatically destroy the image if we return before calling its destroy method
4411 ImageHolder imageHolder(mEGLDisplay, image);
4412
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004413 // this binds the given EGLImage as a framebuffer for the
4414 // duration of this scope.
4415 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004416 if (imageBond.getStatus() != NO_ERROR) {
4417 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004418 return INVALID_OPERATION;
4419 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004420
Dan Stozaabcda352017-06-01 14:37:39 -07004421 // this will in fact render into our dequeued buffer
4422 // via an FBO, which means we didn't have to create
4423 // an EGLSurface and therefore we're not
4424 // dependent on the context's EGLConfig.
4425 renderScreenImplLocked(
4426 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4427 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004428
Dan Stozaabcda352017-06-01 14:37:39 -07004429 // Attempt to create a sync khr object that can produce a sync point. If that
4430 // isn't available, create a non-dupable sync object in the fallback path and
4431 // wait on it directly.
4432 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4433 if (!DEBUG_SCREENSHOTS) {
4434 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4435 // native fence fd will not be populated until flush() is done.
4436 getRenderEngine().flush();
4437 }
4438
4439 if (sync != EGL_NO_SYNC_KHR) {
4440 // get the sync fd
4441 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4442 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4443 ALOGW("captureScreen: failed to dup sync khr object");
4444 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004445 }
Dan Stozaabcda352017-06-01 14:37:39 -07004446 eglDestroySyncKHR(mEGLDisplay, sync);
4447 } else {
4448 // fallback path
4449 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004450 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004451 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4452 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4453 EGLint eglErr = eglGetError();
4454 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4455 ALOGW("captureScreen: fence wait timed out");
4456 } else {
4457 ALOGW_IF(eglErr != EGL_SUCCESS,
4458 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004459 }
4460 eglDestroySyncKHR(mEGLDisplay, sync);
4461 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004462 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004463 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004464 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004465 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004466
4467 if (DEBUG_SCREENSHOTS) {
4468 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4469 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4470 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4471 hw, minLayerZ, maxLayerZ);
4472 delete [] pixels;
4473 }
4474
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004475 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004476 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004477
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004478 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004479}
4480
Mathias Agopiand5556842013-09-19 17:08:37 -07004481void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004482 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004483 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004484 for (size_t y=0 ; y<h ; y++) {
4485 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4486 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004487 if (p[x] != 0xFF000000) return;
4488 }
4489 }
4490 ALOGE("*** we just took a black screenshot ***\n"
4491 "requested minz=%d, maxz=%d, layerStack=%d",
4492 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004493
Robert Carr2047fae2016-11-28 14:09:09 -08004494 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004495 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004496 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004497 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4498 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004499 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004500 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4501 layer->isVisible() ? '+' : '-',
4502 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004503 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004504 i++;
4505 });
4506 }
4507 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004508 }
4509}
4510
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004511// ---------------------------------------------------------------------------
4512
Dan Stoza412903f2017-04-27 13:42:17 -07004513void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4514 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004515}
4516
Dan Stoza412903f2017-04-27 13:42:17 -07004517void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4518 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004519}
4520
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004521}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004522
4523
4524#if defined(__gl_h_)
4525#error "don't include gl/gl.h in this file"
4526#endif
4527
4528#if defined(__gl2_h_)
4529#error "don't include gl2/gl2.h in this file"
4530#endif