blob: 38b93b110bcad02acb3c5defbbe982213ff8502f [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.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"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
David Sodmanbc815282017-11-05 18:57:52 -0800157SurfaceFlingerBE::SurfaceFlingerBE()
158 : mHwcServiceName(getHwcServiceName()),
159 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800160 mFrameBuckets(),
161 mTotalTime(0),
162 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800163 mComposerSequenceId(0) {
164}
165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166SurfaceFlinger::SurfaceFlinger()
Lloyd Pique12eb4232018-01-17 11:54:43 -0800167 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700169 mTransactionPending(false),
170 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700172 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700173 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800175 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800177 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800178 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700181 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700182 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700183 mDebugInSwapBuffers(0),
184 mLastSwapBufferTime(0),
185 mDebugInTransaction(0),
186 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700187 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700188 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800189 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700191 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700192 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700193 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800194 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800195 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700196 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800197 mMainThreadId(std::this_thread::get_id()),
198 mCreateBufferQueue(&BufferQueue::createBufferQueue) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800200
201 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
203
204 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
206
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800207 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
David Sodman99974d22017-11-28 12:04:33 -0800229 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285}
286
Dan Stozac7014012014-02-14 15:03:43 -0800287void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800288{
289 // the window manager died on us. prepare its eulogy.
290
Andy McFadden13a082e2012-08-24 10:16:42 -0700291 // restore initial conditions (default device unblank, etc)
292 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800293
294 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700295 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296}
297
Robert Carr1db73f62016-12-21 12:58:51 -0800298static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700299 status_t err = client->initCheck();
300 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800301 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800302 }
Robert Carr1db73f62016-12-21 12:58:51 -0800303 return nullptr;
304}
305
306sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
307 return initClient(new Client(this));
308}
309
310sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
311 const sp<IGraphicBufferProducer>& gbp) {
312 if (authenticateSurfaceTexture(gbp) == false) {
313 return nullptr;
314 }
315 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
316 if (layer == nullptr) {
317 return nullptr;
318 }
319
320 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700323sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
324 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700325{
326 class DisplayToken : public BBinder {
327 sp<SurfaceFlinger> flinger;
328 virtual ~DisplayToken() {
329 // no more references, this display must be terminated
330 Mutex::Autolock _l(flinger->mStateLock);
331 flinger->mCurrentState.displays.removeItem(this);
332 flinger->setTransactionFlags(eDisplayTransactionNeeded);
333 }
334 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700335 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 : flinger(flinger) {
337 }
338 };
339
340 sp<BBinder> token = new DisplayToken(this);
341
342 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700343 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700344 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700346 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700347 return token;
348}
349
Jesse Hall6c913be2013-08-08 12:15:49 -0700350void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
351 Mutex::Autolock _l(mStateLock);
352
353 ssize_t idx = mCurrentState.displays.indexOfKey(display);
354 if (idx < 0) {
355 ALOGW("destroyDisplay: invalid display token");
356 return;
357 }
358
359 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
360 if (!info.isVirtualDisplay()) {
361 ALOGE("destroyDisplay called for non-virtual display");
362 return;
363 }
Irvelffc9efc2016-07-27 15:16:37 -0700364 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700365 mCurrentState.displays.removeItemsAt(idx);
366 setTransactionFlags(eDisplayTransactionNeeded);
367}
368
Mathias Agopiane57f2922012-08-09 16:29:12 -0700369sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700370 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700371 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800372 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700373 }
Jesse Hall692c7232012-11-08 15:41:56 -0800374 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700375}
376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377void SurfaceFlinger::bootFinished()
378{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700379 if (mStartPropertySetThread->join() != NO_ERROR) {
380 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 const nsecs_t now = systemTime();
383 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000384 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700385
386 // wait patiently for the window manager death
387 const String16 name("window");
388 sp<IBinder> window(defaultServiceManager()->getService(name));
389 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700391 }
392
Steven Thomas050b2c82017-03-06 11:45:16 -0800393 if (mVrFlinger) {
394 mVrFlinger->OnBootFinished();
395 }
396
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700397 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 // formerly we would just kill the process, but we now ask it to exit so it
399 // can choose where to stop the animation.
400 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700401
402 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
403 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
404 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700405
Thierry Strudel2924d012017-08-14 15:19:37 -0700406 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700407 readPersistentProperties();
408 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700409 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410}
411
Mathias Agopian3f844832013-08-07 21:24:32 -0700412void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700413 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800414 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700415 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700416 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800417 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
418 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700419 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 return true;
422 }
423 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425}
426
Lloyd Piquee83f9312018-02-01 12:53:17 -0800427class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* name) :
431 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
435 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 mDispSync(dispSync),
437 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mVsyncMutex(),
439 mPhaseOffset(phaseOffset),
440 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700441
Lloyd Piquee83f9312018-02-01 12:53:17 -0800442 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443
Lloyd Piquee83f9312018-02-01 12:53:17 -0800444 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 static_cast<DispSync::Callback*>(this));
449 if (err != NO_ERROR) {
450 ALOGE("error registering vsync callback: %s (%d)",
451 strerror(-err), err);
452 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700453 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 } else {
455 status_t err = mDispSync->removeEventListener(
456 static_cast<DispSync::Callback*>(this));
457 if (err != NO_ERROR) {
458 ALOGE("error unregistering vsync callback: %s (%d)",
459 strerror(-err), err);
460 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700461 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 }
465
Lloyd Piquee83f9312018-02-01 12:53:17 -0800466 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 mCallback = callback;
469 }
470
Lloyd Piquee83f9312018-02-01 12:53:17 -0800471 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 Mutex::Autolock lock(mVsyncMutex);
473
474 // Normalize phaseOffset to [0, period)
475 auto period = mDispSync->getPeriod();
476 phaseOffset %= period;
477 if (phaseOffset < 0) {
478 // If we're here, then phaseOffset is in (-period, 0). After this
479 // operation, it will be in (0, period)
480 phaseOffset += period;
481 }
482 mPhaseOffset = phaseOffset;
483
484 // If we're not enabled, we don't need to mess with the listeners
485 if (!mEnabled) {
486 return;
487 }
488
489 // Remove the listener with the old offset
490 status_t err = mDispSync->removeEventListener(
491 static_cast<DispSync::Callback*>(this));
492 if (err != NO_ERROR) {
493 ALOGE("error unregistering vsync callback: %s (%d)",
494 strerror(-err), err);
495 }
496
497 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499 static_cast<DispSync::Callback*>(this));
500 if (err != NO_ERROR) {
501 ALOGE("error registering vsync callback: %s (%d)",
502 strerror(-err), err);
503 }
504 }
505
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506private:
507 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700510 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 callback = mCallback;
512
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 if (mTraceVsync) {
514 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700515 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700516 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 }
518
Peiyong Lin566a3b42018-01-09 18:22:43 -0800519 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 callback->onVSyncEvent(when);
521 }
522 }
523
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 const char* const mName;
525
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 int mValue;
527
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 const String8 mVsyncOnLabel;
530 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533
534 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800535 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536
537 Mutex mVsyncMutex; // Protects the following
538 nsecs_t mPhaseOffset;
539 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540};
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700543public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800544 InjectVSyncSource() = default;
545 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700546
Lloyd Piquee83f9312018-02-01 12:53:17 -0800547 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700548 std::lock_guard<std::mutex> lock(mCallbackMutex);
549 mCallback = callback;
550 }
551
Lloyd Piquee83f9312018-02-01 12:53:17 -0800552 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700553 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700554 if (mCallback) {
555 mCallback->onVSyncEvent(when);
556 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setVSyncEnabled(bool) override {}
560 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700561
562private:
563 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800564 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700565};
566
Wei Wangf9b05ee2017-07-19 20:59:39 -0700567// Do not call property_set on main thread which will be blocked by init
568// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700570 ALOGI( "SurfaceFlinger's main thread ready to run. "
571 "Initializing graphics H/W...");
572
Thierry Strudel2924d012017-08-14 15:19:37 -0700573 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900574
Steven Thomasb02664d2017-07-26 18:48:28 -0700575 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800578 mEventThreadSource =
579 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
580 true, "app");
581 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
582 "appEventThread");
583 mSfEventThreadSource =
584 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
585 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
586 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
587 "sfEventThread");
Lloyd Piquee83f9312018-02-01 12:53:17 -0800588 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800591 getBE().mRenderEngine =
592 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
593 hasWideColorDisplay
594 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
595 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800596 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700597
598 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
599 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800600 getBE().mHwc.reset(
601 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700602 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800603 // Process any initial hotplug and resulting display changes.
604 processDisplayHotplugEventsLocked();
605 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
606 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800607
Lloyd Piquefcd86612017-12-14 17:15:36 -0800608 // make the default display GLContext current so that we can create textures
609 // when creating Layers (which may happens before we render something)
610 getDefaultDisplayDeviceLocked()->makeCurrent();
611
Steven Thomas050b2c82017-03-06 11:45:16 -0800612 if (useVrFlinger) {
613 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700614 // This callback is called from the vr flinger dispatch thread. We
615 // need to call signalTransaction(), which requires holding
616 // mStateLock when we're not on the main thread. Acquiring
617 // mStateLock from the vr flinger dispatch thread might trigger a
618 // deadlock in surface flinger (see b/66916578), so post a message
619 // to be handled on the main thread instead.
620 sp<LambdaMessage> message = new LambdaMessage([=]() {
621 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
622 mVrFlingerRequestsDisplay = requestDisplay;
623 signalTransaction();
624 });
625 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 };
David Sodman105b7dc2017-11-04 20:28:14 -0700627 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
628 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800629 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 if (!mVrFlinger) {
631 ALOGE("Failed to start vrflinger");
632 }
633 }
634
Lloyd Pique755e3192018-01-31 16:46:15 -0800635 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
636 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
637 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700638
Mathias Agopian92a979a2012-08-02 18:32:23 -0700639 // initialize our drawing state
640 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700641
Andy McFadden13a082e2012-08-24 10:16:42 -0700642 // set initial conditions (e.g. unblank default device)
643 initializeDisplays();
644
David Sodmanbc815282017-11-05 18:57:52 -0800645 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700646
Wei Wangf9b05ee2017-07-19 20:59:39 -0700647 // Inform native graphics APIs whether the present timestamp is supported:
648 if (getHwComposer().hasCapability(
649 HWC2::Capability::PresentFenceIsNotReliable)) {
650 mStartPropertySetThread = new StartPropertySetThread(false);
651 } else {
652 mStartPropertySetThread = new StartPropertySetThread(true);
653 }
654
655 if (mStartPropertySetThread->Start() != NO_ERROR) {
656 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800658
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700660}
661
Romain Guy11d63f42017-07-20 12:47:14 -0700662void SurfaceFlinger::readPersistentProperties() {
663 char value[PROPERTY_VALUE_MAX];
664
665 property_get("persist.sys.sf.color_saturation", value, "1.0");
666 mSaturation = atof(value);
667 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100668
669 property_get("persist.sys.sf.native_mode", value, "0");
670 mForceNativeColorMode = atoi(value) == 1;
671 if (mForceNativeColorMode) {
672 ALOGV("Forcing native color mode");
673 }
Romain Guy11d63f42017-07-20 12:47:14 -0700674}
675
Mathias Agopiana67e4182012-06-19 17:26:12 -0700676void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800677 // Start boot animation service by setting a property mailbox
678 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 if (mStartPropertySetThread->join() != NO_ERROR) {
682 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800683 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700684}
685
Mathias Agopian875d8e12013-06-07 15:35:48 -0700686size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800687 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700688}
689
Mathias Agopian875d8e12013-06-07 15:35:48 -0700690size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800691 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700692}
693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800694// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800695
Jamie Gennis582270d2011-08-17 18:19:00 -0700696bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800697 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800698 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800699 return authenticateSurfaceTextureLocked(bufferProducer);
700}
701
702bool SurfaceFlinger::authenticateSurfaceTextureLocked(
703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800704 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800705 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800706}
707
Brian Anderson6b376712017-04-04 10:51:39 -0700708status_t SurfaceFlinger::getSupportedFrameTimestamps(
709 std::vector<FrameEvent>* outSupported) const {
710 *outSupported = {
711 FrameEvent::REQUESTED_PRESENT,
712 FrameEvent::ACQUIRE,
713 FrameEvent::LATCH,
714 FrameEvent::FIRST_REFRESH_START,
715 FrameEvent::LAST_REFRESH_START,
716 FrameEvent::GPU_COMPOSITION_DONE,
717 FrameEvent::DEQUEUE_READY,
718 FrameEvent::RELEASE,
719 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700720 ConditionalLock _l(mStateLock,
721 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700722 if (!getHwComposer().hasCapability(
723 HWC2::Capability::PresentFenceIsNotReliable)) {
724 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
725 }
726 return NO_ERROR;
727}
728
Dan Stoza7f7da322014-05-02 15:26:25 -0700729status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
730 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800731 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700732 return BAD_VALUE;
733 }
734
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500735 if (!display.get())
736 return NAME_NOT_FOUND;
737
Jesse Hall692c7232012-11-08 15:41:56 -0800738 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700739 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800740 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700741 type = i;
742 break;
743 }
744 }
745
746 if (type < 0) {
747 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700748 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700749
Mathias Agopian8b736f12012-08-13 17:54:26 -0700750 // TODO: Not sure if display density should handled by SF any longer
751 class Density {
752 static int getDensityFromProperty(char const* propName) {
753 char property[PROPERTY_VALUE_MAX];
754 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800755 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 density = atoi(property);
757 }
758 return density;
759 }
760 public:
761 static int getEmuDensity() {
762 return getDensityFromProperty("qemu.sf.lcd_density"); }
763 static int getBuildDensity() {
764 return getDensityFromProperty("ro.sf.lcd_density"); }
765 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700766
Dan Stoza7f7da322014-05-02 15:26:25 -0700767 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700768
Steven Thomas6d8110b2017-08-31 18:24:21 -0700769 ConditionalLock _l(mStateLock,
770 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800771 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700772 DisplayInfo info = DisplayInfo();
773
Dan Stoza9e56aa02015-11-02 13:00:03 -0800774 float xdpi = hwConfig->getDpiX();
775 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700776
777 if (type == DisplayDevice::DISPLAY_PRIMARY) {
778 // The density of the device is provided by a build property
779 float density = Density::getBuildDensity() / 160.0f;
780 if (density == 0) {
781 // the build doesn't provide a density -- this is wrong!
782 // use xdpi instead
783 ALOGE("ro.sf.lcd_density must be defined as a build property");
784 density = xdpi / 160.0f;
785 }
786 if (Density::getEmuDensity()) {
787 // if "qemu.sf.lcd_density" is specified, it overrides everything
788 xdpi = ydpi = density = Density::getEmuDensity();
789 density /= 160.0f;
790 }
791 info.density = density;
792
793 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700794 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800795 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 } else {
797 // TODO: where should this value come from?
798 static const int TV_DENSITY = 213;
799 info.density = TV_DENSITY / 160.0f;
800 info.orientation = 0;
801 }
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 info.w = hwConfig->getWidth();
804 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 info.xdpi = xdpi;
806 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900808 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809
Andy McFadden91b2ca82014-06-13 14:04:23 -0700810 // This is how far in advance a buffer must be queued for
811 // presentation at a given time. If you want a buffer to appear
812 // on the screen at time N, you must submit the buffer before
813 // (N - presentationDeadline).
814 //
815 // Normally it's one full refresh period (to give SF a chance to
816 // latch the buffer), but this can be reduced by configuring a
817 // DispSync offset. Any additional delays introduced by the hardware
818 // composer or panel must be accounted for here.
819 //
820 // We add an additional 1ms to allow for processing time and
821 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800823 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700824
825 // All non-virtual displays are currently considered secure.
826 info.secure = true;
827
Michael Wright28f24d02016-07-12 13:30:53 -0700828 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 }
830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 return NO_ERROR;
832}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700833
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800834status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700835 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800836 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700837 return BAD_VALUE;
838 }
839
840 // FIXME for now we always return stats for the primary display
841 memset(stats, 0, sizeof(*stats));
842 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
843 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
844 return NO_ERROR;
845}
846
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700847int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800848 if (display == nullptr) {
849 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800850 return BAD_VALUE;
851 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700852
853 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800854 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700855 return device->getActiveConfig();
856 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700857
Dan Stoza24a42e92015-03-09 10:04:11 -0700858 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700859}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700860
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700861void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
862 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
863 this);
864 int32_t type = hw->getDisplayType();
865 int currentMode = hw->getActiveConfig();
866
867 if (mode == currentMode) {
868 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
869 return;
870 }
871
872 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
873 ALOGW("Trying to set config for virtual display");
874 return;
875 }
876
877 hw->setActiveConfig(mode);
878 getHwComposer().setActiveConfig(type, mode);
879}
880
881status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
882 class MessageSetActiveConfig: public MessageBase {
883 SurfaceFlinger& mFlinger;
884 sp<IBinder> mDisplay;
885 int mMode;
886 public:
887 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
888 int mode) :
889 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
890 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700891 Vector<DisplayInfo> configs;
892 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700893 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700894 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700895 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700896 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700897 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700898 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800899 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700900 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700902 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
903 ALOGW("Attempt to set active config = %d for virtual display",
904 mMode);
905 } else {
906 mFlinger.setActiveConfigInternal(hw, mMode);
907 }
908 return true;
909 }
910 };
911 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
912 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700913 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700914}
Michael Wright28f24d02016-07-12 13:30:53 -0700915status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
916 Vector<android_color_mode_t>* outColorModes) {
917 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
918 return BAD_VALUE;
919 }
920
921 if (!display.get()) {
922 return NAME_NOT_FOUND;
923 }
924
925 int32_t type = NAME_NOT_FOUND;
926 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
927 if (display == mBuiltinDisplays[i]) {
928 type = i;
929 break;
930 }
931 }
932
933 if (type < 0) {
934 return type;
935 }
936
Steven Thomas6d8110b2017-08-31 18:24:21 -0700937 std::vector<android_color_mode_t> modes;
938 {
939 ConditionalLock _l(mStateLock,
940 std::this_thread::get_id() != mMainThreadId);
941 modes = getHwComposer().getColorModes(type);
942 }
Michael Wright28f24d02016-07-12 13:30:53 -0700943 outColorModes->clear();
944 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
945
946 return NO_ERROR;
947}
948
949android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700950 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if (device != nullptr) {
952 return device->getActiveColorMode();
953 }
954 return static_cast<android_color_mode_t>(BAD_VALUE);
955}
956
957void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
958 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700959 int32_t type = hw->getDisplayType();
960 android_color_mode_t currentMode = hw->getActiveColorMode();
961
962 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700963 return;
964 }
965
966 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
967 ALOGW("Trying to set config for virtual display");
968 return;
969 }
970
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600971 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
972 hw->getDisplayType());
973
Michael Wright28f24d02016-07-12 13:30:53 -0700974 hw->setActiveColorMode(mode);
975 getHwComposer().setActiveColorMode(type, mode);
976}
977
978
979status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
980 android_color_mode_t colorMode) {
981 class MessageSetActiveColorMode: public MessageBase {
982 SurfaceFlinger& mFlinger;
983 sp<IBinder> mDisplay;
984 android_color_mode_t mMode;
985 public:
986 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
987 android_color_mode_t mode) :
988 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
989 virtual bool handler() {
990 Vector<android_color_mode_t> modes;
991 mFlinger.getDisplayColorModes(mDisplay, &modes);
992 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
993 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600994 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
995 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700996 return true;
997 }
998 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
999 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001000 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1001 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001002 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGW("Attempt to set active color mode %s %d for virtual display",
1004 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001005 } else {
1006 mFlinger.setActiveColorModeInternal(hw, mMode);
1007 }
1008 return true;
1009 }
1010 };
1011 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1012 postMessageSync(msg);
1013 return NO_ERROR;
1014}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001015
Svetoslavd85084b2014-03-20 10:28:31 -07001016status_t SurfaceFlinger::clearAnimationFrameStats() {
1017 Mutex::Autolock _l(mStateLock);
1018 mAnimFrameTracker.clearStats();
1019 return NO_ERROR;
1020}
1021
1022status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.getStats(outStats);
1025 return NO_ERROR;
1026}
1027
Dan Stozac4f471e2016-03-24 09:31:08 -07001028status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1029 HdrCapabilities* outCapabilities) const {
1030 Mutex::Autolock _l(mStateLock);
1031
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001032 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001033 if (displayDevice == nullptr) {
1034 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1035 return BAD_VALUE;
1036 }
1037
1038 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001039 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001040 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001041 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1042 // insert HDR10 as we will force client composition for HDR10
1043 // layers
1044 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1045 types.push_back(HAL_HDR_HDR10);
1046
1047 *outCapabilities = HdrCapabilities(types,
1048 capabilities->getDesiredMaxLuminance(),
1049 capabilities->getDesiredMaxAverageLuminance(),
1050 capabilities->getDesiredMinLuminance());
1051 } else {
1052 *outCapabilities = std::move(*capabilities);
1053 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001054 } else {
1055 return BAD_VALUE;
1056 }
1057
1058 return NO_ERROR;
1059}
1060
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001062 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1063 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001064
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 if (mInjectVSyncs == enable) {
1066 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068
1069 if (enable) {
1070 ALOGV("VSync Injections enabled");
1071 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001072 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001073 mInjectorEventThread =
1074 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1075 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001077 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078 } else {
1079 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001080 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 }
1082
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001083 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 });
1085 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001086 return NO_ERROR;
1087}
1088
1089status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001090 Mutex::Autolock _l(mStateLock);
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 if (!mInjectVSyncs) {
1093 ALOGE("VSync Injections not enabled");
1094 return BAD_VALUE;
1095 }
1096 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1097 ALOGV("Injecting VSync inside SurfaceFlinger");
1098 mVSyncInjector->onInjectSyncEvent(when);
1099 }
1100 return NO_ERROR;
1101}
1102
Lloyd Pique755e3192018-01-31 16:46:15 -08001103status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1104 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001105 IPCThreadState* ipc = IPCThreadState::self();
1106 const int pid = ipc->getCallingPid();
1107 const int uid = ipc->getCallingUid();
1108 if ((uid != AID_SHELL) &&
1109 !PermissionCache::checkPermission(sDump, pid, uid)) {
1110 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1111 return PERMISSION_DENIED;
1112 }
1113
1114 // Try to acquire a lock for 1s, fail gracefully
1115 const status_t err = mStateLock.timedLock(s2ns(1));
1116 const bool locked = (err == NO_ERROR);
1117 if (!locked) {
1118 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1119 return TIMED_OUT;
1120 }
1121
1122 outLayers->clear();
1123 mCurrentState.traverseInZOrder([&](Layer* layer) {
1124 outLayers->push_back(layer->getLayerDebugInfo());
1125 });
1126
1127 mStateLock.unlock();
1128 return NO_ERROR;
1129}
1130
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001131// ----------------------------------------------------------------------------
1132
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001133sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1134 ISurfaceComposer::VsyncSource vsyncSource) {
1135 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1136 return mSFEventThread->createEventConnection();
1137 } else {
1138 return mEventThread->createEventConnection();
1139 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001140}
1141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143
1144void SurfaceFlinger::waitForEvent() {
1145 mEventQueue.waitMessage();
1146}
1147
1148void SurfaceFlinger::signalTransaction() {
1149 mEventQueue.invalidate();
1150}
1151
1152void SurfaceFlinger::signalLayerUpdate() {
1153 mEventQueue.invalidate();
1154}
1155
1156void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001157 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158 mEventQueue.refresh();
1159}
1160
1161status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001162 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 return mEventQueue.postMessage(msg, reltime);
1164}
1165
1166status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001167 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001168 status_t res = mEventQueue.postMessage(msg, reltime);
1169 if (res == NO_ERROR) {
1170 msg->wait();
1171 }
1172 return res;
1173}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001175void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001176 do {
1177 waitForEvent();
1178 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179}
1180
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181void SurfaceFlinger::enableHardwareVsync() {
1182 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001183 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001185 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1186 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001188 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189}
1190
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 Mutex::Autolock _l(mHWVsyncLock);
1193
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 if (makeAvailable) {
1195 mHWVsyncAvailable = true;
1196 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001197 // Hardware vsync is not currently available, so abort the resync
1198 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199 return;
1200 }
1201
David Sodman105b7dc2017-11-04 20:28:14 -07001202 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204
1205 mPrimaryDispSync.reset();
1206 mPrimaryDispSync.setPeriod(period);
1207
1208 if (!mPrimaryHWVsyncEnabled) {
1209 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1211 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryHWVsyncEnabled = true;
1213 }
1214}
1215
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 Mutex::Autolock _l(mHWVsyncLock);
1218 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1220 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryDispSync.endResync();
1222 mPrimaryHWVsyncEnabled = false;
1223 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 if (makeUnavailable) {
1225 mHWVsyncAvailable = false;
1226 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227}
1228
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229void SurfaceFlinger::resyncWithRateLimit() {
1230 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001231
1232 // No explicit locking is needed here since EventThread holds a lock while calling this method
1233 static nsecs_t sLastResyncAttempted = 0;
1234 const nsecs_t now = systemTime();
1235 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237 }
Dan Stoza57164302017-05-08 14:03:54 -07001238 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239}
1240
Steven Thomasb02664d2017-07-26 18:48:28 -07001241void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1242 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001243 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001245 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 return;
1247 }
1248
1249 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001250 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 return;
1252 }
1253
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 { // Scope for the lock
1257 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001258 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001261 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001262
1263 if (needsHwVsync) {
1264 enableHardwareVsync();
1265 } else {
1266 disableHardwareVsync(false);
1267 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001268}
1269
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001270void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001271 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1272 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001273}
1274
Lloyd Pique715a2c12017-12-14 17:18:08 -08001275void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1276 HWC2::Connection connection) {
1277 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1278 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001279
Lloyd Piqueba04e622017-12-14 17:11:26 -08001280 // Ignore events that do not have the right sequenceId.
1281 if (sequenceId != getBE().mComposerSequenceId) {
1282 return;
1283 }
1284
Steven Thomasb02664d2017-07-26 18:48:28 -07001285 // Only lock if we're not on the main thread. This function is normally
1286 // called on a hwbinder thread, but for the primary display it's called on
1287 // the main thread with the state lock already held, so don't attempt to
1288 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001289 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001290
Lloyd Pique715a2c12017-12-14 17:18:08 -08001291 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001292
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001293 if (std::this_thread::get_id() == mMainThreadId) {
1294 // Process all pending hot plug events immediately if we are on the main thread.
1295 processDisplayHotplugEventsLocked();
1296 }
1297
Lloyd Piqueba04e622017-12-14 17:11:26 -08001298 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001299}
1300
Steven Thomasb02664d2017-07-26 18:48:28 -07001301void SurfaceFlinger::onRefreshReceived(int sequenceId,
1302 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001303 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001304 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001305 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001306 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001307 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001308}
1309
Dan Stoza9e56aa02015-11-02 13:00:03 -08001310void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001312 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 getHwComposer().setVsyncEnabled(disp,
1314 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001315}
1316
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001318void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001319 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320 // Clear the drawing state so that the logic inside of
1321 // handleTransactionLocked will fire. It will determine the delta between
1322 // mCurrentState and mDrawingState and re-apply all changes when we make the
1323 // transition.
1324 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001325 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326 mDisplays.clear();
1327}
1328
Steven Thomas050b2c82017-03-06 11:45:16 -08001329void SurfaceFlinger::updateVrFlinger() {
1330 if (!mVrFlinger)
1331 return;
1332 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001333 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001334 return;
1335 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336
David Sodman105b7dc2017-11-04 20:28:14 -07001337 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 ALOGE("Vr flinger is only supported for remote hardware composer"
1339 " service connections. Ignoring request to transition to vr"
1340 " flinger.");
1341 mVrFlingerRequestsDisplay = false;
1342 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001343 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 int currentDisplayPowerMode = getDisplayDeviceLocked(
1348 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349
Steven Thomasb02664d2017-07-26 18:48:28 -07001350 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001355 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001356 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1357 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001358 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359
David Sodman105b7dc2017-11-04 20:28:14 -07001360 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1361 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001362
1363 if (vrFlingerRequestsDisplay) {
1364 mVrFlinger->GrantDisplayOwnership();
1365 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368
1369 mVisibleRegionsDirty = true;
1370 invalidateHwcGeometry();
1371
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001372 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1374 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1375 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001376
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001378 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 const nsecs_t period = activeConfig->getVsyncPeriod();
1380 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 // Use phase of 0 since phase is not known.
1383 // Use latency of 0, which will snap to the ideal latency.
1384 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 android_atomic_or(1, &mRepaintEverything);
1387 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388}
1389
Mathias Agopian4fec8732012-06-29 14:12:52 -07001390void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001391 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001392 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001393 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001394 bool frameMissed = !mHadClientComposition &&
1395 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396 (mPreviousPresentFence->getSignalTime() ==
1397 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001398 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001399 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001400 signalLayerUpdate();
1401 break;
1402 }
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404 // Now that we're going to make it to the handleMessageTransaction()
1405 // call below it's safe to call updateVrFlinger(), which will
1406 // potentially trigger a display handoff.
1407 updateVrFlinger();
1408
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 bool refreshNeeded = handleMessageTransaction();
1410 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001411 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001413 // Signal a refresh if a transaction modified the window state,
1414 // a new buffer was latched, or if HWC has requested a full
1415 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 signalRefresh();
1417 }
1418 break;
1419 }
1420 case MessageQueue::REFRESH: {
1421 handleMessageRefresh();
1422 break;
1423 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424 }
1425}
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001428 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001430 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001431 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434}
1435
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001439}
1440
1441void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001443
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001444 mRefreshPending = false;
1445
Pablo Ceballos40845df2016-01-25 17:41:15 -08001446 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001447
Brian Andersond6927fb2016-07-23 23:37:30 -07001448 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001449 rebuildLayerStacks();
1450 setUpHWComposer();
1451 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001452 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001453 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001454 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001455
David Sodman105b7dc2017-11-04 20:28:14 -07001456 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001457
1458 mHadClientComposition = false;
1459 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1460 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1461 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001462 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001463 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001464
Dan Stoza9e56aa02015-11-02 13:00:03 -08001465 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468void SurfaceFlinger::doDebugFlashRegions()
1469{
1470 // is debugging enabled
1471 if (CC_LIKELY(!mDebugRegion))
1472 return;
1473
1474 const bool repaintEverything = mRepaintEverything;
1475 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1476 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001477 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001478 // transform the dirty region into this screen's coordinate space
1479 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1480 if (!dirtyRegion.isEmpty()) {
1481 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001482 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483
1484 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001486 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001487 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1488
Mathias Agopianda27af92012-09-13 18:17:13 -07001489 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490 }
1491 }
1492 }
1493
1494 postFramebuffer();
1495
1496 if (mDebugRegion > 1) {
1497 usleep(mDebugRegion * 1000);
1498 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001499
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001501 auto& displayDevice = mDisplays[displayId];
1502 if (!displayDevice->isDisplayOn()) {
1503 continue;
1504 }
1505
David Sodman105b7dc2017-11-04 20:28:14 -07001506 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1507 ALOGE_IF(result != NO_ERROR,
1508 "prepareFrame for display %zd failed:"
1509 " %d (%s)",
1510 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001511 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512}
1513
Adrian Roos1e1a1282017-11-01 19:05:31 +01001514void SurfaceFlinger::doTracing(const char* where) {
1515 ATRACE_CALL();
1516 ATRACE_NAME(where);
1517 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001518 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001519 }
1520}
1521
Brian Andersond6927fb2016-07-23 23:37:30 -07001522void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001524 ATRACE_CALL();
1525 ALOGV("preComposition");
1526
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001528 mDrawingState.traverseInZOrder([&](Layer* layer) {
1529 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530 needExtraInvalidate = true;
1531 }
Robert Carr2047fae2016-11-28 14:09:09 -08001532 });
1533
Mathias Agopiancd60f992012-08-16 16:28:27 -07001534 if (needExtraInvalidate) {
1535 signalLayerUpdate();
1536 }
1537}
1538
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539void SurfaceFlinger::updateCompositorTiming(
1540 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1541 std::shared_ptr<FenceTime>& presentFenceTime) {
1542 // Update queue of past composite+present times and determine the
1543 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001544 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001545 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001546 while (!getBE().mCompositePresentTimes.empty()) {
1547 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001548 // Cached values should have been updated before calling this method,
1549 // which helps avoid duplicate syscalls.
1550 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1551 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1552 break;
1553 }
1554 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001555 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001556 }
1557
1558 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001559 while (getBE().mCompositePresentTimes.size() > 16) {
1560 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561 }
1562
Brian Andersond0010582017-03-07 13:20:31 -08001563 setCompositorTimingSnapped(
1564 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1565}
1566
1567void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1568 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001569 // Integer division and modulo round toward 0 not -inf, so we need to
1570 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001571 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001572 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1573 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1574
Brian Andersond0010582017-03-07 13:20:31 -08001575 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1576 if (idealLatency <= 0) {
1577 idealLatency = vsyncInterval;
1578 }
1579
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001580 // Snap the latency to a value that removes scheduling jitter from the
1581 // composition and present times, which often have >1ms of jitter.
1582 // Reducing jitter is important if an app attempts to extrapolate
1583 // something (such as user input) to an accurate diasplay time.
1584 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1585 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001586 nsecs_t bias = vsyncInterval / 2;
1587 int64_t extraVsyncs =
1588 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1589 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1590 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001591
David Sodman99974d22017-11-28 12:04:33 -08001592 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1593 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1594 getBE().mCompositorTiming.interval = vsyncInterval;
1595 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001596}
1597
1598void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001600 ATRACE_CALL();
1601 ALOGV("postComposition");
1602
Brian Anderson3546a3f2016-07-14 11:51:14 -07001603 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001604 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001605 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001606 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001607 }
1608
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609 // |mStateLock| not needed as we are on the main thread
1610 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001611
David Sodman73beded2017-11-15 11:56:06 -08001612 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001613 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001614 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001615 glCompositionDoneFenceTime =
1616 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001617 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001618 } else {
1619 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1620 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001621
David Sodman73beded2017-11-15 11:56:06 -08001622 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001623 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001624 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001625 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001626
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1628 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1629
1630 // We use the refreshStartTime which might be sampled a little later than
1631 // when we started doing work for this frame, but that should be okay
1632 // since updateCompositorTiming has snapping logic.
1633 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001634 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001635 CompositorTiming compositorTiming;
1636 {
David Sodman99974d22017-11-28 12:04:33 -08001637 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1638 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001639 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640
Robert Carr2047fae2016-11-28 14:09:09 -08001641 mDrawingState.traverseInZOrder([&](Layer* layer) {
1642 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001643 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001644 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001645 recordBufferingStats(layer->getName().string(),
1646 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001647 }
Robert Carr2047fae2016-11-28 14:09:09 -08001648 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001649
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001650 if (presentFenceTime->isValid()) {
1651 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001652 enableHardwareVsync();
1653 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001654 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001655 }
1656 }
1657
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001658 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001659 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001660 enableHardwareVsync();
1661 }
1662 }
1663
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001664 if (mAnimCompositionPending) {
1665 mAnimCompositionPending = false;
1666
Brian Anderson4e606e32017-03-16 15:34:57 -07001667 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001669 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001670 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001671 // The HWC doesn't support present fences, so use the refresh
1672 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001673 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001674 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001675 mAnimFrameTracker.setActualPresentTime(presentTime);
1676 }
1677 mAnimFrameTracker.advanceFrame();
1678 }
Dan Stozab90cf072015-03-05 11:05:59 -08001679
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001680 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1681 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001682 return;
1683 }
1684
1685 nsecs_t currentTime = systemTime();
1686 if (mHasPoweredOff) {
1687 mHasPoweredOff = false;
1688 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001689 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001691 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1692 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001693 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001694 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001695 }
David Sodman4a36e932017-11-07 14:29:47 -08001696 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001697 }
David Sodman4a36e932017-11-07 14:29:47 -08001698 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699}
1700
1701void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001702 ATRACE_CALL();
1703 ALOGV("rebuildLayerStacks");
1704
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001706 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001707 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001708 mVisibleRegionsDirty = false;
1709 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001710
Jeff Sharkey76488112017-02-27 14:15:18 -07001711 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1712 Region opaqueRegion;
1713 Region dirtyRegion;
1714 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001715 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001716 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1717 const Transform& tr(displayDevice->getTransform());
1718 const Rect bounds(displayDevice->getBounds());
1719 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001720 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001721
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001723 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001724 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1725 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001726 Region drawRegion(tr.transform(
1727 layer->visibleNonTransparentRegion));
1728 drawRegion.andSelf(bounds);
1729 if (!drawRegion.isEmpty()) {
1730 layersSortedByZ.add(layer);
1731 } else {
1732 // Clear out the HWC layer if this layer was
1733 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001734 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001735 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001736 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001737 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001738 // WM changes displayDevice->layerStack upon sleep/awake.
1739 // Here we make sure we delete the HWC layers even if
1740 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001741 hwcLayerDestroyed = layer->destroyHwcLayer(
1742 displayDevice->getHwcDisplayId());
1743 }
1744
1745 // If a layer is not going to get a release fence because
1746 // it is invisible, but it is also going to release its
1747 // old buffer, add it to the list of layers needing
1748 // fences.
1749 if (hwcLayerDestroyed) {
1750 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1751 mLayersWithQueuedFrames.cend(), layer);
1752 if (found != mLayersWithQueuedFrames.cend()) {
1753 layersNeedingFences.add(layer);
1754 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001755 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001756 });
1757 }
1758 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001759 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 displayDevice->undefinedRegion.set(bounds);
1761 displayDevice->undefinedRegion.subtractSelf(
1762 tr.transform(opaqueRegion));
1763 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001764 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001765 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001766}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001767
Romain Guy0147a172017-06-01 13:53:56 -07001768mat4 SurfaceFlinger::computeSaturationMatrix() const {
1769 if (mSaturation == 1.0f) {
1770 return mat4();
1771 }
1772
1773 // Rec.709 luma coefficients
1774 float3 luminance{0.213f, 0.715f, 0.072f};
1775 luminance *= 1.0f - mSaturation;
1776 return mat4(
1777 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1778 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1779 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1780 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1781 );
1782}
1783
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001784// pickColorMode translates a given dataspace into the best available color mode.
1785// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001786android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001787 if (mForceNativeColorMode) {
1788 return HAL_COLOR_MODE_NATIVE;
1789 }
1790
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001791 switch (dataSpace) {
1792 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1793 // system expects.
1794 case HAL_DATASPACE_UNKNOWN:
1795 case HAL_DATASPACE_SRGB:
1796 case HAL_DATASPACE_V0_SRGB:
1797 return HAL_COLOR_MODE_SRGB;
1798 break;
1799
1800 case HAL_DATASPACE_DISPLAY_P3:
1801 return HAL_COLOR_MODE_DISPLAY_P3;
1802 break;
1803
1804 default:
1805 // TODO (courtneygo): Do we want to assert an error here?
1806 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1807 dataSpace);
1808 return HAL_COLOR_MODE_SRGB;
1809 break;
1810 }
1811}
1812
Romain Guy0147a172017-06-01 13:53:56 -07001813android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001814 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001815 // Only support sRGB and Display-P3 right now.
1816 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1817 return HAL_DATASPACE_DISPLAY_P3;
1818 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001819 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1820 return HAL_DATASPACE_DISPLAY_P3;
1821 }
1822 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1823 return HAL_DATASPACE_DISPLAY_P3;
1824 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001825 if (!hasHdr) {
1826 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1827 return HAL_DATASPACE_DISPLAY_P3;
1828 }
1829 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1830 return HAL_DATASPACE_DISPLAY_P3;
1831 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001832 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001833
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001834 return HAL_DATASPACE_V0_SRGB;
1835}
1836
Mathias Agopiancd60f992012-08-16 16:28:27 -07001837void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001838 ATRACE_CALL();
1839 ALOGV("setUpHWComposer");
1840
Jesse Hall028dc8f2013-08-20 16:35:32 -07001841 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001842 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1843 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1844 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1845
1846 // If nothing has changed (!dirty), don't recompose.
1847 // If something changed, but we don't currently have any visible layers,
1848 // and didn't when we last did a composition, then skip it this time.
1849 // The second rule does two things:
1850 // - When all layers are removed from a display, we'll emit one black
1851 // frame, then nothing more until we get new layers.
1852 // - When a display is created with a private layer stack, we won't
1853 // emit any black frames until a layer is added to the layer stack.
1854 bool mustRecompose = dirty && !(empty && wasEmpty);
1855
1856 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1857 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1858 mustRecompose ? "doing" : "skipping",
1859 dirty ? "+" : "-",
1860 empty ? "+" : "-",
1861 wasEmpty ? "+" : "-");
1862
Dan Stoza71433162014-02-04 16:22:36 -08001863 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001864
1865 if (mustRecompose) {
1866 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1867 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001868 }
1869
Dan Stoza9e56aa02015-11-02 13:00:03 -08001870 // build the h/w work list
1871 if (CC_UNLIKELY(mGeometryInvalid)) {
1872 mGeometryInvalid = false;
1873 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1874 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1875 const auto hwcId = displayDevice->getHwcDisplayId();
1876 if (hwcId >= 0) {
1877 const Vector<sp<Layer>>& currentLayers(
1878 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001879 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001880 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001881 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001882 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001885 }
1886 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001887
Robert Carrae060832016-11-28 10:51:00 -08001888 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001889 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001891 }
1892 }
1893 }
1894 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 }
Riley Andrews03414a12014-07-01 14:22:59 -07001896
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001897
Romain Guy0147a172017-06-01 13:53:56 -07001898 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001899
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 // Set the per-frame data
1901 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1902 auto& displayDevice = mDisplays[displayId];
1903 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001904
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 if (hwcId < 0) {
1906 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001907 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001908 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001909 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001910 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1911 "display %zd: %d", displayId, result);
1912 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001914 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1915 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001916 !displayDevice->getHdrSupport()) {
1917 layer->forceClientComposition(hwcId);
1918 }
1919
chaviwc9232ed2017-11-14 15:31:15 -08001920 if (layer->getForceClientComposition(hwcId)) {
1921 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1922 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1923 continue;
1924 }
1925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 layer->setPerFrameData(displayDevice);
1927 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001928
1929 if (hasWideColorDisplay) {
1930 android_color_mode newColorMode;
1931 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1932
1933 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001934 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1935 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001936 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1937 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1938 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1939 }
1940 newColorMode = pickColorMode(newDataSpace);
1941
Thierry Strudel2924d012017-08-14 15:19:37 -07001942 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001943 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 }
1945
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001946 mPreviousColorMatrix = colorMatrix;
1947
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001949 auto& displayDevice = mDisplays[displayId];
1950 if (!displayDevice->isDisplayOn()) {
1951 continue;
1952 }
1953
David Sodman105b7dc2017-11-04 20:28:14 -07001954 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1956 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001957 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001959
Mathias Agopiancd60f992012-08-16 16:28:27 -07001960void SurfaceFlinger::doComposition() {
1961 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 ALOGV("doComposition");
1963
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001964 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001965 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001966 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001967 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 // transform the dirty region into this screen's coordinate space
1969 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001970
1971 // repaint the framebuffer (if needed)
1972 doDisplayComposition(hw, dirtyRegion);
1973
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001975 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001976 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001977 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001978 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001979}
1980
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981void SurfaceFlinger::postFramebuffer()
1982{
Mathias Agopian841cde52012-03-01 15:44:37 -08001983 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001985
Mathias Agopiana44b0412011-10-16 18:46:35 -07001986 const nsecs_t now = systemTime();
1987 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001988
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1990 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001991 if (!displayDevice->isDisplayOn()) {
1992 continue;
1993 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 const auto hwcId = displayDevice->getHwcDisplayId();
1995 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001996 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001997 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001998 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001999 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002001 // The layer buffer from the previous frame (if any) is released
2002 // by HWC only when the release fence from this frame (if any) is
2003 // signaled. Always get the release fence from HWC first.
2004 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002005 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002006
2007 // If the layer was client composited in the previous frame, we
2008 // need to merge with the previous client target acquire fence.
2009 // Since we do not track that, always merge with the current
2010 // client target acquire fence when it is available, even though
2011 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002013 releaseFence = Fence::merge("LayerRelease", releaseFence,
2014 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002015 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002016
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 layer->onLayerDisplayed(releaseFence);
2018 }
Chia-I Wu83806892017-11-16 10:50:20 -08002019
2020 // We've got a list of layers needing fences, that are disjoint with
2021 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2022 // supply them with the present fence.
2023 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002024 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002025 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2026 layer->onLayerDisplayed(presentFence);
2027 }
2028 }
2029
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002031 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002032 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002033 }
2034
Mathias Agopiana44b0412011-10-16 18:46:35 -07002035 mLastSwapBufferTime = systemTime() - now;
2036 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002038 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002039 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2040 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2041 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2042 logFrameStats();
2043 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002044 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002045}
2046
Mathias Agopian87baae12012-07-31 12:38:26 -07002047void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002048{
Mathias Agopian841cde52012-03-01 15:44:37 -08002049 ATRACE_CALL();
2050
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002051 // here we keep a copy of the drawing state (that is the state that's
2052 // going to be overwritten by handleTransactionLocked()) outside of
2053 // mStateLock so that the side-effects of the State assignment
2054 // don't happen with mStateLock held (which can cause deadlocks).
2055 State drawingState(mDrawingState);
2056
Mathias Agopianca4d3602011-05-19 15:38:14 -07002057 Mutex::Autolock _l(mStateLock);
2058 const nsecs_t now = systemTime();
2059 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060
Mathias Agopianca4d3602011-05-19 15:38:14 -07002061 // Here we're guaranteed that some transaction flags are set
2062 // so we can call handleTransactionLocked() unconditionally.
2063 // We call getTransactionFlags(), which will also clear the flags,
2064 // with mStateLock held to guarantee that mCurrentState won't change
2065 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002066
Mathias Agopiane57f2922012-08-09 16:29:12 -07002067 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002068 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002069
Mathias Agopianca4d3602011-05-19 15:38:14 -07002070 mLastTransactionTime = systemTime() - now;
2071 mDebugInTransaction = 0;
2072 invalidateHwcGeometry();
2073 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002074}
2075
Lloyd Pique715a2c12017-12-14 17:18:08 -08002076DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2077 HWC2::Connection connection) const {
2078 // Figure out whether the event is for the primary display or an
2079 // external display by matching the Hwc display id against one for a
2080 // connected display. If we did not find a match, we then check what
2081 // displays are not already connected to determine the type. If we don't
2082 // have a connected primary display, we assume the new display is meant to
2083 // be the primary display, and then if we don't have an external display,
2084 // we assume it is that.
2085 const auto primaryDisplayId =
2086 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2087 const auto externalDisplayId =
2088 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2089 if (primaryDisplayId && primaryDisplayId == display) {
2090 return DisplayDevice::DISPLAY_PRIMARY;
2091 } else if (externalDisplayId && externalDisplayId == display) {
2092 return DisplayDevice::DISPLAY_EXTERNAL;
2093 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2094 return DisplayDevice::DISPLAY_PRIMARY;
2095 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2096 return DisplayDevice::DISPLAY_EXTERNAL;
2097 }
2098
2099 return DisplayDevice::DISPLAY_ID_INVALID;
2100}
2101
Lloyd Piqueba04e622017-12-14 17:11:26 -08002102void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2103 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002104 auto displayType = determineDisplayType(event.display, event.connection);
2105 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2106 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2107 continue;
2108 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002109
2110 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2111 ALOGE("External displays are not supported by the vr hardware composer.");
2112 continue;
2113 }
2114
Lloyd Pique715a2c12017-12-14 17:18:08 -08002115 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002116
2117 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002118 ALOGV("Creating built in display %d", displayType);
2119 ALOGW_IF(mBuiltinDisplays[displayType],
2120 "Overwriting display token for display type %d", displayType);
2121 mBuiltinDisplays[displayType] = new BBinder();
2122 // All non-virtual displays are currently considered secure.
2123 DisplayDeviceState info(displayType, true);
2124 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2125 "Built-in Screen" : "External Screen";
2126 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2127 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002128 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002129 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002130
Lloyd Piquefcd86612017-12-14 17:15:36 -08002131 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2132 if (idx >= 0) {
2133 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2134 mInterceptor.saveDisplayDeletion(info.displayId);
2135 mCurrentState.displays.removeItemsAt(idx);
2136 }
2137 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002138 }
2139
2140 processDisplayChangesLocked();
2141 }
2142
2143 mPendingHotplugEvents.clear();
2144}
2145
Lloyd Pique347200f2017-12-14 17:00:15 -08002146void SurfaceFlinger::processDisplayChangesLocked() {
2147 // here we take advantage of Vector's copy-on-write semantics to
2148 // improve performance by skipping the transaction entirely when
2149 // know that the lists are identical
2150 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2151 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2152 if (!curr.isIdenticalTo(draw)) {
2153 mVisibleRegionsDirty = true;
2154 const size_t cc = curr.size();
2155 size_t dc = draw.size();
2156
2157 // find the displays that were removed
2158 // (ie: in drawing state but not in current state)
2159 // also handle displays that changed
2160 // (ie: displays that are in both lists)
2161 for (size_t i = 0; i < dc;) {
2162 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2163 if (j < 0) {
2164 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002165 // Call makeCurrent() on the primary display so we can
2166 // be sure that nothing associated with this display
2167 // is current.
2168 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2169 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2170 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2171 if (hw != nullptr) hw->disconnect(getHwComposer());
2172 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2173 mEventThread->onHotplugReceived(draw[i].type, false);
2174 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002175 } else {
2176 // this display is in both lists. see if something changed.
2177 const DisplayDeviceState& state(curr[j]);
2178 const wp<IBinder>& display(curr.keyAt(j));
2179 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2180 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2181 if (state_binder != draw_binder) {
2182 // changing the surface is like destroying and
2183 // recreating the DisplayDevice, so we just remove it
2184 // from the drawing state, so that it get re-added
2185 // below.
2186 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2187 if (hw != nullptr) hw->disconnect(getHwComposer());
2188 mDisplays.removeItem(display);
2189 mDrawingState.displays.removeItemsAt(i);
2190 dc--;
2191 // at this point we must loop to the next item
2192 continue;
2193 }
2194
2195 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2196 if (disp != nullptr) {
2197 if (state.layerStack != draw[i].layerStack) {
2198 disp->setLayerStack(state.layerStack);
2199 }
2200 if ((state.orientation != draw[i].orientation) ||
2201 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2202 disp->setProjection(state.orientation, state.viewport, state.frame);
2203 }
2204 if (state.width != draw[i].width || state.height != draw[i].height) {
2205 disp->setDisplaySize(state.width, state.height);
2206 }
2207 }
2208 }
2209 ++i;
2210 }
2211
2212 // find displays that were added
2213 // (ie: in current state but not in drawing state)
2214 for (size_t i = 0; i < cc; i++) {
2215 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2216 const DisplayDeviceState& state(curr[i]);
2217
2218 sp<DisplaySurface> dispSurface;
2219 sp<IGraphicBufferProducer> producer;
2220 sp<IGraphicBufferProducer> bqProducer;
2221 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002222 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002223
2224 int32_t hwcId = -1;
2225 if (state.isVirtualDisplay()) {
2226 // Virtual displays without a surface are dormant:
2227 // they have external state (layer stack, projection,
2228 // etc.) but no internal state (i.e. a DisplayDevice).
2229 if (state.surface != nullptr) {
2230 // Allow VR composer to use virtual displays.
2231 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2232 int width = 0;
2233 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2234 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2235 int height = 0;
2236 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2237 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2238 int intFormat = 0;
2239 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2240 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2241 auto format = static_cast<android_pixel_format_t>(intFormat);
2242
2243 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2244 }
2245
2246 // TODO: Plumb requested format back up to consumer
2247
2248 sp<VirtualDisplaySurface> vds =
2249 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2250 bqProducer, bqConsumer,
2251 state.displayName);
2252
2253 dispSurface = vds;
2254 producer = vds;
2255 }
2256 } else {
2257 ALOGE_IF(state.surface != nullptr,
2258 "adding a supported display, but rendering "
2259 "surface is provided (%p), ignoring it",
2260 state.surface.get());
2261
2262 hwcId = state.type;
2263 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2264 producer = bqProducer;
2265 }
2266
2267 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002268
Lloyd Pique347200f2017-12-14 17:00:15 -08002269 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002270 bool hasWideColorSupport = false;
2271 if (hasWideColorDisplay) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002272 std::vector<android_color_mode_t> modes =
2273 getHwComposer().getColorModes(state.type);
2274 for (android_color_mode_t colorMode : modes) {
2275 switch (colorMode) {
2276 case HAL_COLOR_MODE_DISPLAY_P3:
2277 case HAL_COLOR_MODE_ADOBE_RGB:
2278 case HAL_COLOR_MODE_DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002279 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002280 break;
2281 default:
2282 break;
2283 }
2284 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002285 }
2286
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002287 bool hasHdrSupport = false;
2288 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2289 getHwComposer().getHdrCapabilities(state.type);
2290 if (hdrCapabilities) {
2291 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2292 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2293 hasHdrSupport = iter != types.cend();
2294 }
2295
Lloyd Pique347200f2017-12-14 17:00:15 -08002296 sp<DisplayDevice> hw =
2297 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002298 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002299 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002300
Lloyd Piquec5208312018-01-08 17:59:02 -08002301 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002302 if (hasWideColorSupport) {
Lloyd Piquec5208312018-01-08 17:59:02 -08002303 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002304 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002305 setActiveColorModeInternal(hw, defaultColorMode);
2306 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002307 hw->setLayerStack(state.layerStack);
2308 hw->setProjection(state.orientation, state.viewport, state.frame);
2309 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002310
Lloyd Pique347200f2017-12-14 17:00:15 -08002311 mDisplays.add(display, hw);
2312 if (!state.isVirtualDisplay()) {
2313 mEventThread->onHotplugReceived(state.type, true);
2314 }
2315 }
2316 }
2317 }
2318 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002319
2320 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002321}
2322
Mathias Agopian87baae12012-07-31 12:38:26 -07002323void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002324{
Dan Stoza7dde5992015-05-22 09:51:44 -07002325 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002326 mCurrentState.traverseInZOrder([](Layer* layer) {
2327 layer->notifyAvailableFrames();
2328 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 /*
2331 * Traversal of the children
2332 * (perform the transaction for each of them if needed)
2333 */
2334
Mathias Agopian3559b072012-08-15 13:46:03 -07002335 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002336 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002338 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339
2340 const uint32_t flags = layer->doTransaction(0);
2341 if (flags & Layer::eVisibleRegion)
2342 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002343 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 }
2345
2346 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002347 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348 */
2349
Mathias Agopiane57f2922012-08-09 16:29:12 -07002350 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002352 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354
Mathias Agopian84300952012-11-21 16:02:13 -08002355 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2356 // The transform hint might have changed for some layers
2357 // (either because a display has changed, or because a layer
2358 // as changed).
2359 //
2360 // Walk through all the layers in currentLayers,
2361 // and update their transform hint.
2362 //
2363 // If a layer is visible only on a single display, then that
2364 // display is used to calculate the hint, otherwise we use the
2365 // default display.
2366 //
2367 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2368 // the hint is set before we acquire a buffer from the surface texture.
2369 //
2370 // NOTE: layer transactions have taken place already, so we use their
2371 // drawing state. However, SurfaceFlinger's own transaction has not
2372 // happened yet, so we must use the current state layer list
2373 // (soon to become the drawing state list).
2374 //
2375 sp<const DisplayDevice> disp;
2376 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002377 bool first = true;
2378 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002379 // NOTE: we rely on the fact that layers are sorted by
2380 // layerStack first (so we don't have to traverse the list
2381 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002382 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002383 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002384 currentlayerStack = layerStack;
2385 // figure out if this layerstack is mirrored
2386 // (more than one display) if so, pick the default display,
2387 // if not, pick the only display it's on.
2388 disp.clear();
2389 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2390 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002391 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002392 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002393 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002394 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002395 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002396 break;
2397 }
2398 }
2399 }
2400 }
Chet Haase91d25932013-04-11 15:24:55 -07002401
Robert Carr56a0b9a2017-12-04 16:06:13 -08002402 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002403 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002404 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2405 // redraw after transform hint changes. See bug 8508397.
2406
2407 // could be null when this layer is using a layerStack
2408 // that is not visible on any display. Also can occur at
2409 // screen off/on times.
2410 disp = getDefaultDisplayDeviceLocked();
2411 }
2412 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002413 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002414 if (disp != nullptr) {
2415 layer->updateTransformHint(disp);
2416 }
Robert Carr2047fae2016-11-28 14:09:09 -08002417
2418 first = false;
2419 });
Mathias Agopian84300952012-11-21 16:02:13 -08002420 }
2421
2422
Mathias Agopian3559b072012-08-15 13:46:03 -07002423 /*
2424 * Perform our own transaction if needed
2425 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002426
2427 if (mLayersAdded) {
2428 mLayersAdded = false;
2429 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002430 mVisibleRegionsDirty = true;
2431 }
2432
2433 // some layers might have been removed, so
2434 // we need to update the regions they're exposing.
2435 if (mLayersRemoved) {
2436 mLayersRemoved = false;
2437 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002438 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002439 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002440 // this layer is not visible anymore
2441 // TODO: we could traverse the tree from front to back and
2442 // compute the actual visible region
2443 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002444 Region visibleReg;
2445 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002446 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002447 }
Robert Carr2047fae2016-11-28 14:09:09 -08002448 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 }
2450
2451 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002452
2453 updateCursorAsync();
2454}
2455
2456void SurfaceFlinger::updateCursorAsync()
2457{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2459 auto& displayDevice = mDisplays[displayId];
2460 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002461 continue;
2462 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463
2464 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2465 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002466 }
2467 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002468}
2469
2470void SurfaceFlinger::commitTransaction()
2471{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002472 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002473 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002474 for (const auto& l : mLayersPendingRemoval) {
2475 recordBufferingStats(l->getName().string(),
2476 l->getOccupancyHistory(true));
2477 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 }
2479 mLayersPendingRemoval.clear();
2480 }
2481
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002482 // If this transaction is part of a window animation then the next frame
2483 // we composite should be considered an animation as well.
2484 mAnimCompositionPending = mAnimTransactionPending;
2485
Mathias Agopian4fec8732012-06-29 14:12:52 -07002486 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002487 mDrawingState.traverseInZOrder([](Layer* layer) {
2488 layer->commitChildList();
2489 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002490 mTransactionPending = false;
2491 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493}
2494
Chia-I Wuab0c3192017-08-01 11:29:00 -07002495void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002496 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497{
Mathias Agopian841cde52012-03-01 15:44:37 -08002498 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 Region aboveOpaqueLayers;
2502 Region aboveCoveredLayers;
2503 Region dirty;
2504
Mathias Agopian87baae12012-07-31 12:38:26 -07002505 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Robert Carr2047fae2016-11-28 14:09:09 -08002507 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002509 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510
Jesse Hall01e29052013-02-19 16:13:35 -08002511 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002512 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002513 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002514
Mathias Agopianab028732010-03-16 16:41:46 -07002515 /*
2516 * opaqueRegion: area of a surface that is fully opaque.
2517 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002519
2520 /*
2521 * visibleRegion: area of a surface that is visible on screen
2522 * and not fully transparent. This is essentially the layer's
2523 * footprint minus the opaque regions above it.
2524 * Areas covered by a translucent surface are considered visible.
2525 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002527
2528 /*
2529 * coveredRegion: area of a surface that is covered by all
2530 * visible regions above it (which includes the translucent areas).
2531 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002533
Jesse Halla8026d22012-09-25 13:25:04 -07002534 /*
2535 * transparentRegion: area of a surface that is hinted to be completely
2536 * transparent. This is only used to tell when the layer has no visible
2537 * non-transparent regions and can be removed from the layer list. It
2538 * does not affect the visibleRegion of this layer or any layers
2539 * beneath it. The hint may not be correct if apps don't respect the
2540 * SurfaceView restrictions (which, sadly, some don't).
2541 */
2542 Region transparentRegion;
2543
Mathias Agopianab028732010-03-16 16:41:46 -07002544
2545 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002546 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002547 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002551 if (!visibleRegion.isEmpty()) {
2552 // Remove the transparent area from the visible region
2553 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002554 if (tr.preserveRects()) {
2555 // transform the transparent region
2556 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002557 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002558 // transformation too complex, can't do the
2559 // transparent region optimization.
2560 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002561 }
Mathias Agopianab028732010-03-16 16:41:46 -07002562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563
Mathias Agopianab028732010-03-16 16:41:46 -07002564 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002565 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002566 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002567 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2568 // the opaque region is the layer's footprint
2569 opaqueRegion = visibleRegion;
2570 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 }
2572 }
2573
Robert Carre5f4f692018-01-12 13:12:28 -08002574 if (visibleRegion.isEmpty()) {
2575 layer->clearVisibilityRegions();
2576 return;
2577 }
2578
Mathias Agopianab028732010-03-16 16:41:46 -07002579 // Clip the covered region to the visible region
2580 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2581
2582 // Update aboveCoveredLayers for next (lower) layer
2583 aboveCoveredLayers.orSelf(visibleRegion);
2584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 // subtract the opaque region covered by the layers above us
2586 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587
2588 // compute this layer's dirty region
2589 if (layer->contentDirty) {
2590 // we need to invalidate the whole region
2591 dirty = visibleRegion;
2592 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002593 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 layer->contentDirty = false;
2595 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002596 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002597 * the exposed region consists of two components:
2598 * 1) what's VISIBLE now and was COVERED before
2599 * 2) what's EXPOSED now less what was EXPOSED before
2600 *
2601 * note that (1) is conservative, we start with the whole
2602 * visible region but only keep what used to be covered by
2603 * something -- which mean it may have been exposed.
2604 *
2605 * (2) handles areas that were not covered by anything but got
2606 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002607 */
Mathias Agopianab028732010-03-16 16:41:46 -07002608 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002609 const Region oldVisibleRegion = layer->visibleRegion;
2610 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002611 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2612 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 }
2614 dirty.subtractSelf(aboveOpaqueLayers);
2615
2616 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002617 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618
Mathias Agopianab028732010-03-16 16:41:46 -07002619 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002621
Jesse Halla8026d22012-09-25 13:25:04 -07002622 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 layer->setVisibleRegion(visibleRegion);
2624 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002625 layer->setVisibleNonTransparentRegion(
2626 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002627 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628
Mathias Agopian87baae12012-07-31 12:38:26 -07002629 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630}
2631
Chia-I Wuab0c3192017-08-01 11:29:00 -07002632void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002633 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002634 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002635 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002636 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002637 }
2638 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002639}
2640
Dan Stoza6b9454d2014-11-07 16:00:59 -08002641bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 ALOGV("handlePageFlip");
2644
Brian Andersond6927fb2016-07-23 23:37:30 -07002645 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646
Mathias Agopian4fec8732012-06-29 14:12:52 -07002647 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002648 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002649 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002650
2651 // Store the set of layers that need updates. This set must not change as
2652 // buffers are being latched, as this could result in a deadlock.
2653 // Example: Two producers share the same command stream and:
2654 // 1.) Layer 0 is latched
2655 // 2.) Layer 0 gets a new frame
2656 // 2.) Layer 1 gets a new frame
2657 // 3.) Layer 1 is latched.
2658 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2659 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002660 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002661 if (layer->hasQueuedFrame()) {
2662 frameQueued = true;
2663 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002664 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002665 } else {
2666 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002667 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002668 } else {
2669 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002670 }
Robert Carr2047fae2016-11-28 14:09:09 -08002671 });
2672
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002674 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002675 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002676 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002677 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002678 newDataLatched = true;
2679 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002680 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002681
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002682 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002683
2684 // If we will need to wake up at some time in the future to deal with a
2685 // queued frame that shouldn't be displayed during this vsync period, wake
2686 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002687 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002688 signalLayerUpdate();
2689 }
2690
2691 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002692 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693}
2694
Mathias Agopianad456f92011-01-13 17:53:01 -08002695void SurfaceFlinger::invalidateHwcGeometry()
2696{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002698}
2699
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002700
Fabien Sanglard830b8472016-11-30 16:35:58 -08002701void SurfaceFlinger::doDisplayComposition(
2702 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002703 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704{
Dan Stoza71433162014-02-04 16:22:36 -08002705 // We only need to actually compose the display if:
2706 // 1) It is being handled by hardware composer, which may need this to
2707 // keep its virtual display state machine in sync, or
2708 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002709 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002710 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002712 return;
2713 }
2714
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002716 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002717
2718 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002719 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720}
2721
Chia-I Wub02087d2017-11-09 10:19:54 -08002722bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002723{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002724 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002725
Chia-I Wub02087d2017-11-09 10:19:54 -08002726 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002727 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002728 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002729
2730 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002731 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2732 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002733 if (applyColorMatrix) {
2734 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2735 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2736 }
2737
David Sodman105b7dc2017-11-04 20:28:14 -07002738 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 if (hasClientComposition) {
2740 ALOGV("hasClientComposition");
2741
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002742 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002743 if (displayDevice->getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002744 displayDevice->getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
2745 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2746 }
2747 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2748
Chia-I Wu7f402902017-11-09 12:51:10 -08002749 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002750 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002751 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002752 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002753
2754 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002755 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002756 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2757 }
2758 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002759 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002760
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002761 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002762 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002764 // when using overlays, we assume a fully transparent framebuffer
2765 // NOTE: we could reduce how much we need to clear, for instance
2766 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002767 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002768 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002769 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002770 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002771 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002772 // we're left with the letterbox region
2773 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002775
2776 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002778
Mathias Agopianb9494d52012-04-18 02:28:45 -07002779 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002780 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002781 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002783 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002784 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002785
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002787 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002788 // scissor on the main display. It should never be needed
2789 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 const Rect& bounds(displayDevice->getBounds());
2791 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002792 if (scissor != bounds) {
2793 // scissor doesn't match the screen's dimensions, so we
2794 // need to clear everything outside of it and enable
2795 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002796
Mathias Agopianf45c5102012-10-24 16:29:17 -07002797 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002799 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002800 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002801 }
2802 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002803 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002804
Mathias Agopian85d751c2012-08-29 16:59:24 -07002805 /*
2806 * and then, render the layers targeted at the framebuffer
2807 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002808
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 ALOGV("Rendering client layers");
2810 const Transform& displayTransform = displayDevice->getTransform();
2811 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002812 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002813 bool firstLayer = true;
2814 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002815 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 displayTransform.transform(layer->visibleRegion)));
2817 ALOGV("Layer: %s", layer->getName().string());
2818 ALOGV(" Composition type: %s",
2819 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002820 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 switch (layer->getCompositionType(hwcId)) {
2822 case HWC2::Composition::Cursor:
2823 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002824 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002825 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002826 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002828 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002830 // never clear the very first layer since we're
2831 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002832 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002833 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002834 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002835 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002836 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002837 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002838 break;
2839 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002841 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002842 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002843 } else {
2844 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002845 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002847 }
2848 } else {
2849 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002850 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002851 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002852 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002853 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002854 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002855 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002856 }
2857 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002858
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002859 if (applyColorMatrix) {
2860 getRenderEngine().setupColorTransform(oldColorMatrix);
2861 }
2862
Mathias Agopianf45c5102012-10-24 16:29:17 -07002863 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002864 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002865 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866}
2867
Fabien Sanglard830b8472016-11-30 16:35:58 -08002868void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2869 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002870 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002871 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Dan Stoza7d89d062015-04-30 13:29:25 -07002874status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002875 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002876 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 const sp<Layer>& lbc,
2878 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002879{
Dan Stoza7d89d062015-04-30 13:29:25 -07002880 // add this layer to the current state list
2881 {
2882 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002884 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2885 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002886 return NO_MEMORY;
2887 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 if (parent == nullptr) {
2889 mCurrentState.layersSortedByZ.add(lbc);
2890 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002891 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002892 ALOGE("addClientLayer called with a removed parent");
2893 return NAME_NOT_FOUND;
2894 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 parent->addChild(lbc);
2896 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002897
Dan Stoza101d8dc2018-02-27 15:42:25 -08002898 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2899 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() > MAX_LAYERS,
2900 "Suspected IGBP leak");
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901 mLayersAdded = true;
2902 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002903 }
2904
Mathias Agopian96f08192010-06-02 23:28:45 -07002905 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002906 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002907
Dan Stoza7d89d062015-04-30 13:29:25 -07002908 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002909}
2910
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002911status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002912 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002913 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2914}
Robert Carr7f9b8992017-03-10 11:08:39 -08002915
chaviwca27f252018-02-06 16:46:39 -08002916status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2917 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002918 if (layer->isPendingRemoval()) {
2919 return NO_ERROR;
2920 }
2921
Robert Carr1f0a16a2016-10-24 16:27:39 -07002922 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002923 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002924 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002925 if (topLevelOnly) {
2926 return NO_ERROR;
2927 }
2928
Chia-I Wu98f1c102017-05-30 14:54:08 -07002929 sp<Layer> ancestor = p;
2930 while (ancestor->getParent() != nullptr) {
2931 ancestor = ancestor->getParent();
2932 }
2933 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2934 ALOGE("removeLayer called with a layer whose parent has been removed");
2935 return NAME_NOT_FOUND;
2936 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002937
2938 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002939 } else {
2940 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002941 }
2942
Robert Carr136e2f62017-02-08 17:54:29 -08002943 // As a matter of normal operation, the LayerCleaner will produce a second
2944 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2945 // so we will succeed in promoting it, but it's already been removed
2946 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2947 // otherwise something has gone wrong and we are leaking the layer.
2948 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002949 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2950 layer->getName().string(),
2951 (p != nullptr) ? p->getName().string() : "no-parent");
2952 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002953 } else if (index < 0) {
2954 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002955 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002956
Chia-I Wuc6657022017-08-15 11:18:17 -07002957 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002958 mLayersPendingRemoval.add(layer);
2959 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002960 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002961 setTransactionFlags(eTransactionNeeded);
2962 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963}
2964
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002965uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002966 return android_atomic_release_load(&mTransactionFlags);
2967}
2968
Mathias Agopian3f844832013-08-07 21:24:32 -07002969uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2971}
2972
Mathias Agopian3f844832013-08-07 21:24:32 -07002973uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2975 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002976 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002977 }
2978 return old;
2979}
2980
chaviwca27f252018-02-06 16:46:39 -08002981bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
2982 for (const ComposerState& state : states) {
2983 // Here we need to check that the interface we're given is indeed
2984 // one of our own. A malicious client could give us a nullptr
2985 // IInterface, or one of its own or even one of our own but a
2986 // different type. All these situations would cause us to crash.
2987 if (state.client == nullptr) {
2988 return true;
2989 }
2990
2991 sp<IBinder> binder = IInterface::asBinder(state.client);
2992 if (binder == nullptr) {
2993 return true;
2994 }
2995
2996 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
2997 return true;
2998 }
2999 }
3000 return false;
3001}
3002
Mathias Agopian8b33f032012-07-24 20:43:54 -07003003void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003004 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003005 const Vector<DisplayState>& displays,
3006 uint32_t flags)
3007{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003008 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003009 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003010 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011
chaviwca27f252018-02-06 16:46:39 -08003012 if (containsAnyInvalidClientState(states)) {
3013 return;
3014 }
3015
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003016 if (flags & eAnimation) {
3017 // For window updates that are part of an animation we must wait for
3018 // previous animation "frames" to be handled.
3019 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003020 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003021 if (CC_UNLIKELY(err != NO_ERROR)) {
3022 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003023 // caller after a few seconds.
3024 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3025 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003026 mAnimTransactionPending = false;
3027 break;
3028 }
3029 }
3030 }
3031
chaviwca27f252018-02-06 16:46:39 -08003032 for (const DisplayState& display : displays) {
3033 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003034 }
3035
chaviwca27f252018-02-06 16:46:39 -08003036 for (const ComposerState& state : states) {
3037 transactionFlags |= setClientStateLocked(state);
3038 }
3039
3040 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3041 // as destroyed should only occur after setting all other states. This is to allow for a
3042 // child re-parent to happen before marking its original parent as destroyed (which would
3043 // then mark the child as destroyed).
3044 for (const ComposerState& state : states) {
3045 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003046 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003047
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003048 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3049 // anyway. This can be used as a flush mechanism for previous async transactions.
3050 // Empty animation transaction can be used to simulate back-pressure, so also force a
3051 // transaction for empty animation transactions.
3052 if (transactionFlags == 0 &&
3053 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003054 transactionFlags = eTransactionNeeded;
3055 }
3056
Mathias Agopian386aa982011-11-07 21:58:03 -08003057 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003058 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003059 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003060 }
Irvel468051e2016-06-13 16:44:44 -07003061
Mathias Agopian386aa982011-11-07 21:58:03 -08003062 // this triggers the transaction
3063 setTransactionFlags(transactionFlags);
3064
3065 // if this is a synchronous transaction, wait for it to take effect
3066 // before returning.
3067 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003068 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003069 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003070 if (flags & eAnimation) {
3071 mAnimTransactionPending = true;
3072 }
3073 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003074 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3075 if (CC_UNLIKELY(err != NO_ERROR)) {
3076 // just in case something goes wrong in SF, return to the
3077 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003078 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3079 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003080 break;
3081 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003082 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083 }
3084}
3085
Mathias Agopiane57f2922012-08-09 16:29:12 -07003086uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3087{
Jesse Hall9a143922012-10-04 16:29:19 -07003088 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3089 if (dpyIdx < 0)
3090 return 0;
3091
Mathias Agopiane57f2922012-08-09 16:29:12 -07003092 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003093 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003094 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003095 const uint32_t what = s.what;
3096 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003097 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098 disp.surface = s.surface;
3099 flags |= eDisplayTransactionNeeded;
3100 }
3101 }
3102 if (what & DisplayState::eLayerStackChanged) {
3103 if (disp.layerStack != s.layerStack) {
3104 disp.layerStack = s.layerStack;
3105 flags |= eDisplayTransactionNeeded;
3106 }
3107 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003108 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003109 if (disp.orientation != s.orientation) {
3110 disp.orientation = s.orientation;
3111 flags |= eDisplayTransactionNeeded;
3112 }
3113 if (disp.frame != s.frame) {
3114 disp.frame = s.frame;
3115 flags |= eDisplayTransactionNeeded;
3116 }
3117 if (disp.viewport != s.viewport) {
3118 disp.viewport = s.viewport;
3119 flags |= eDisplayTransactionNeeded;
3120 }
3121 }
Michael Lentine47e45402014-07-18 15:34:25 -07003122 if (what & DisplayState::eDisplaySizeChanged) {
3123 if (disp.width != s.width) {
3124 disp.width = s.width;
3125 flags |= eDisplayTransactionNeeded;
3126 }
3127 if (disp.height != s.height) {
3128 disp.height = s.height;
3129 flags |= eDisplayTransactionNeeded;
3130 }
3131 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132 }
3133 return flags;
3134}
3135
chaviwca27f252018-02-06 16:46:39 -08003136uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3137 const layer_state_t& s = composerState.state;
3138 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3139
Mathias Agopian13127d82013-03-05 17:47:11 -08003140 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003141 if (layer == nullptr) {
3142 return 0;
3143 }
3144
3145 if (layer->isPendingRemoval()) {
3146 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3147 return 0;
3148 }
3149
3150 uint32_t flags = 0;
3151
3152 const uint32_t what = s.what;
3153 bool geometryAppliesWithResize =
3154 what & layer_state_t::eGeometryAppliesWithResize;
3155 if (what & layer_state_t::ePositionChanged) {
3156 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3157 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003158 }
chaviw8b3871a2017-11-01 17:41:01 -07003159 }
3160 if (what & layer_state_t::eLayerChanged) {
3161 // NOTE: index needs to be calculated before we update the state
3162 const auto& p = layer->getParent();
3163 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003164 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003165 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003166 mCurrentState.layersSortedByZ.removeAt(idx);
3167 mCurrentState.layersSortedByZ.add(layer);
3168 // we need traversal (state changed)
3169 // AND transaction (list changed)
3170 flags |= eTransactionNeeded|eTraversalNeeded;
3171 }
chaviw8b3871a2017-11-01 17:41:01 -07003172 } else {
3173 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003174 flags |= eTransactionNeeded|eTraversalNeeded;
3175 }
3176 }
chaviw8b3871a2017-11-01 17:41:01 -07003177 }
3178 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003179 // NOTE: index needs to be calculated before we update the state
3180 const auto& p = layer->getParent();
3181 if (p == nullptr) {
3182 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3183 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3184 mCurrentState.layersSortedByZ.removeAt(idx);
3185 mCurrentState.layersSortedByZ.add(layer);
3186 // we need traversal (state changed)
3187 // AND transaction (list changed)
3188 flags |= eTransactionNeeded|eTraversalNeeded;
3189 }
3190 } else {
3191 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3192 flags |= eTransactionNeeded|eTraversalNeeded;
3193 }
chaviw8b3871a2017-11-01 17:41:01 -07003194 }
3195 }
3196 if (what & layer_state_t::eSizeChanged) {
3197 if (layer->setSize(s.w, s.h)) {
3198 flags |= eTraversalNeeded;
3199 }
3200 }
3201 if (what & layer_state_t::eAlphaChanged) {
3202 if (layer->setAlpha(s.alpha))
3203 flags |= eTraversalNeeded;
3204 }
3205 if (what & layer_state_t::eColorChanged) {
3206 if (layer->setColor(s.color))
3207 flags |= eTraversalNeeded;
3208 }
3209 if (what & layer_state_t::eMatrixChanged) {
3210 if (layer->setMatrix(s.matrix))
3211 flags |= eTraversalNeeded;
3212 }
3213 if (what & layer_state_t::eTransparentRegionChanged) {
3214 if (layer->setTransparentRegionHint(s.transparentRegion))
3215 flags |= eTraversalNeeded;
3216 }
3217 if (what & layer_state_t::eFlagsChanged) {
3218 if (layer->setFlags(s.flags, s.mask))
3219 flags |= eTraversalNeeded;
3220 }
3221 if (what & layer_state_t::eCropChanged) {
3222 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3223 flags |= eTraversalNeeded;
3224 }
3225 if (what & layer_state_t::eFinalCropChanged) {
3226 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3227 flags |= eTraversalNeeded;
3228 }
3229 if (what & layer_state_t::eLayerStackChanged) {
3230 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3231 // We only allow setting layer stacks for top level layers,
3232 // everything else inherits layer stack from its parent.
3233 if (layer->hasParent()) {
3234 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3235 layer->getName().string());
3236 } else if (idx < 0) {
3237 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3238 "that also does not appear in the top level layer list. Something"
3239 " has gone wrong.", layer->getName().string());
3240 } else if (layer->setLayerStack(s.layerStack)) {
3241 mCurrentState.layersSortedByZ.removeAt(idx);
3242 mCurrentState.layersSortedByZ.add(layer);
3243 // we need traversal (state changed)
3244 // AND transaction (list changed)
3245 flags |= eTransactionNeeded|eTraversalNeeded;
3246 }
3247 }
3248 if (what & layer_state_t::eDeferTransaction) {
3249 if (s.barrierHandle != nullptr) {
3250 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3251 } else if (s.barrierGbp != nullptr) {
3252 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3253 if (authenticateSurfaceTextureLocked(gbp)) {
3254 const auto& otherLayer =
3255 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3256 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3257 } else {
3258 ALOGE("Attempt to defer transaction to to an"
3259 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003260 }
3261 }
chaviw8b3871a2017-11-01 17:41:01 -07003262 // We don't trigger a traversal here because if no other state is
3263 // changed, we don't want this to cause any more work
3264 }
3265 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003266 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003267 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003268 if (!hadParent) {
3269 mCurrentState.layersSortedByZ.remove(layer);
3270 }
chaviw8b3871a2017-11-01 17:41:01 -07003271 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003272 }
chaviw8b3871a2017-11-01 17:41:01 -07003273 }
3274 if (what & layer_state_t::eReparentChildren) {
3275 if (layer->reparentChildren(s.reparentHandle)) {
3276 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003277 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003278 }
chaviw8b3871a2017-11-01 17:41:01 -07003279 if (what & layer_state_t::eDetachChildren) {
3280 layer->detachChildren();
3281 }
3282 if (what & layer_state_t::eOverrideScalingModeChanged) {
3283 layer->setOverrideScalingMode(s.overrideScalingMode);
3284 // We don't trigger a traversal here because if no other state is
3285 // changed, we don't want this to cause any more work
3286 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 return flags;
3288}
3289
chaviwca27f252018-02-06 16:46:39 -08003290void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3291 const layer_state_t& state = composerState.state;
3292 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3293
3294 sp<Layer> layer(client->getLayerUser(state.surface));
3295 if (layer == nullptr) {
3296 return;
3297 }
3298
3299 if (layer->isPendingRemoval()) {
3300 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3301 return;
3302 }
3303
3304 if (state.what & layer_state_t::eDestroySurface) {
3305 removeLayerLocked(mStateLock, layer);
3306 }
3307}
3308
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003309status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003310 const String8& name,
3311 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003312 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003313 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3314 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003316 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003317 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003318 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003319 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003320 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003321
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003322 status_t result = NO_ERROR;
3323
3324 sp<Layer> layer;
3325
Cody Northropbc755282017-03-31 12:00:08 -06003326 String8 uniqueName = getUniqueLayerName(name);
3327
Mathias Agopian3165cc22012-08-08 19:42:09 -07003328 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3329 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003330 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003331 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003332 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334 break;
chaviw13fdc492017-06-27 12:40:18 -07003335 case ISurfaceComposerClient::eFXSurfaceColor:
3336 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003337 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003338 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003339 break;
3340 default:
3341 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342 break;
3343 }
3344
Dan Stoza7d89d062015-04-30 13:29:25 -07003345 if (result != NO_ERROR) {
3346 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003348
Chia-I Wuab0c3192017-08-01 11:29:00 -07003349 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3350 // TODO b/64227542
3351 if (windowType == 441731) {
3352 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3353 layer->setPrimaryDisplayOnly();
3354 }
3355
Albert Chaulk479c60c2017-01-27 14:21:34 -05003356 layer->setInfo(windowType, ownerUid);
3357
Robert Carr1f0a16a2016-10-24 16:27:39 -07003358 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003359 if (result != NO_ERROR) {
3360 return result;
3361 }
Irvelffc9efc2016-07-27 15:16:37 -07003362 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003363
3364 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003365 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366}
3367
Cody Northropbc755282017-03-31 12:00:08 -06003368String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3369{
3370 bool matchFound = true;
3371 uint32_t dupeCounter = 0;
3372
3373 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3374 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3375
3376 // Loop over layers until we're sure there is no matching name
3377 while (matchFound) {
3378 matchFound = false;
3379 mDrawingState.traverseInZOrder([&](Layer* layer) {
3380 if (layer->getName() == uniqueName) {
3381 matchFound = true;
3382 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3383 }
3384 });
3385 }
3386
3387 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3388
3389 return uniqueName;
3390}
3391
David Sodman0c69cad2017-08-21 12:12:51 -07003392status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003393 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3394 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003395{
3396 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003397 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003398 case PIXEL_FORMAT_TRANSPARENT:
3399 case PIXEL_FORMAT_TRANSLUCENT:
3400 format = PIXEL_FORMAT_RGBA_8888;
3401 break;
3402 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003403 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003404 break;
3405 }
3406
David Sodman0c69cad2017-08-21 12:12:51 -07003407 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3408 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003409 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003410 *handle = layer->getHandle();
3411 *gbp = layer->getProducer();
3412 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003414
David Sodman0c69cad2017-08-21 12:12:51 -07003415 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003416 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003417}
3418
chaviw13fdc492017-06-27 12:40:18 -07003419status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003420 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003421 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422{
chaviw13fdc492017-06-27 12:40:18 -07003423 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003424 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003425 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003426}
3427
Mathias Agopianac9fa422013-02-11 16:40:36 -08003428status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003429{
Robert Carr9524cb32017-02-13 11:32:32 -08003430 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003431 status_t err = NO_ERROR;
3432 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003433 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003434 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003435 err = removeLayer(l);
3436 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3437 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003438 }
3439 return err;
3440}
3441
Mathias Agopian13127d82013-03-05 17:47:11 -08003442status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003443{
Mathias Agopian67106042013-03-14 19:18:13 -07003444 // called by ~LayerCleaner() when all references to the IBinder (handle)
3445 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003446 sp<Layer> l = layer.promote();
3447 if (l == nullptr) {
3448 // The layer has already been removed, carry on
3449 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003450 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003451 // If we have a parent, then we can continue to live as long as it does.
3452 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003453}
3454
Mathias Agopianb60314a2012-04-10 22:09:54 -07003455// ---------------------------------------------------------------------------
3456
Andy McFadden13a082e2012-08-24 10:16:42 -07003457void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003458 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003459 Vector<ComposerState> state;
3460 Vector<DisplayState> displays;
3461 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003462 d.what = DisplayState::eDisplayProjectionChanged |
3463 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003464 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003465 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003466 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003467 d.frame.makeInvalid();
3468 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003469 d.width = 0;
3470 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003471 displays.add(d);
3472 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003473 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3474 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003475
David Sodman105b7dc2017-11-04 20:28:14 -07003476 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003477 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003478 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003479
Brian Andersond0010582017-03-07 13:20:31 -08003480 // Use phase of 0 since phase is not known.
3481 // Use latency of 0, which will snap to the ideal latency.
3482 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003483}
3484
3485void SurfaceFlinger::initializeDisplays() {
3486 class MessageScreenInitialized : public MessageBase {
3487 SurfaceFlinger* flinger;
3488 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003489 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003490 virtual bool handler() {
3491 flinger->onInitializeDisplays();
3492 return true;
3493 }
3494 };
3495 sp<MessageBase> msg = new MessageScreenInitialized(this);
3496 postMessageAsync(msg); // we may be called from main thread, use async message
3497}
3498
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003499void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003500 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003501 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3502 this);
3503 int32_t type = hw->getDisplayType();
3504 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003505
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003506 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003507 return;
3508 }
3509
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 hw->setPowerMode(mode);
3511 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3512 ALOGW("Trying to set power mode for virtual display");
3513 return;
3514 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003515
Irvelffc9efc2016-07-27 15:16:37 -07003516 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003517 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003518 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3519 if (idx < 0) {
3520 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3521 return;
3522 }
3523 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3524 }
3525
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003526 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003527 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003528 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003529 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3530 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003531 // FIXME: eventthread only knows about the main display right now
3532 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003533 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003536 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003537 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003538 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003539
3540 struct sched_param param = {0};
3541 param.sched_priority = 1;
3542 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3543 ALOGW("Couldn't set SCHED_FIFO on display on");
3544 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003545 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003546 // Turn off the display
3547 struct sched_param param = {0};
3548 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3549 ALOGW("Couldn't set SCHED_OTHER on display off");
3550 }
3551
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003552 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3553 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003554 disableHardwareVsync(true); // also cancels any in-progress resync
3555
Mathias Agopiancde87a32012-09-13 14:09:01 -07003556 // FIXME: eventthread only knows about the main display right now
3557 mEventThread->onScreenReleased();
3558 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003559
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003560 getHwComposer().setPowerMode(type, mode);
3561 mVisibleRegionsDirty = true;
3562 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003563 } else if (mode == HWC_POWER_MODE_DOZE ||
3564 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003565 // Update display while dozing
3566 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003567 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3568 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003569 // FIXME: eventthread only knows about the main display right now
3570 mEventThread->onScreenAcquired();
3571 resyncToHardwareVsync(true);
3572 }
3573 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3574 // Leave display going to doze
3575 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3576 disableHardwareVsync(true); // also cancels any in-progress resync
3577 // FIXME: eventthread only knows about the main display right now
3578 mEventThread->onScreenReleased();
3579 }
3580 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003581 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003582 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003583 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003584 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003585}
3586
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003587void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3588 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003589 SurfaceFlinger& mFlinger;
3590 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003591 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003592 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003593 MessageSetPowerMode(SurfaceFlinger& flinger,
3594 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3595 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003596 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003597 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003598 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003599 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003600 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003601 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003602 ALOGW("Attempt to set power mode = %d for virtual display",
3603 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003604 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003605 mFlinger.setPowerModeInternal(
3606 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003607 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003608 return true;
3609 }
3610 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003611 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003612 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003613}
3614
3615// ---------------------------------------------------------------------------
3616
Lloyd Pique755e3192018-01-31 16:46:15 -08003617status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3618 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003620
Mathias Agopianbd115332013-04-18 16:41:04 -07003621 IPCThreadState* ipc = IPCThreadState::self();
3622 const int pid = ipc->getCallingPid();
3623 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003624
Mathias Agopianbd115332013-04-18 16:41:04 -07003625 if ((uid != AID_SHELL) &&
3626 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003627 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003628 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003630 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003631 // (this would indicate SF is stuck, but we want to be able to
3632 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003633 status_t err = mStateLock.timedLock(s2ns(1));
3634 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003635 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003636 result.appendFormat(
3637 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3638 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003639 }
3640
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003641 bool dumpAll = true;
3642 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003643 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003644
3645 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003646 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003647 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3648 dumpAll = false;
3649 }
3650
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003651 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003652 if ((index < numArgs) &&
3653 (args[index] == String16("--list"))) {
3654 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003655 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003656 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003657 }
3658
3659 if ((index < numArgs) &&
3660 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003661 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003662 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003663 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003664 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003665
3666 if ((index < numArgs) &&
3667 (args[index] == String16("--latency-clear"))) {
3668 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003669 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003670 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003671 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003672
3673 if ((index < numArgs) &&
3674 (args[index] == String16("--dispsync"))) {
3675 index++;
3676 mPrimaryDispSync.dump(result);
3677 dumpAll = false;
3678 }
Dan Stozab90cf072015-03-05 11:05:59 -08003679
3680 if ((index < numArgs) &&
3681 (args[index] == String16("--static-screen"))) {
3682 index++;
3683 dumpStaticScreenStats(result);
3684 dumpAll = false;
3685 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003686
3687 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003688 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003689 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003690 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003691 dumpAll = false;
3692 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003693
3694 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3695 index++;
3696 dumpWideColorInfo(result);
3697 dumpAll = false;
3698 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003700
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003701 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003702 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003703 }
3704
Mathias Agopian9795c422009-08-26 16:36:26 -07003705 if (locked) {
3706 mStateLock.unlock();
3707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708 }
3709 write(fd, result.string(), result.size());
3710 return NO_ERROR;
3711}
3712
Dan Stozac7014012014-02-14 15:03:43 -08003713void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3714 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003715{
Robert Carr2047fae2016-11-28 14:09:09 -08003716 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003717 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003718 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003719}
3720
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003721void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003722 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003723{
3724 String8 name;
3725 if (index < args.size()) {
3726 name = String8(args[index]);
3727 index++;
3728 }
3729
David Sodman105b7dc2017-11-04 20:28:14 -07003730 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003731 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003732 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003733
3734 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003735 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003736 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003737 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003738 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003739 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003740 }
Robert Carr2047fae2016-11-28 14:09:09 -08003741 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003742 }
3743}
3744
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003745void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003746 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003747{
3748 String8 name;
3749 if (index < args.size()) {
3750 name = String8(args[index]);
3751 index++;
3752 }
3753
Robert Carr2047fae2016-11-28 14:09:09 -08003754 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003755 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003756 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003757 }
Robert Carr2047fae2016-11-28 14:09:09 -08003758 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003759
Svetoslavd85084b2014-03-20 10:28:31 -07003760 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003761}
3762
Jamie Gennis6547ff42013-07-16 20:12:42 -07003763// This should only be called from the main thread. Otherwise it would need
3764// the lock and should use mCurrentState rather than mDrawingState.
3765void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003766 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003767 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003768 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003769
3770 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3771}
3772
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003773void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003774{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003775 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003776
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003777 if (isLayerTripleBufferingDisabled())
3778 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003779
3780 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003781 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003782 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003783 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003784 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3785 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003786 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003787}
3788
Dan Stozab90cf072015-03-05 11:05:59 -08003789void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3790{
3791 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003792 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3793 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003794 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003795 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003796 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3797 b + 1, bucketTimeSec, percent);
3798 }
David Sodman4a36e932017-11-07 14:29:47 -08003799 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003800 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003801 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003802 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003803 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003804}
3805
Dan Stozae77c7662016-05-13 11:37:28 -07003806void SurfaceFlinger::recordBufferingStats(const char* layerName,
3807 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003808 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3809 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003810 for (const auto& segment : history) {
3811 if (!segment.usedThirdBuffer) {
3812 stats.twoBufferTime += segment.totalTime;
3813 }
3814 if (segment.occupancyAverage < 1.0f) {
3815 stats.doubleBufferedTime += segment.totalTime;
3816 } else if (segment.occupancyAverage < 2.0f) {
3817 stats.tripleBufferedTime += segment.totalTime;
3818 }
3819 ++stats.numSegments;
3820 stats.totalTime += segment.totalTime;
3821 }
3822}
3823
Brian Andersond6927fb2016-07-23 23:37:30 -07003824void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3825 result.appendFormat("Layer frame timestamps:\n");
3826
3827 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3828 const size_t count = currentLayers.size();
3829 for (size_t i=0 ; i<count ; i++) {
3830 currentLayers[i]->dumpFrameEvents(result);
3831 }
3832}
3833
Dan Stozae77c7662016-05-13 11:37:28 -07003834void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3835 result.append("Buffering stats:\n");
3836 result.append(" [Layer name] <Active time> <Two buffer> "
3837 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003838 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003839 typedef std::tuple<std::string, float, float, float> BufferTuple;
3840 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003841 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003842 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003843 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003844 if (stats.numSegments == 0) {
3845 continue;
3846 }
3847 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3848 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3849 stats.totalTime;
3850 float doubleBufferRatio = static_cast<float>(
3851 stats.doubleBufferedTime) / stats.totalTime;
3852 float tripleBufferRatio = static_cast<float>(
3853 stats.tripleBufferedTime) / stats.totalTime;
3854 sorted.insert({activeTime, {name, twoBufferRatio,
3855 doubleBufferRatio, tripleBufferRatio}});
3856 }
3857 for (const auto& sortedPair : sorted) {
3858 float activeTime = sortedPair.first;
3859 const BufferTuple& values = sortedPair.second;
3860 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3861 std::get<0>(values).c_str(), activeTime,
3862 std::get<1>(values), std::get<2>(values),
3863 std::get<3>(values));
3864 }
3865 result.append("\n");
3866}
3867
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003868void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3869 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003870 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003871
3872 // TODO: print out if wide-color mode is active or not
3873
3874 for (size_t d = 0; d < mDisplays.size(); d++) {
3875 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3876 int32_t hwcId = displayDevice->getHwcDisplayId();
3877 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3878 continue;
3879 }
3880
3881 result.appendFormat("Display %d color modes:\n", hwcId);
3882 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3883 for (auto&& mode : modes) {
3884 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3885 }
3886
3887 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3888 result.appendFormat(" Current color mode: %s (%d)\n",
3889 decodeColorMode(currentMode).c_str(), currentMode);
3890 }
3891 result.append("\n");
3892}
3893
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003894LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003895 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003896 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3897 const State& state = useDrawing ? mDrawingState : mCurrentState;
3898 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003899 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003900 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003901 });
3902
3903 return layersProto;
3904}
3905
Mathias Agopian74d211a2013-04-22 16:55:35 +02003906void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3907 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003908{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003909 bool colorize = false;
3910 if (index < args.size()
3911 && (args[index] == String16("--color"))) {
3912 colorize = true;
3913 index++;
3914 }
3915
3916 Colorizer colorizer(colorize);
3917
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918 // figure out if we're stuck somewhere
3919 const nsecs_t now = systemTime();
3920 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3921 const nsecs_t inTransaction(mDebugInTransaction);
3922 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3923 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3924
3925 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003926 * Dump library configuration.
3927 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003928
3929 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003930 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003931 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003932 appendSfConfigString(result);
3933 appendUiConfigString(result);
3934 appendGuiConfigString(result);
3935 result.append("\n");
3936
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003937 result.append("\nWide-Color information:\n");
3938 dumpWideColorInfo(result);
3939
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003940 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003941 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003943 result.append(SyncFeatures::getInstance().toString());
3944 result.append("\n");
3945
David Sodman105b7dc2017-11-04 20:28:14 -07003946 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003947
Andy McFadden41d67d72014-04-25 16:58:34 -07003948 colorizer.bold(result);
3949 result.append("DispSync configuration: ");
3950 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003951 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003952 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003953 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003954 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003955 result.append("\n");
3956
Dan Stozab90cf072015-03-05 11:05:59 -08003957 // Dump static screen stats
3958 result.append("\n");
3959 dumpStaticScreenStats(result);
3960 result.append("\n");
3961
Dan Stozae77c7662016-05-13 11:37:28 -07003962 dumpBufferingStats(result);
3963
Andy McFadden4803b742012-09-24 19:07:20 -07003964 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965 * Dump the visible layer list
3966 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003967 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003968 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003969 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003970
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003971 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003972 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3973 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974
3975 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003976 * Dump Display state
3977 */
3978
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003979 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003980 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003981 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003982 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3983 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003984 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003985 }
3986
3987 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003988 * Dump SurfaceFlinger global state
3989 */
3990
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003991 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003992 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003993 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003994
Mathias Agopian888c8222012-08-04 21:10:38 -07003995 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003996 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003997
David Sodmanbc815282017-11-05 18:57:52 -08003998 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003999
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004000 if (hw) {
4001 hw->undefinedRegion.dump(result, "undefinedRegion");
4002 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4003 hw->getOrientation(), hw->isDisplayOn());
4004 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004005 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004006 " last eglSwapBuffers() time: %f us\n"
4007 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004008 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004009 " refresh-rate : %f fps\n"
4010 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004011 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004012 " gpu_to_cpu_unsupported : %d\n"
4013 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014 mLastSwapBufferTime/1000.0,
4015 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004016 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004017 1e9 / activeConfig->getVsyncPeriod(),
4018 activeConfig->getDpiX(),
4019 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004020 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004021
Mathias Agopian74d211a2013-04-22 16:55:35 +02004022 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004023 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004024
Mathias Agopian74d211a2013-04-22 16:55:35 +02004025 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004026 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004027
4028 /*
4029 * VSYNC state
4030 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004031 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004032 result.append("\n");
4033
4034 /*
4035 * HWC layer minidump
4036 */
4037 for (size_t d = 0; d < mDisplays.size(); d++) {
4038 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4039 int32_t hwcId = displayDevice->getHwcDisplayId();
4040 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4041 continue;
4042 }
4043
4044 result.appendFormat("Display %d HWC layers:\n", hwcId);
4045 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004046 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004047 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004048 });
Dan Stozae22aec72016-08-01 13:20:59 -07004049 result.append("\n");
4050 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004051
4052 /*
4053 * Dump HWComposer state
4054 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004055 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004056 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004057 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004058 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004059 result.appendFormat(" h/w composer %s\n",
4060 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004061 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004062
4063 /*
4064 * Dump gralloc state
4065 */
4066 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4067 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004068
4069 /*
4070 * Dump VrFlinger state if in use.
4071 */
4072 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4073 result.append("VrFlinger state:\n");
4074 result.append(mVrFlinger->Dump().c_str());
4075 result.append("\n");
4076 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004077}
4078
Mathias Agopian13127d82013-03-05 17:47:11 -08004079const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004080SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004081 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004082 wp<IBinder> dpy;
4083 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4084 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4085 dpy = mDisplays.keyAt(i);
4086 break;
4087 }
4088 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004089 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004090 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4091 // Just use the primary display so we have something to return
4092 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4093 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004094 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004095}
4096
Keun young Park63f165f2012-08-31 10:53:36 -07004097bool SurfaceFlinger::startDdmConnection()
4098{
4099 void* libddmconnection_dso =
4100 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4101 if (!libddmconnection_dso) {
4102 return false;
4103 }
4104 void (*DdmConnection_start)(const char* name);
4105 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004106 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004107 if (!DdmConnection_start) {
4108 dlclose(libddmconnection_dso);
4109 return false;
4110 }
4111 (*DdmConnection_start)(getServiceName());
4112 return true;
4113}
4114
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004115status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 switch (code) {
4117 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004118 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004119 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004120 case CLEAR_ANIMATION_FRAME_STATS:
4121 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004122 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004123 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004124 case ENABLE_VSYNC_INJECTIONS:
4125 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 {
4127 // codes that require permission check
4128 IPCThreadState* ipc = IPCThreadState::self();
4129 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004130 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004131 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004132 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004133 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004134 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004136 break;
4137 }
Robert Carr1db73f62016-12-21 12:58:51 -08004138 /*
4139 * Calling setTransactionState is safe, because you need to have been
4140 * granted a reference to Client* and Handle* to do anything with it.
4141 *
4142 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4143 */
4144 case SET_TRANSACTION_STATE:
4145 case CREATE_SCOPED_CONNECTION:
4146 {
4147 return OK;
4148 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004149 case CAPTURE_SCREEN:
4150 {
4151 // codes that require permission check
4152 IPCThreadState* ipc = IPCThreadState::self();
4153 const int pid = ipc->getCallingPid();
4154 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004155 if ((uid != AID_GRAPHICS) &&
4156 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004157 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004158 return PERMISSION_DENIED;
4159 }
4160 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161 }
chaviwa76b2712017-09-20 12:02:26 -07004162 case CAPTURE_LAYERS: {
4163 IPCThreadState* ipc = IPCThreadState::self();
4164 const int pid = ipc->getCallingPid();
4165 const int uid = ipc->getCallingUid();
4166 if ((uid != AID_GRAPHICS) &&
4167 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4168 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4169 return PERMISSION_DENIED;
4170 }
4171 break;
4172 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004174 return OK;
4175}
4176
4177status_t SurfaceFlinger::onTransact(
4178 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4179{
4180 status_t credentialCheck = CheckTransactCodeCredentials(code);
4181 if (credentialCheck != OK) {
4182 return credentialCheck;
4183 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4186 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004187 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004188 IPCThreadState* ipc = IPCThreadState::self();
4189 const int uid = ipc->getCallingUid();
4190 if (CC_UNLIKELY(uid != AID_SYSTEM
4191 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004192 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004193 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004194 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195 return PERMISSION_DENIED;
4196 }
4197 int n;
4198 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004199 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004200 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004201 return NO_ERROR;
4202 case 1002: // SHOW_UPDATES
4203 n = data.readInt32();
4204 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004205 invalidateHwcGeometry();
4206 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004207 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004209 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004210 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004211 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004212 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004213 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004214 setTransactionFlags(
4215 eTransactionNeeded|
4216 eDisplayTransactionNeeded|
4217 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004218 return NO_ERROR;
4219 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004220 case 1006:{ // send empty update
4221 signalRefresh();
4222 return NO_ERROR;
4223 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004224 case 1008: // toggle use of hw composer
4225 n = data.readInt32();
4226 mDebugDisableHWC = n ? 1 : 0;
4227 invalidateHwcGeometry();
4228 repaintEverything();
4229 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004230 case 1009: // toggle use of transform hint
4231 n = data.readInt32();
4232 mDebugDisableTransformHint = n ? 1 : 0;
4233 invalidateHwcGeometry();
4234 repaintEverything();
4235 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004236 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004237 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004238 reply->writeInt32(0);
4239 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004240 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004241 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004242 return NO_ERROR;
4243 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004244 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004245 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004246 return NO_ERROR;
4247 }
4248 case 1014: {
4249 // daltonize
4250 n = data.readInt32();
4251 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004252 case 1:
4253 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4254 break;
4255 case 2:
4256 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4257 break;
4258 case 3:
4259 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4260 break;
4261 default:
4262 mDaltonizer.setType(ColorBlindnessType::None);
4263 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004264 }
4265 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004266 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004267 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004268 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004269 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004270 invalidateHwcGeometry();
4271 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004272 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004274 case 1015: {
4275 // apply a color matrix
4276 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004277 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004278 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004279 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004280 for (size_t j = 0; j < 4; j++) {
4281 mColorMatrix[i][j] = data.readFloat();
4282 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004283 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004284 } else {
4285 mColorMatrix = mat4();
4286 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004287
4288 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4289 // the division by w in the fragment shader
4290 float4 lastRow(transpose(mColorMatrix)[3]);
4291 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4292 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4293 }
4294
Alan Viverette9c5a3332013-09-12 20:04:35 -07004295 invalidateHwcGeometry();
4296 repaintEverything();
4297 return NO_ERROR;
4298 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004299 // This is an experimental interface
4300 // Needs to be shifted to proper binder interface when we productize
4301 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004302 n = data.readInt32();
4303 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004304 return NO_ERROR;
4305 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004306 case 1017: {
4307 n = data.readInt32();
4308 mForceFullDamage = static_cast<bool>(n);
4309 return NO_ERROR;
4310 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004311 case 1018: { // Modify Choreographer's phase offset
4312 n = data.readInt32();
4313 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4314 return NO_ERROR;
4315 }
4316 case 1019: { // Modify SurfaceFlinger's phase offset
4317 n = data.readInt32();
4318 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4319 return NO_ERROR;
4320 }
Irvel468051e2016-06-13 16:44:44 -07004321 case 1020: { // Layer updates interceptor
4322 n = data.readInt32();
4323 if (n) {
4324 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004325 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004326 }
4327 else{
4328 ALOGV("Interceptor disabled");
4329 mInterceptor.disable();
4330 }
4331 return NO_ERROR;
4332 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004333 case 1021: { // Disable HWC virtual displays
4334 n = data.readInt32();
4335 mUseHwcVirtualDisplays = !n;
4336 return NO_ERROR;
4337 }
Romain Guy0147a172017-06-01 13:53:56 -07004338 case 1022: { // Set saturation boost
4339 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4340
4341 invalidateHwcGeometry();
4342 repaintEverything();
4343 return NO_ERROR;
4344 }
Romain Guy54f154a2017-10-24 21:40:32 +01004345 case 1023: { // Set native mode
4346 mForceNativeColorMode = data.readInt32() == 1;
4347
4348 invalidateHwcGeometry();
4349 repaintEverything();
4350 return NO_ERROR;
4351 }
4352 case 1024: { // Is wide color gamut rendering/color management supported?
4353 reply->writeBool(hasWideColorDisplay);
4354 return NO_ERROR;
4355 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004356 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004357 n = data.readInt32();
4358 if (n) {
4359 ALOGV("LayerTracing enabled");
4360 mTracing.enable();
4361 doTracing("tracing.enable");
4362 reply->writeInt32(NO_ERROR);
4363 } else {
4364 ALOGV("LayerTracing disabled");
4365 status_t err = mTracing.disable();
4366 reply->writeInt32(err);
4367 }
4368 return NO_ERROR;
4369 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004370 case 1026: { // Get layer tracing status
4371 reply->writeBool(mTracing.isEnabled());
4372 return NO_ERROR;
4373 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004374 }
4375 }
4376 return err;
4377}
4378
Steven Thomas6d8110b2017-08-31 18:24:21 -07004379void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004380 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004381 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004382}
4383
Steven Thomas6d8110b2017-08-31 18:24:21 -07004384void SurfaceFlinger::repaintEverything() {
4385 ConditionalLock _l(mStateLock,
4386 std::this_thread::get_id() != mMainThreadId);
4387 repaintEverythingLocked();
4388}
4389
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004390// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4391class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004392public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004393 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4394 ~WindowDisconnector() {
4395 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004396 }
4397
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004398private:
4399 ANativeWindow* mWindow;
4400 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004401};
4402
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004403status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4404 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4405 int32_t minLayerZ, int32_t maxLayerZ,
4406 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004407 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004408 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004409
chaviwa76b2712017-09-20 12:02:26 -07004410 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4411
4412 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4413 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4414
4415 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4416 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004417 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004418}
4419
4420status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004421 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004422 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004423 ATRACE_CALL();
4424
4425 class LayerRenderArea : public RenderArea {
4426 public:
Robert Carr578038f2018-03-09 12:25:24 -08004427 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4428 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4429 : RenderArea(reqHeight, reqWidth),
4430 mLayer(layer),
4431 mCrop(crop),
4432 mFlinger(flinger),
4433 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004434 Rect getBounds() const override {
4435 const Layer::State& layerState(mLayer->getDrawingState());
4436 return Rect(layerState.active.w, layerState.active.h);
4437 }
4438 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4439 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4440 bool isSecure() const override { return false; }
4441 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004442 const Transform& getTransform() const { return mTransform; }
4443
4444 class ReparentForDrawing {
4445 public:
4446 const sp<Layer>& oldParent;
4447 const sp<Layer>& newParent;
4448
4449 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4450 : oldParent(oldParent), newParent(newParent) {
4451 oldParent->reparentChildrenForDrawing(newParent);
4452 }
4453 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4454 };
4455
4456 void render(std::function<void()> drawLayers) override {
4457 if (!mChildrenOnly) {
4458 mTransform = mLayer->getTransform().inverse();
4459 drawLayers();
4460 } else {
4461 Rect bounds = getBounds();
4462 screenshotParentLayer =
4463 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4464 bounds.getWidth(), bounds.getHeight(), 0);
4465
4466 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4467 drawLayers();
4468 }
4469 }
chaviwa76b2712017-09-20 12:02:26 -07004470
chaviw7206d492017-11-10 16:16:12 -08004471 Rect getSourceCrop() const override {
4472 if (mCrop.isEmpty()) {
4473 return getBounds();
4474 } else {
4475 return mCrop;
4476 }
4477 }
chaviwa76b2712017-09-20 12:02:26 -07004478 bool getWideColorSupport() const override { return false; }
4479 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4480
4481 private:
chaviw7206d492017-11-10 16:16:12 -08004482 const sp<Layer> mLayer;
4483 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004484
4485 // In the "childrenOnly" case we reparent the children to a screenshot
4486 // layer which has no properties set and which does not draw.
4487 sp<ContainerLayer> screenshotParentLayer;
4488 Transform mTransform;
4489
4490 SurfaceFlinger* mFlinger;
4491 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004492 };
4493
4494 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4495 auto parent = layerHandle->owner.promote();
4496
chaviw7206d492017-11-10 16:16:12 -08004497 if (parent == nullptr || parent->isPendingRemoval()) {
4498 ALOGE("captureLayers called with a removed parent");
4499 return NAME_NOT_FOUND;
4500 }
4501
Robert Carr578038f2018-03-09 12:25:24 -08004502 const int uid = IPCThreadState::self()->getCallingUid();
4503 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4504 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4505 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4506 return PERMISSION_DENIED;
4507 }
4508
chaviw7206d492017-11-10 16:16:12 -08004509 Rect crop(sourceCrop);
4510 if (sourceCrop.width() <= 0) {
4511 crop.left = 0;
4512 crop.right = parent->getCurrentState().active.w;
4513 }
4514
4515 if (sourceCrop.height() <= 0) {
4516 crop.top = 0;
4517 crop.bottom = parent->getCurrentState().active.h;
4518 }
4519
4520 int32_t reqWidth = crop.width() * frameScale;
4521 int32_t reqHeight = crop.height() * frameScale;
4522
Robert Carr578038f2018-03-09 12:25:24 -08004523 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004524
Robert Carr578038f2018-03-09 12:25:24 -08004525 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004526 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4527 if (!layer->isVisible()) {
4528 return;
Robert Carr578038f2018-03-09 12:25:24 -08004529 } else if (childrenOnly && layer == parent.get()) {
4530 return;
chaviwa76b2712017-09-20 12:02:26 -07004531 }
4532 visitor(layer);
4533 });
4534 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004535 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004536}
4537
4538status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4539 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004540 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004541 bool useIdentityTransform) {
4542 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004543
chaviwa76b2712017-09-20 12:02:26 -07004544 renderArea.updateDimensions();
4545
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004546 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4547 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4548 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4549 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004550
4551 // This mutex protects syncFd and captureResult for communication of the return values from the
4552 // main thread back to this Binder thread
4553 std::mutex captureMutex;
4554 std::condition_variable captureCondition;
4555 std::unique_lock<std::mutex> captureLock(captureMutex);
4556 int syncFd = -1;
4557 std::optional<status_t> captureResult;
4558
Robert Carr03480e22018-01-04 16:02:06 -08004559 const int uid = IPCThreadState::self()->getCallingUid();
4560 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4561
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004562 sp<LambdaMessage> message = new LambdaMessage([&]() {
4563 // If there is a refresh pending, bug out early and tell the binder thread to try again
4564 // after the refresh.
4565 if (mRefreshPending) {
4566 ATRACE_NAME("Skipping screenshot for now");
4567 std::unique_lock<std::mutex> captureLock(captureMutex);
4568 captureResult = std::make_optional<status_t>(EAGAIN);
4569 captureCondition.notify_one();
4570 return;
4571 }
4572
4573 status_t result = NO_ERROR;
4574 int fd = -1;
4575 {
4576 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004577 renderArea.render([&]() {
4578 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4579 useIdentityTransform, forSystem, &fd);
4580 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004581 }
4582
4583 {
4584 std::unique_lock<std::mutex> captureLock(captureMutex);
4585 syncFd = fd;
4586 captureResult = std::make_optional<status_t>(result);
4587 captureCondition.notify_one();
4588 }
4589 });
4590
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004591 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004592 if (result == NO_ERROR) {
4593 captureCondition.wait(captureLock, [&]() { return captureResult; });
4594 while (*captureResult == EAGAIN) {
4595 captureResult.reset();
4596 result = postMessageAsync(message);
4597 if (result != NO_ERROR) {
4598 return result;
4599 }
4600 captureCondition.wait(captureLock, [&]() { return captureResult; });
4601 }
4602 result = *captureResult;
4603 }
4604
4605 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004606 sync_wait(syncFd, -1);
4607 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004608 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004609
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004610 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004611}
4612
chaviwa76b2712017-09-20 12:02:26 -07004613void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4614 TraverseLayersFunction traverseLayers, bool yswap,
4615 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004616 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004617
Lloyd Pique144e1162017-12-20 16:44:52 -08004618 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004619
4620 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004621 const auto raWidth = renderArea.getWidth();
4622 const auto raHeight = renderArea.getHeight();
4623
4624 const auto reqWidth = renderArea.getReqWidth();
4625 const auto reqHeight = renderArea.getReqHeight();
4626 Rect sourceCrop = renderArea.getSourceCrop();
4627
4628 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4629 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004630
Dan Stozac1879002014-05-22 15:59:05 -07004631 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004632 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004633 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004634 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004635 }
4636
4637 // ensure that sourceCrop is inside screen
4638 if (sourceCrop.left < 0) {
4639 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4640 }
chaviwa76b2712017-09-20 12:02:26 -07004641 if (sourceCrop.right > raWidth) {
4642 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004643 }
4644 if (sourceCrop.top < 0) {
4645 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4646 }
chaviwa76b2712017-09-20 12:02:26 -07004647 if (sourceCrop.bottom > raHeight) {
4648 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004649 }
4650
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004651 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004652 if (renderArea.getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004653 renderArea.getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
4654 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4655 }
4656 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004657
Mathias Agopian180f10d2013-04-10 22:55:41 -07004658 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004659 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004660
4661 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004662 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4663 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004664 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004665
4666 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004667 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004668
chaviwa76b2712017-09-20 12:02:26 -07004669 traverseLayers([&](Layer* layer) {
4670 if (filtering) layer->setFiltering(true);
4671 layer->draw(renderArea, useIdentityTransform);
4672 if (filtering) layer->setFiltering(false);
4673 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004674}
4675
chaviwa76b2712017-09-20 12:02:26 -07004676status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4677 TraverseLayersFunction traverseLayers,
4678 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004679 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004680 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004681 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004682 ATRACE_CALL();
4683
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004684 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004685
4686 traverseLayers([&](Layer* layer) {
4687 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4688 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004689
Robert Carr03480e22018-01-04 16:02:06 -08004690 // We allow the system server to take screenshots of secure layers for
4691 // use in situations like the Screen-rotation animation and place
4692 // the impetus on WindowManager to not persist them.
4693 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004694 ALOGW("FB is protected: PERMISSION_DENIED");
4695 return PERMISSION_DENIED;
4696 }
4697
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004698 // this binds the given EGLImage as a framebuffer for the
4699 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004700 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004701 if (bufferBond.getStatus() != NO_ERROR) {
4702 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004703 return INVALID_OPERATION;
4704 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004705
Dan Stozaabcda352017-06-01 14:37:39 -07004706 // this will in fact render into our dequeued buffer
4707 // via an FBO, which means we didn't have to create
4708 // an EGLSurface and therefore we're not
4709 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004710 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004711
Dan Stozaabcda352017-06-01 14:37:39 -07004712 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004713 getRenderEngine().finish();
4714 *outSyncFd = -1;
4715
chaviwa76b2712017-09-20 12:02:26 -07004716 const auto reqWidth = renderArea.getReqWidth();
4717 const auto reqHeight = renderArea.getReqHeight();
4718
Dan Stozaabcda352017-06-01 14:37:39 -07004719 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4720 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004721 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004722 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004723 } else {
4724 base::unique_fd syncFd = getRenderEngine().flush();
4725 if (syncFd < 0) {
4726 getRenderEngine().finish();
4727 }
4728 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004729 }
4730
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004731 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004732}
4733
Mathias Agopiand5556842013-09-19 17:08:37 -07004734void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004735 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004736 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004737 for (size_t y = 0; y < h; y++) {
4738 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4739 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004740 if (p[x] != 0xFF000000) return;
4741 }
4742 }
chaviwa76b2712017-09-20 12:02:26 -07004743 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004744
Robert Carr2047fae2016-11-28 14:09:09 -08004745 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004746 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004747 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004748 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4749 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4750 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4751 static_cast<float>(state.color.a));
4752 i++;
4753 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004754 }
4755}
4756
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004757// ---------------------------------------------------------------------------
4758
Dan Stoza412903f2017-04-27 13:42:17 -07004759void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4760 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004761}
4762
Dan Stoza412903f2017-04-27 13:42:17 -07004763void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4764 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004765}
4766
chaviwa76b2712017-09-20 12:02:26 -07004767void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4768 int32_t maxLayerZ,
4769 const LayerVector::Visitor& visitor) {
4770 // We loop through the first level of layers without traversing,
4771 // as we need to interpret min/max layer Z in the top level Z space.
4772 for (const auto& layer : mDrawingState.layersSortedByZ) {
4773 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4774 continue;
4775 }
4776 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004777 // relative layers are traversed in Layer::traverseInZOrder
4778 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004779 continue;
4780 }
4781 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004782 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4783 return;
4784 }
chaviwa76b2712017-09-20 12:02:26 -07004785 if (!layer->isVisible()) {
4786 return;
4787 }
4788 visitor(layer);
4789 });
4790 }
4791}
4792
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004794
4795
4796#if defined(__gl_h_)
4797#error "don't include gl/gl.h in this file"
4798#endif
4799
4800#if defined(__gl2_h_)
4801#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004802#endif