blob: cdf126e9e2b08eb757f2cda0575247d392e2a8e0 [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
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800166SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
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),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800196 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800197 mCreateBufferQueue(&BufferQueue::createBufferQueue) {}
198
199SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800200 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800201
202 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
203 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
204
205 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
206 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
207
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800208 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
209 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
212 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
213
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700214 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
215 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
216
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800217 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
218 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
219
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 // Vr flinger is only enabled on Daydream ready devices.
221 useVrFlinger = getBool< ISurfaceFlingerConfigs,
222 &ISurfaceFlingerConfigs::useVrFlinger>(false);
223
Fabien Sanglard1971b632017-03-10 14:50:03 -0800224 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
225 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
226
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227 hasWideColorDisplay =
228 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
229
David Sodman99974d22017-11-28 12:04:33 -0800230 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 // debugging stuff...
233 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700234
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700236 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 property_get("debug.sf.showupdates", value, "0");
239 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241 property_get("debug.sf.ddms", value, "0");
242 mDebugDDMS = atoi(value);
243 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700244 if (!startDdmConnection()) {
245 // start failed, and DDMS debugging not enabled
246 mDebugDDMS = 0;
247 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700249 ALOGI_IF(mDebugRegion, "showupdates enabled");
250 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700251
252 property_get("debug.sf.disable_backpressure", value, "0");
253 mPropagateBackpressure = !atoi(value);
254 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700255
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800256 property_get("debug.sf.enable_hwc_vds", value, "0");
257 mUseHwcVirtualDisplays = atoi(value);
258 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800259
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800260 property_get("ro.sf.disable_triple_buffer", value, "1");
261 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800262 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700263
Dan Stoza0a0158c2018-03-16 13:38:54 -0700264 // TODO (b/74616334): Reduce the default value once we isolate the leak
265 const size_t defaultListSize = 4 * MAX_LAYERS;
266 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
267 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
268
Romain Guy11d63f42017-07-20 12:47:14 -0700269 // We should be reading 'persist.sys.sf.color_saturation' here
270 // but since /data may be encrypted, we need to wait until after vold
271 // comes online to attempt to read the property. The property is
272 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800273
274 if (useTrebleTestingOverride()) {
275 // Without the override SurfaceFlinger cannot connect to HIDL
276 // services that are not listed in the manifests. Considered
277 // deriving the setting from the set service name, but it
278 // would be brittle if the name that's not 'default' is used
279 // for production purposes later on.
280 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
281 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282}
283
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800284void SurfaceFlinger::onFirstRef()
285{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800286 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800287}
288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289SurfaceFlinger::~SurfaceFlinger()
290{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291}
292
Dan Stozac7014012014-02-14 15:03:43 -0800293void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800294{
295 // the window manager died on us. prepare its eulogy.
296
Andy McFadden13a082e2012-08-24 10:16:42 -0700297 // restore initial conditions (default device unblank, etc)
298 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299
300 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700301 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800302}
303
Robert Carr1db73f62016-12-21 12:58:51 -0800304static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700305 status_t err = client->initCheck();
306 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800307 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 }
Robert Carr1db73f62016-12-21 12:58:51 -0800309 return nullptr;
310}
311
312sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
313 return initClient(new Client(this));
314}
315
316sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
317 const sp<IGraphicBufferProducer>& gbp) {
318 if (authenticateSurfaceTexture(gbp) == false) {
319 return nullptr;
320 }
321 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
322 if (layer == nullptr) {
323 return nullptr;
324 }
325
326 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327}
328
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700329sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
330 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700331{
332 class DisplayToken : public BBinder {
333 sp<SurfaceFlinger> flinger;
334 virtual ~DisplayToken() {
335 // no more references, this display must be terminated
336 Mutex::Autolock _l(flinger->mStateLock);
337 flinger->mCurrentState.displays.removeItem(this);
338 flinger->setTransactionFlags(eDisplayTransactionNeeded);
339 }
340 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700341 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700342 : flinger(flinger) {
343 }
344 };
345
346 sp<BBinder> token = new DisplayToken(this);
347
348 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700349 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700350 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700351 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800352 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700353 return token;
354}
355
Jesse Hall6c913be2013-08-08 12:15:49 -0700356void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
357 Mutex::Autolock _l(mStateLock);
358
359 ssize_t idx = mCurrentState.displays.indexOfKey(display);
360 if (idx < 0) {
361 ALOGW("destroyDisplay: invalid display token");
362 return;
363 }
364
365 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
366 if (!info.isVirtualDisplay()) {
367 ALOGE("destroyDisplay called for non-virtual display");
368 return;
369 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800370 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700371 mCurrentState.displays.removeItemsAt(idx);
372 setTransactionFlags(eDisplayTransactionNeeded);
373}
374
Mathias Agopiane57f2922012-08-09 16:29:12 -0700375sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700376 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700377 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800378 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700379 }
Jesse Hall692c7232012-11-08 15:41:56 -0800380 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381}
382
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383void SurfaceFlinger::bootFinished()
384{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700385 if (mStartPropertySetThread->join() != NO_ERROR) {
386 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800387 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388 const nsecs_t now = systemTime();
389 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000390 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700391
392 // wait patiently for the window manager death
393 const String16 name("window");
394 sp<IBinder> window(defaultServiceManager()->getService(name));
395 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700396 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700397 }
398
Steven Thomas050b2c82017-03-06 11:45:16 -0800399 if (mVrFlinger) {
400 mVrFlinger->OnBootFinished();
401 }
402
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700403 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700404 // formerly we would just kill the process, but we now ask it to exit so it
405 // can choose where to stop the animation.
406 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700407
408 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
409 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
410 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700411
Thierry Strudel2924d012017-08-14 15:19:37 -0700412 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700413 readPersistentProperties();
414 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700415 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416}
417
Mathias Agopian3f844832013-08-07 21:24:32 -0700418void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700419 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800420 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700421 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700422 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800423 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
424 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700426 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 return true;
428 }
429 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700430 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700431}
432
Lloyd Piquee83f9312018-02-01 12:53:17 -0800433class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700435 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000436 const char* name) :
437 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700438 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700439 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000440 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
441 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442 mDispSync(dispSync),
443 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700444 mVsyncMutex(),
445 mPhaseOffset(phaseOffset),
446 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700447
Lloyd Piquee83f9312018-02-01 12:53:17 -0800448 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449
Lloyd Piquee83f9312018-02-01 12:53:17 -0800450 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000453 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 static_cast<DispSync::Callback*>(this));
455 if (err != NO_ERROR) {
456 ALOGE("error registering vsync callback: %s (%d)",
457 strerror(-err), err);
458 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700459 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 } else {
461 status_t err = mDispSync->removeEventListener(
462 static_cast<DispSync::Callback*>(this));
463 if (err != NO_ERROR) {
464 ALOGE("error unregistering vsync callback: %s (%d)",
465 strerror(-err), err);
466 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700467 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 }
471
Lloyd Piquee83f9312018-02-01 12:53:17 -0800472 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 mCallback = callback;
475 }
476
Lloyd Piquee83f9312018-02-01 12:53:17 -0800477 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mVsyncMutex);
479
480 // Normalize phaseOffset to [0, period)
481 auto period = mDispSync->getPeriod();
482 phaseOffset %= period;
483 if (phaseOffset < 0) {
484 // If we're here, then phaseOffset is in (-period, 0). After this
485 // operation, it will be in (0, period)
486 phaseOffset += period;
487 }
488 mPhaseOffset = phaseOffset;
489
490 // If we're not enabled, we don't need to mess with the listeners
491 if (!mEnabled) {
492 return;
493 }
494
495 // Remove the listener with the old offset
496 status_t err = mDispSync->removeEventListener(
497 static_cast<DispSync::Callback*>(this));
498 if (err != NO_ERROR) {
499 ALOGE("error unregistering vsync callback: %s (%d)",
500 strerror(-err), err);
501 }
502
503 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 static_cast<DispSync::Callback*>(this));
506 if (err != NO_ERROR) {
507 ALOGE("error registering vsync callback: %s (%d)",
508 strerror(-err), err);
509 }
510 }
511
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512private:
513 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800514 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700516 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 callback = mCallback;
518
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700519 if (mTraceVsync) {
520 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700521 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700522 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 }
524
Peiyong Lin566a3b42018-01-09 18:22:43 -0800525 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 callback->onVSyncEvent(when);
527 }
528 }
529
Tim Murray4a4e4a22016-04-19 16:29:23 +0000530 const char* const mName;
531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 int mValue;
533
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700534 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700535 const String8 mVsyncOnLabel;
536 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700537
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700539
540 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542
543 Mutex mVsyncMutex; // Protects the following
544 nsecs_t mPhaseOffset;
545 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700546};
547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700549public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800550 InjectVSyncSource() = default;
551 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700552
Lloyd Piquee83f9312018-02-01 12:53:17 -0800553 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700554 std::lock_guard<std::mutex> lock(mCallbackMutex);
555 mCallback = callback;
556 }
557
Lloyd Piquee83f9312018-02-01 12:53:17 -0800558 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700559 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700560 if (mCallback) {
561 mCallback->onVSyncEvent(when);
562 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700563 }
564
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 void setVSyncEnabled(bool) override {}
566 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700567
568private:
569 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800570 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700571};
572
Wei Wangf9b05ee2017-07-19 20:59:39 -0700573// Do not call property_set on main thread which will be blocked by init
574// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700576 ALOGI( "SurfaceFlinger's main thread ready to run. "
577 "Initializing graphics H/W...");
578
Thierry Strudel2924d012017-08-14 15:19:37 -0700579 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800584 mEventThreadSource =
585 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
586 true, "app");
587 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
588 "appEventThread");
589 mSfEventThreadSource =
590 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
591 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800592
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800593 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
594 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800595 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800598 getBE().mRenderEngine =
599 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
600 hasWideColorDisplay
601 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
602 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800603 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700604
605 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
606 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800607 getBE().mHwc.reset(
608 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700609 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800610 // Process any initial hotplug and resulting display changes.
611 processDisplayHotplugEventsLocked();
612 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
613 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800614
Lloyd Piquefcd86612017-12-14 17:15:36 -0800615 // make the default display GLContext current so that we can create textures
616 // when creating Layers (which may happens before we render something)
617 getDefaultDisplayDeviceLocked()->makeCurrent();
618
Steven Thomas050b2c82017-03-06 11:45:16 -0800619 if (useVrFlinger) {
620 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700621 // This callback is called from the vr flinger dispatch thread. We
622 // need to call signalTransaction(), which requires holding
623 // mStateLock when we're not on the main thread. Acquiring
624 // mStateLock from the vr flinger dispatch thread might trigger a
625 // deadlock in surface flinger (see b/66916578), so post a message
626 // to be handled on the main thread instead.
627 sp<LambdaMessage> message = new LambdaMessage([=]() {
628 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
629 mVrFlingerRequestsDisplay = requestDisplay;
630 signalTransaction();
631 });
632 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 };
David Sodman105b7dc2017-11-04 20:28:14 -0700634 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
635 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800636 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 if (!mVrFlinger) {
638 ALOGE("Failed to start vrflinger");
639 }
640 }
641
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800642 mEventControlThread = std::make_unique<impl::EventControlThread>(
643 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700644
Mathias Agopian92a979a2012-08-02 18:32:23 -0700645 // initialize our drawing state
646 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700647
Andy McFadden13a082e2012-08-24 10:16:42 -0700648 // set initial conditions (e.g. unblank default device)
649 initializeDisplays();
650
David Sodmanbc815282017-11-05 18:57:52 -0800651 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700652
Wei Wangf9b05ee2017-07-19 20:59:39 -0700653 // Inform native graphics APIs whether the present timestamp is supported:
654 if (getHwComposer().hasCapability(
655 HWC2::Capability::PresentFenceIsNotReliable)) {
656 mStartPropertySetThread = new StartPropertySetThread(false);
657 } else {
658 mStartPropertySetThread = new StartPropertySetThread(true);
659 }
660
661 if (mStartPropertySetThread->Start() != NO_ERROR) {
662 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800664
Dan Stoza9e56aa02015-11-02 13:00:03 -0800665 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700666}
667
Romain Guy11d63f42017-07-20 12:47:14 -0700668void SurfaceFlinger::readPersistentProperties() {
669 char value[PROPERTY_VALUE_MAX];
670
671 property_get("persist.sys.sf.color_saturation", value, "1.0");
672 mSaturation = atof(value);
673 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100674
675 property_get("persist.sys.sf.native_mode", value, "0");
676 mForceNativeColorMode = atoi(value) == 1;
677 if (mForceNativeColorMode) {
678 ALOGV("Forcing native color mode");
679 }
Romain Guy11d63f42017-07-20 12:47:14 -0700680}
681
Mathias Agopiana67e4182012-06-19 17:26:12 -0700682void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Start boot animation service by setting a property mailbox
684 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800686 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687 if (mStartPropertySetThread->join() != NO_ERROR) {
688 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800689 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800693 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
Mathias Agopian875d8e12013-06-07 15:35:48 -0700696size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800697 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700698}
699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800701
Jamie Gennis582270d2011-08-17 18:19:00 -0700702bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800704 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800705 return authenticateSurfaceTextureLocked(bufferProducer);
706}
707
708bool SurfaceFlinger::authenticateSurfaceTextureLocked(
709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800710 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800711 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800712}
713
Brian Anderson6b376712017-04-04 10:51:39 -0700714status_t SurfaceFlinger::getSupportedFrameTimestamps(
715 std::vector<FrameEvent>* outSupported) const {
716 *outSupported = {
717 FrameEvent::REQUESTED_PRESENT,
718 FrameEvent::ACQUIRE,
719 FrameEvent::LATCH,
720 FrameEvent::FIRST_REFRESH_START,
721 FrameEvent::LAST_REFRESH_START,
722 FrameEvent::GPU_COMPOSITION_DONE,
723 FrameEvent::DEQUEUE_READY,
724 FrameEvent::RELEASE,
725 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700726 ConditionalLock _l(mStateLock,
727 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700728 if (!getHwComposer().hasCapability(
729 HWC2::Capability::PresentFenceIsNotReliable)) {
730 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
731 }
732 return NO_ERROR;
733}
734
Dan Stoza7f7da322014-05-02 15:26:25 -0700735status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
736 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800737 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 return BAD_VALUE;
739 }
740
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500741 if (!display.get())
742 return NAME_NOT_FOUND;
743
Jesse Hall692c7232012-11-08 15:41:56 -0800744 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700745 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800746 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700747 type = i;
748 break;
749 }
750 }
751
752 if (type < 0) {
753 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700754 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 // TODO: Not sure if display density should handled by SF any longer
757 class Density {
758 static int getDensityFromProperty(char const* propName) {
759 char property[PROPERTY_VALUE_MAX];
760 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800761 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 density = atoi(property);
763 }
764 return density;
765 }
766 public:
767 static int getEmuDensity() {
768 return getDensityFromProperty("qemu.sf.lcd_density"); }
769 static int getBuildDensity() {
770 return getDensityFromProperty("ro.sf.lcd_density"); }
771 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700774
Steven Thomas6d8110b2017-08-31 18:24:21 -0700775 ConditionalLock _l(mStateLock,
776 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 DisplayInfo info = DisplayInfo();
779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 float xdpi = hwConfig->getDpiX();
781 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700782
783 if (type == DisplayDevice::DISPLAY_PRIMARY) {
784 // The density of the device is provided by a build property
785 float density = Density::getBuildDensity() / 160.0f;
786 if (density == 0) {
787 // the build doesn't provide a density -- this is wrong!
788 // use xdpi instead
789 ALOGE("ro.sf.lcd_density must be defined as a build property");
790 density = xdpi / 160.0f;
791 }
792 if (Density::getEmuDensity()) {
793 // if "qemu.sf.lcd_density" is specified, it overrides everything
794 xdpi = ydpi = density = Density::getEmuDensity();
795 density /= 160.0f;
796 }
797 info.density = density;
798
799 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800801 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 } else {
803 // TODO: where should this value come from?
804 static const int TV_DENSITY = 213;
805 info.density = TV_DENSITY / 160.0f;
806 info.orientation = 0;
807 }
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.w = hwConfig->getWidth();
810 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 info.xdpi = xdpi;
812 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900814 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815
Andy McFadden91b2ca82014-06-13 14:04:23 -0700816 // This is how far in advance a buffer must be queued for
817 // presentation at a given time. If you want a buffer to appear
818 // on the screen at time N, you must submit the buffer before
819 // (N - presentationDeadline).
820 //
821 // Normally it's one full refresh period (to give SF a chance to
822 // latch the buffer), but this can be reduced by configuring a
823 // DispSync offset. Any additional delays introduced by the hardware
824 // composer or panel must be accounted for here.
825 //
826 // We add an additional 1ms to allow for processing time and
827 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800829 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
831 // All non-virtual displays are currently considered secure.
832 info.secure = true;
833
Michael Wright28f24d02016-07-12 13:30:53 -0700834 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return NO_ERROR;
838}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700839
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800840status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800842 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700843 return BAD_VALUE;
844 }
845
846 // FIXME for now we always return stats for the primary display
847 memset(stats, 0, sizeof(*stats));
848 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
849 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
850 return NO_ERROR;
851}
852
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700853int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800854 if (display == nullptr) {
855 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800856 return BAD_VALUE;
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
859 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800860 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700861 return device->getActiveConfig();
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
Dan Stoza24a42e92015-03-09 10:04:11 -0700864 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700867void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
868 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
869 this);
870 int32_t type = hw->getDisplayType();
871 int currentMode = hw->getActiveConfig();
872
873 if (mode == currentMode) {
874 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
875 return;
876 }
877
878 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
879 ALOGW("Trying to set config for virtual display");
880 return;
881 }
882
883 hw->setActiveConfig(mode);
884 getHwComposer().setActiveConfig(type, mode);
885}
886
887status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
888 class MessageSetActiveConfig: public MessageBase {
889 SurfaceFlinger& mFlinger;
890 sp<IBinder> mDisplay;
891 int mMode;
892 public:
893 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
894 int mode) :
895 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
896 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700897 Vector<DisplayInfo> configs;
898 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700899 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700900 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700902 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700903 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800905 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700907 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
909 ALOGW("Attempt to set active config = %d for virtual display",
910 mMode);
911 } else {
912 mFlinger.setActiveConfigInternal(hw, mMode);
913 }
914 return true;
915 }
916 };
917 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
918 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700919 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700920}
Michael Wright28f24d02016-07-12 13:30:53 -0700921status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700922 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700923 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
924 return BAD_VALUE;
925 }
926
927 if (!display.get()) {
928 return NAME_NOT_FOUND;
929 }
930
931 int32_t type = NAME_NOT_FOUND;
932 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
933 if (display == mBuiltinDisplays[i]) {
934 type = i;
935 break;
936 }
937 }
938
939 if (type < 0) {
940 return type;
941 }
942
Peiyong Lina52f0292018-03-14 17:26:31 -0700943 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700944 {
945 ConditionalLock _l(mStateLock,
946 std::this_thread::get_id() != mMainThreadId);
947 modes = getHwComposer().getColorModes(type);
948 }
Michael Wright28f24d02016-07-12 13:30:53 -0700949 outColorModes->clear();
950 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
951
952 return NO_ERROR;
953}
954
Peiyong Lina52f0292018-03-14 17:26:31 -0700955ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700957 if (device != nullptr) {
958 return device->getActiveColorMode();
959 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700960 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700961}
962
963void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700964 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700965 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700966 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700967
968 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700969 return;
970 }
971
972 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
973 ALOGW("Trying to set config for virtual display");
974 return;
975 }
976
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600977 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
978 hw->getDisplayType());
979
Michael Wright28f24d02016-07-12 13:30:53 -0700980 hw->setActiveColorMode(mode);
981 getHwComposer().setActiveColorMode(type, mode);
982}
983
984
985status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700986 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700987 class MessageSetActiveColorMode: public MessageBase {
988 SurfaceFlinger& mFlinger;
989 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -0700991 public:
992 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -0700994 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
995 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -0700997 mFlinger.getDisplayColorModes(mDisplay, &modes);
998 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -0700999 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001000 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1001 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001002 return true;
1003 }
1004 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1005 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1007 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001009 ALOGW("Attempt to set active color mode %s %d for virtual display",
1010 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001011 } else {
1012 mFlinger.setActiveColorModeInternal(hw, mMode);
1013 }
1014 return true;
1015 }
1016 };
1017 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1018 postMessageSync(msg);
1019 return NO_ERROR;
1020}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001021
Svetoslavd85084b2014-03-20 10:28:31 -07001022status_t SurfaceFlinger::clearAnimationFrameStats() {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.clearStats();
1025 return NO_ERROR;
1026}
1027
1028status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1029 Mutex::Autolock _l(mStateLock);
1030 mAnimFrameTracker.getStats(outStats);
1031 return NO_ERROR;
1032}
1033
Dan Stozac4f471e2016-03-24 09:31:08 -07001034status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1035 HdrCapabilities* outCapabilities) const {
1036 Mutex::Autolock _l(mStateLock);
1037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001038 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001039 if (displayDevice == nullptr) {
1040 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1041 return BAD_VALUE;
1042 }
1043
1044 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001045 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001046 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001047 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1048 // insert HDR10 as we will force client composition for HDR10
1049 // layers
1050 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1051 types.push_back(HAL_HDR_HDR10);
1052
1053 *outCapabilities = HdrCapabilities(types,
1054 capabilities->getDesiredMaxLuminance(),
1055 capabilities->getDesiredMaxAverageLuminance(),
1056 capabilities->getDesiredMinLuminance());
1057 } else {
1058 *outCapabilities = std::move(*capabilities);
1059 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001060 } else {
1061 return BAD_VALUE;
1062 }
1063
1064 return NO_ERROR;
1065}
1066
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1069 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 if (mInjectVSyncs == enable) {
1072 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001074
1075 if (enable) {
1076 ALOGV("VSync Injections enabled");
1077 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001078 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001079 mInjectorEventThread =
1080 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1081 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001083 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 } else {
1085 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001086 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 }
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001090 });
1091 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
1097
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 if (!mInjectVSyncs) {
1099 ALOGE("VSync Injections not enabled");
1100 return BAD_VALUE;
1101 }
1102 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1103 ALOGV("Injecting VSync inside SurfaceFlinger");
1104 mVSyncInjector->onInjectSyncEvent(when);
1105 }
1106 return NO_ERROR;
1107}
1108
Lloyd Pique755e3192018-01-31 16:46:15 -08001109status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1110 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001111 IPCThreadState* ipc = IPCThreadState::self();
1112 const int pid = ipc->getCallingPid();
1113 const int uid = ipc->getCallingUid();
1114 if ((uid != AID_SHELL) &&
1115 !PermissionCache::checkPermission(sDump, pid, uid)) {
1116 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1117 return PERMISSION_DENIED;
1118 }
1119
1120 // Try to acquire a lock for 1s, fail gracefully
1121 const status_t err = mStateLock.timedLock(s2ns(1));
1122 const bool locked = (err == NO_ERROR);
1123 if (!locked) {
1124 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1125 return TIMED_OUT;
1126 }
1127
1128 outLayers->clear();
1129 mCurrentState.traverseInZOrder([&](Layer* layer) {
1130 outLayers->push_back(layer->getLayerDebugInfo());
1131 });
1132
1133 mStateLock.unlock();
1134 return NO_ERROR;
1135}
1136
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001137// ----------------------------------------------------------------------------
1138
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001139sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1140 ISurfaceComposer::VsyncSource vsyncSource) {
1141 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1142 return mSFEventThread->createEventConnection();
1143 } else {
1144 return mEventThread->createEventConnection();
1145 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001146}
1147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001148// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149
1150void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001151 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152}
1153
1154void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001155 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156}
1157
1158void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001159 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160}
1161
1162void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001163 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001164 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165}
1166
1167status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001168 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001169 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001170}
1171
1172status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001173 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001174 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175 if (res == NO_ERROR) {
1176 msg->wait();
1177 }
1178 return res;
1179}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001180
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001181void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001182 do {
1183 waitForEvent();
1184 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185}
1186
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187void SurfaceFlinger::enableHardwareVsync() {
1188 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001191 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1192 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001194 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195}
1196
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 Mutex::Autolock _l(mHWVsyncLock);
1199
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 if (makeAvailable) {
1201 mHWVsyncAvailable = true;
1202 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001203 // Hardware vsync is not currently available, so abort the resync
1204 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001205 return;
1206 }
1207
David Sodman105b7dc2017-11-04 20:28:14 -07001208 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210
1211 mPrimaryDispSync.reset();
1212 mPrimaryDispSync.setPeriod(period);
1213
1214 if (!mPrimaryHWVsyncEnabled) {
1215 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1217 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryHWVsyncEnabled = true;
1219 }
1220}
1221
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 Mutex::Autolock _l(mHWVsyncLock);
1224 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1226 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 mPrimaryDispSync.endResync();
1228 mPrimaryHWVsyncEnabled = false;
1229 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230 if (makeUnavailable) {
1231 mHWVsyncAvailable = false;
1232 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233}
1234
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235void SurfaceFlinger::resyncWithRateLimit() {
1236 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001237
1238 // No explicit locking is needed here since EventThread holds a lock while calling this method
1239 static nsecs_t sLastResyncAttempted = 0;
1240 const nsecs_t now = systemTime();
1241 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001242 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001243 }
Dan Stoza57164302017-05-08 14:03:54 -07001244 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001245}
1246
Steven Thomasb02664d2017-07-26 18:48:28 -07001247void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1248 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001250 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001251 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001252 return;
1253 }
1254
1255 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001256 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001257 return;
1258 }
1259
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 { // Scope for the lock
1263 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001264 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001265 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001268
1269 if (needsHwVsync) {
1270 enableHardwareVsync();
1271 } else {
1272 disableHardwareVsync(false);
1273 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001274}
1275
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001277 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1278 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279}
1280
Lloyd Pique715a2c12017-12-14 17:18:08 -08001281void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1282 HWC2::Connection connection) {
1283 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1284 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285
Lloyd Piqueba04e622017-12-14 17:11:26 -08001286 // Ignore events that do not have the right sequenceId.
1287 if (sequenceId != getBE().mComposerSequenceId) {
1288 return;
1289 }
1290
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 // Only lock if we're not on the main thread. This function is normally
1292 // called on a hwbinder thread, but for the primary display it's called on
1293 // the main thread with the state lock already held, so don't attempt to
1294 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001295 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001296
Lloyd Pique715a2c12017-12-14 17:18:08 -08001297 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001298
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001299 if (std::this_thread::get_id() == mMainThreadId) {
1300 // Process all pending hot plug events immediately if we are on the main thread.
1301 processDisplayHotplugEventsLocked();
1302 }
1303
Lloyd Piqueba04e622017-12-14 17:11:26 -08001304 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001305}
1306
Steven Thomasb02664d2017-07-26 18:48:28 -07001307void SurfaceFlinger::onRefreshReceived(int sequenceId,
1308 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001309 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001313 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001314}
1315
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001318 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 getHwComposer().setVsyncEnabled(disp,
1320 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001321}
1322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001324void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326 // Clear the drawing state so that the logic inside of
1327 // handleTransactionLocked will fire. It will determine the delta between
1328 // mCurrentState and mDrawingState and re-apply all changes when we make the
1329 // transition.
1330 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001331 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332 mDisplays.clear();
1333}
1334
Steven Thomas050b2c82017-03-06 11:45:16 -08001335void SurfaceFlinger::updateVrFlinger() {
1336 if (!mVrFlinger)
1337 return;
1338 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001340 return;
1341 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342
David Sodman105b7dc2017-11-04 20:28:14 -07001343 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 ALOGE("Vr flinger is only supported for remote hardware composer"
1345 " service connections. Ignoring request to transition to vr"
1346 " flinger.");
1347 mVrFlingerRequestsDisplay = false;
1348 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001349 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 int currentDisplayPowerMode = getDisplayDeviceLocked(
1354 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001361 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001362 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1363 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001364 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
David Sodman105b7dc2017-11-04 20:28:14 -07001366 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1367 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001368
1369 if (vrFlingerRequestsDisplay) {
1370 mVrFlinger->GrantDisplayOwnership();
1371 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374
1375 mVisibleRegionsDirty = true;
1376 invalidateHwcGeometry();
1377
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001378 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1380 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1381 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001384 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 const nsecs_t period = activeConfig->getVsyncPeriod();
1386 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 // Use phase of 0 since phase is not known.
1389 // Use latency of 0, which will snap to the ideal latency.
1390 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392 android_atomic_or(1, &mRepaintEverything);
1393 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394}
1395
Mathias Agopian4fec8732012-06-29 14:12:52 -07001396void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001397 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001398 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001399 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001400 bool frameMissed = !mHadClientComposition &&
1401 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001402 (mPreviousPresentFence->getSignalTime() ==
1403 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001404 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001405 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001406 signalLayerUpdate();
1407 break;
1408 }
1409
Steven Thomas050b2c82017-03-06 11:45:16 -08001410 // Now that we're going to make it to the handleMessageTransaction()
1411 // call below it's safe to call updateVrFlinger(), which will
1412 // potentially trigger a display handoff.
1413 updateVrFlinger();
1414
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 bool refreshNeeded = handleMessageTransaction();
1416 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001417 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001419 // Signal a refresh if a transaction modified the window state,
1420 // a new buffer was latched, or if HWC has requested a full
1421 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001422 signalRefresh();
1423 }
1424 break;
1425 }
1426 case MessageQueue::REFRESH: {
1427 handleMessageRefresh();
1428 break;
1429 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001430 }
1431}
1432
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001434 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001436 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001437 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001438 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001439 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001440}
1441
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445}
1446
1447void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001448 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001449
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001450 mRefreshPending = false;
1451
Pablo Ceballos40845df2016-01-25 17:41:15 -08001452 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001453
Brian Andersond6927fb2016-07-23 23:37:30 -07001454 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001455 rebuildLayerStacks();
1456 setUpHWComposer();
1457 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001458 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001459 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001460 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001461
David Sodman105b7dc2017-11-04 20:28:14 -07001462 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001463
1464 mHadClientComposition = false;
1465 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1466 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1467 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001468 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001469 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001470
Dan Stoza9e56aa02015-11-02 13:00:03 -08001471 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473
Mathias Agopiancd60f992012-08-16 16:28:27 -07001474void SurfaceFlinger::doDebugFlashRegions()
1475{
1476 // is debugging enabled
1477 if (CC_LIKELY(!mDebugRegion))
1478 return;
1479
1480 const bool repaintEverything = mRepaintEverything;
1481 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1482 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001483 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 // transform the dirty region into this screen's coordinate space
1485 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1486 if (!dirtyRegion.isEmpty()) {
1487 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001488 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001489
1490 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001492 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001493 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1494
Mathias Agopianda27af92012-09-13 18:17:13 -07001495 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001496 }
1497 }
1498 }
1499
1500 postFramebuffer();
1501
1502 if (mDebugRegion > 1) {
1503 usleep(mDebugRegion * 1000);
1504 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001505
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001507 auto& displayDevice = mDisplays[displayId];
1508 if (!displayDevice->isDisplayOn()) {
1509 continue;
1510 }
1511
David Sodman105b7dc2017-11-04 20:28:14 -07001512 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1513 ALOGE_IF(result != NO_ERROR,
1514 "prepareFrame for display %zd failed:"
1515 " %d (%s)",
1516 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001517 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518}
1519
Adrian Roos1e1a1282017-11-01 19:05:31 +01001520void SurfaceFlinger::doTracing(const char* where) {
1521 ATRACE_CALL();
1522 ATRACE_NAME(where);
1523 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001524 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001525 }
1526}
1527
Brian Andersond6927fb2016-07-23 23:37:30 -07001528void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001530 ATRACE_CALL();
1531 ALOGV("preComposition");
1532
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001534 mDrawingState.traverseInZOrder([&](Layer* layer) {
1535 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536 needExtraInvalidate = true;
1537 }
Robert Carr2047fae2016-11-28 14:09:09 -08001538 });
1539
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540 if (needExtraInvalidate) {
1541 signalLayerUpdate();
1542 }
1543}
1544
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001545void SurfaceFlinger::updateCompositorTiming(
1546 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1547 std::shared_ptr<FenceTime>& presentFenceTime) {
1548 // Update queue of past composite+present times and determine the
1549 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001550 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001552 while (!getBE().mCompositePresentTimes.empty()) {
1553 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001554 // Cached values should have been updated before calling this method,
1555 // which helps avoid duplicate syscalls.
1556 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1557 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1558 break;
1559 }
1560 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001561 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562 }
1563
1564 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001565 while (getBE().mCompositePresentTimes.size() > 16) {
1566 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001567 }
1568
Brian Andersond0010582017-03-07 13:20:31 -08001569 setCompositorTimingSnapped(
1570 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1571}
1572
1573void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1574 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001575 // Integer division and modulo round toward 0 not -inf, so we need to
1576 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001577 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001578 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1579 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1580
Brian Andersond0010582017-03-07 13:20:31 -08001581 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1582 if (idealLatency <= 0) {
1583 idealLatency = vsyncInterval;
1584 }
1585
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001586 // Snap the latency to a value that removes scheduling jitter from the
1587 // composition and present times, which often have >1ms of jitter.
1588 // Reducing jitter is important if an app attempts to extrapolate
1589 // something (such as user input) to an accurate diasplay time.
1590 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1591 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001592 nsecs_t bias = vsyncInterval / 2;
1593 int64_t extraVsyncs =
1594 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1595 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1596 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001597
David Sodman99974d22017-11-28 12:04:33 -08001598 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1599 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1600 getBE().mCompositorTiming.interval = vsyncInterval;
1601 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602}
1603
1604void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001606 ATRACE_CALL();
1607 ALOGV("postComposition");
1608
Brian Anderson3546a3f2016-07-14 11:51:14 -07001609 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001610 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001611 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001612 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001613 }
1614
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001615 // |mStateLock| not needed as we are on the main thread
1616 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001617
David Sodman73beded2017-11-15 11:56:06 -08001618 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001619 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001620 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001621 glCompositionDoneFenceTime =
1622 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001623 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001624 } else {
1625 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1626 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001627
David Sodman73beded2017-11-15 11:56:06 -08001628 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001629 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001630 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001631 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001632
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1634 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1635
1636 // We use the refreshStartTime which might be sampled a little later than
1637 // when we started doing work for this frame, but that should be okay
1638 // since updateCompositorTiming has snapping logic.
1639 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001640 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001641 CompositorTiming compositorTiming;
1642 {
David Sodman99974d22017-11-28 12:04:33 -08001643 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1644 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001645 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646
Robert Carr2047fae2016-11-28 14:09:09 -08001647 mDrawingState.traverseInZOrder([&](Layer* layer) {
1648 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001649 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001650 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001651 recordBufferingStats(layer->getName().string(),
1652 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001653 }
Robert Carr2047fae2016-11-28 14:09:09 -08001654 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001655
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001656 if (presentFenceTime->isValid()) {
1657 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001658 enableHardwareVsync();
1659 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001660 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001661 }
1662 }
1663
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001664 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001665 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001666 enableHardwareVsync();
1667 }
1668 }
1669
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001670 if (mAnimCompositionPending) {
1671 mAnimCompositionPending = false;
1672
Brian Anderson4e606e32017-03-16 15:34:57 -07001673 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001674 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001675 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001676 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001677 // The HWC doesn't support present fences, so use the refresh
1678 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001679 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001680 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001681 mAnimFrameTracker.setActualPresentTime(presentTime);
1682 }
1683 mAnimFrameTracker.advanceFrame();
1684 }
Dan Stozab90cf072015-03-05 11:05:59 -08001685
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001686 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1687 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001688 return;
1689 }
1690
1691 nsecs_t currentTime = systemTime();
1692 if (mHasPoweredOff) {
1693 mHasPoweredOff = false;
1694 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001695 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001697 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1698 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001699 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001700 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001701 }
David Sodman4a36e932017-11-07 14:29:47 -08001702 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001703 }
David Sodman4a36e932017-11-07 14:29:47 -08001704 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705}
1706
1707void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 ATRACE_CALL();
1709 ALOGV("rebuildLayerStacks");
1710
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001712 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001713 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001714 mVisibleRegionsDirty = false;
1715 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001716
Jeff Sharkey76488112017-02-27 14:15:18 -07001717 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1718 Region opaqueRegion;
1719 Region dirtyRegion;
1720 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001721 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1723 const Transform& tr(displayDevice->getTransform());
1724 const Rect bounds(displayDevice->getBounds());
1725 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001726 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001727
Jeff Sharkey76488112017-02-27 14:15:18 -07001728 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001729 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001730 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1731 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001732 Region drawRegion(tr.transform(
1733 layer->visibleNonTransparentRegion));
1734 drawRegion.andSelf(bounds);
1735 if (!drawRegion.isEmpty()) {
1736 layersSortedByZ.add(layer);
1737 } else {
1738 // Clear out the HWC layer if this layer was
1739 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001740 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001741 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001742 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001743 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001744 // WM changes displayDevice->layerStack upon sleep/awake.
1745 // Here we make sure we delete the HWC layers even if
1746 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001747 hwcLayerDestroyed = layer->destroyHwcLayer(
1748 displayDevice->getHwcDisplayId());
1749 }
1750
1751 // If a layer is not going to get a release fence because
1752 // it is invisible, but it is also going to release its
1753 // old buffer, add it to the list of layers needing
1754 // fences.
1755 if (hwcLayerDestroyed) {
1756 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1757 mLayersWithQueuedFrames.cend(), layer);
1758 if (found != mLayersWithQueuedFrames.cend()) {
1759 layersNeedingFences.add(layer);
1760 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001761 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 });
1763 }
1764 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001765 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001766 displayDevice->undefinedRegion.set(bounds);
1767 displayDevice->undefinedRegion.subtractSelf(
1768 tr.transform(opaqueRegion));
1769 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001770 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001771 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001772}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001773
Romain Guy0147a172017-06-01 13:53:56 -07001774mat4 SurfaceFlinger::computeSaturationMatrix() const {
1775 if (mSaturation == 1.0f) {
1776 return mat4();
1777 }
1778
1779 // Rec.709 luma coefficients
1780 float3 luminance{0.213f, 0.715f, 0.072f};
1781 luminance *= 1.0f - mSaturation;
1782 return mat4(
1783 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1784 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1785 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1786 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1787 );
1788}
1789
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001790// pickColorMode translates a given dataspace into the best available color mode.
1791// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001792ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001793 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001794 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001795 }
1796
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001797 switch (dataSpace) {
1798 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1799 // system expects.
1800 case HAL_DATASPACE_UNKNOWN:
1801 case HAL_DATASPACE_SRGB:
1802 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001803 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001804 break;
1805
1806 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001807 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001808 break;
1809
1810 default:
1811 // TODO (courtneygo): Do we want to assert an error here?
1812 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1813 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001814 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001815 break;
1816 }
1817}
1818
Romain Guy0147a172017-06-01 13:53:56 -07001819android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001820 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001821 // Only support sRGB and Display-P3 right now.
1822 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1823 return HAL_DATASPACE_DISPLAY_P3;
1824 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001825 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1826 return HAL_DATASPACE_DISPLAY_P3;
1827 }
1828 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1829 return HAL_DATASPACE_DISPLAY_P3;
1830 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001831 if (!hasHdr) {
1832 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1833 return HAL_DATASPACE_DISPLAY_P3;
1834 }
1835 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1836 return HAL_DATASPACE_DISPLAY_P3;
1837 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001838 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001839
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001840 return HAL_DATASPACE_V0_SRGB;
1841}
1842
Mathias Agopiancd60f992012-08-16 16:28:27 -07001843void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 ATRACE_CALL();
1845 ALOGV("setUpHWComposer");
1846
Jesse Hall028dc8f2013-08-20 16:35:32 -07001847 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001848 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1849 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1850 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1851
1852 // If nothing has changed (!dirty), don't recompose.
1853 // If something changed, but we don't currently have any visible layers,
1854 // and didn't when we last did a composition, then skip it this time.
1855 // The second rule does two things:
1856 // - When all layers are removed from a display, we'll emit one black
1857 // frame, then nothing more until we get new layers.
1858 // - When a display is created with a private layer stack, we won't
1859 // emit any black frames until a layer is added to the layer stack.
1860 bool mustRecompose = dirty && !(empty && wasEmpty);
1861
1862 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1863 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1864 mustRecompose ? "doing" : "skipping",
1865 dirty ? "+" : "-",
1866 empty ? "+" : "-",
1867 wasEmpty ? "+" : "-");
1868
Dan Stoza71433162014-02-04 16:22:36 -08001869 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001870
1871 if (mustRecompose) {
1872 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1873 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001874 }
1875
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 // build the h/w work list
1877 if (CC_UNLIKELY(mGeometryInvalid)) {
1878 mGeometryInvalid = false;
1879 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1880 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1881 const auto hwcId = displayDevice->getHwcDisplayId();
1882 if (hwcId >= 0) {
1883 const Vector<sp<Layer>>& currentLayers(
1884 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001885 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001886 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001888 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001891 }
1892 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001893
Robert Carrae060832016-11-28 10:51:00 -08001894 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001895 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001897 }
1898 }
1899 }
1900 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 }
Riley Andrews03414a12014-07-01 14:22:59 -07001902
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001903
Romain Guy0147a172017-06-01 13:53:56 -07001904 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001905
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 // Set the per-frame data
1907 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1908 auto& displayDevice = mDisplays[displayId];
1909 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001910
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 if (hwcId < 0) {
1912 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001913 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001914 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001915 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001916 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1917 "display %zd: %d", displayId, result);
1918 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001920 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1921 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001922 !displayDevice->getHdrSupport()) {
1923 layer->forceClientComposition(hwcId);
1924 }
1925
chaviwc9232ed2017-11-14 15:31:15 -08001926 if (layer->getForceClientComposition(hwcId)) {
1927 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1928 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1929 continue;
1930 }
1931
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 layer->setPerFrameData(displayDevice);
1933 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001934
1935 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001936 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1938
1939 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001940 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1941 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001942 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1943 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1944 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1945 }
1946 newColorMode = pickColorMode(newDataSpace);
1947
Thierry Strudel2924d012017-08-14 15:19:37 -07001948 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001949 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 }
1951
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001952 mPreviousColorMatrix = colorMatrix;
1953
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001955 auto& displayDevice = mDisplays[displayId];
1956 if (!displayDevice->isDisplayOn()) {
1957 continue;
1958 }
1959
David Sodman105b7dc2017-11-04 20:28:14 -07001960 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1962 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001963 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001964}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001965
Mathias Agopiancd60f992012-08-16 16:28:27 -07001966void SurfaceFlinger::doComposition() {
1967 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 ALOGV("doComposition");
1969
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001970 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001971 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001972 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001973 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974 // transform the dirty region into this screen's coordinate space
1975 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001976
1977 // repaint the framebuffer (if needed)
1978 doDisplayComposition(hw, dirtyRegion);
1979
Mathias Agopiancd60f992012-08-16 16:28:27 -07001980 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001981 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001982 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001983 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001984 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001985}
1986
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987void SurfaceFlinger::postFramebuffer()
1988{
Mathias Agopian841cde52012-03-01 15:44:37 -08001989 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001991
Mathias Agopiana44b0412011-10-16 18:46:35 -07001992 const nsecs_t now = systemTime();
1993 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001994
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1996 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001997 if (!displayDevice->isDisplayOn()) {
1998 continue;
1999 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 const auto hwcId = displayDevice->getHwcDisplayId();
2001 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002002 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002003 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002004 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002005 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002007 // The layer buffer from the previous frame (if any) is released
2008 // by HWC only when the release fence from this frame (if any) is
2009 // signaled. Always get the release fence from HWC first.
2010 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002011 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002012
2013 // If the layer was client composited in the previous frame, we
2014 // need to merge with the previous client target acquire fence.
2015 // Since we do not track that, always merge with the current
2016 // client target acquire fence when it is available, even though
2017 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002019 releaseFence = Fence::merge("LayerRelease", releaseFence,
2020 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002021 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002022
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 layer->onLayerDisplayed(releaseFence);
2024 }
Chia-I Wu83806892017-11-16 10:50:20 -08002025
2026 // We've got a list of layers needing fences, that are disjoint with
2027 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2028 // supply them with the present fence.
2029 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002030 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002031 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2032 layer->onLayerDisplayed(presentFence);
2033 }
2034 }
2035
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002037 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002038 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002039 }
2040
Mathias Agopiana44b0412011-10-16 18:46:35 -07002041 mLastSwapBufferTime = systemTime() - now;
2042 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002043
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002044 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002045 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2046 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2047 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2048 logFrameStats();
2049 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002050 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051}
2052
Mathias Agopian87baae12012-07-31 12:38:26 -07002053void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002054{
Mathias Agopian841cde52012-03-01 15:44:37 -08002055 ATRACE_CALL();
2056
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002057 // here we keep a copy of the drawing state (that is the state that's
2058 // going to be overwritten by handleTransactionLocked()) outside of
2059 // mStateLock so that the side-effects of the State assignment
2060 // don't happen with mStateLock held (which can cause deadlocks).
2061 State drawingState(mDrawingState);
2062
Mathias Agopianca4d3602011-05-19 15:38:14 -07002063 Mutex::Autolock _l(mStateLock);
2064 const nsecs_t now = systemTime();
2065 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066
Mathias Agopianca4d3602011-05-19 15:38:14 -07002067 // Here we're guaranteed that some transaction flags are set
2068 // so we can call handleTransactionLocked() unconditionally.
2069 // We call getTransactionFlags(), which will also clear the flags,
2070 // with mStateLock held to guarantee that mCurrentState won't change
2071 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002072
Mathias Agopiane57f2922012-08-09 16:29:12 -07002073 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002074 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002075
Mathias Agopianca4d3602011-05-19 15:38:14 -07002076 mLastTransactionTime = systemTime() - now;
2077 mDebugInTransaction = 0;
2078 invalidateHwcGeometry();
2079 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002080}
2081
Lloyd Pique715a2c12017-12-14 17:18:08 -08002082DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2083 HWC2::Connection connection) const {
2084 // Figure out whether the event is for the primary display or an
2085 // external display by matching the Hwc display id against one for a
2086 // connected display. If we did not find a match, we then check what
2087 // displays are not already connected to determine the type. If we don't
2088 // have a connected primary display, we assume the new display is meant to
2089 // be the primary display, and then if we don't have an external display,
2090 // we assume it is that.
2091 const auto primaryDisplayId =
2092 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2093 const auto externalDisplayId =
2094 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2095 if (primaryDisplayId && primaryDisplayId == display) {
2096 return DisplayDevice::DISPLAY_PRIMARY;
2097 } else if (externalDisplayId && externalDisplayId == display) {
2098 return DisplayDevice::DISPLAY_EXTERNAL;
2099 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2100 return DisplayDevice::DISPLAY_PRIMARY;
2101 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2102 return DisplayDevice::DISPLAY_EXTERNAL;
2103 }
2104
2105 return DisplayDevice::DISPLAY_ID_INVALID;
2106}
2107
Lloyd Piqueba04e622017-12-14 17:11:26 -08002108void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2109 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002110 auto displayType = determineDisplayType(event.display, event.connection);
2111 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2112 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2113 continue;
2114 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002115
2116 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2117 ALOGE("External displays are not supported by the vr hardware composer.");
2118 continue;
2119 }
2120
Lloyd Pique715a2c12017-12-14 17:18:08 -08002121 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002122
2123 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002124 if (!mBuiltinDisplays[displayType].get()) {
2125 ALOGV("Creating built in display %d", displayType);
2126 mBuiltinDisplays[displayType] = new BBinder();
2127 // All non-virtual displays are currently considered secure.
2128 DisplayDeviceState info(displayType, true);
2129 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2130 "Built-in Screen" : "External Screen";
2131 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002132 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002133 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002134 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002135 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002136
Lloyd Piquefcd86612017-12-14 17:15:36 -08002137 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2138 if (idx >= 0) {
2139 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002140 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002141 mCurrentState.displays.removeItemsAt(idx);
2142 }
2143 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002144 }
2145
2146 processDisplayChangesLocked();
2147 }
2148
2149 mPendingHotplugEvents.clear();
2150}
2151
Lloyd Pique347200f2017-12-14 17:00:15 -08002152void SurfaceFlinger::processDisplayChangesLocked() {
2153 // here we take advantage of Vector's copy-on-write semantics to
2154 // improve performance by skipping the transaction entirely when
2155 // know that the lists are identical
2156 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2157 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2158 if (!curr.isIdenticalTo(draw)) {
2159 mVisibleRegionsDirty = true;
2160 const size_t cc = curr.size();
2161 size_t dc = draw.size();
2162
2163 // find the displays that were removed
2164 // (ie: in drawing state but not in current state)
2165 // also handle displays that changed
2166 // (ie: displays that are in both lists)
2167 for (size_t i = 0; i < dc;) {
2168 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2169 if (j < 0) {
2170 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002171 // Call makeCurrent() on the primary display so we can
2172 // be sure that nothing associated with this display
2173 // is current.
2174 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2175 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2176 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2177 if (hw != nullptr) hw->disconnect(getHwComposer());
2178 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2179 mEventThread->onHotplugReceived(draw[i].type, false);
2180 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002181 } else {
2182 // this display is in both lists. see if something changed.
2183 const DisplayDeviceState& state(curr[j]);
2184 const wp<IBinder>& display(curr.keyAt(j));
2185 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2186 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2187 if (state_binder != draw_binder) {
2188 // changing the surface is like destroying and
2189 // recreating the DisplayDevice, so we just remove it
2190 // from the drawing state, so that it get re-added
2191 // below.
2192 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2193 if (hw != nullptr) hw->disconnect(getHwComposer());
2194 mDisplays.removeItem(display);
2195 mDrawingState.displays.removeItemsAt(i);
2196 dc--;
2197 // at this point we must loop to the next item
2198 continue;
2199 }
2200
2201 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2202 if (disp != nullptr) {
2203 if (state.layerStack != draw[i].layerStack) {
2204 disp->setLayerStack(state.layerStack);
2205 }
2206 if ((state.orientation != draw[i].orientation) ||
2207 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2208 disp->setProjection(state.orientation, state.viewport, state.frame);
2209 }
2210 if (state.width != draw[i].width || state.height != draw[i].height) {
2211 disp->setDisplaySize(state.width, state.height);
2212 }
2213 }
2214 }
2215 ++i;
2216 }
2217
2218 // find displays that were added
2219 // (ie: in current state but not in drawing state)
2220 for (size_t i = 0; i < cc; i++) {
2221 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2222 const DisplayDeviceState& state(curr[i]);
2223
2224 sp<DisplaySurface> dispSurface;
2225 sp<IGraphicBufferProducer> producer;
2226 sp<IGraphicBufferProducer> bqProducer;
2227 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002228 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002229
2230 int32_t hwcId = -1;
2231 if (state.isVirtualDisplay()) {
2232 // Virtual displays without a surface are dormant:
2233 // they have external state (layer stack, projection,
2234 // etc.) but no internal state (i.e. a DisplayDevice).
2235 if (state.surface != nullptr) {
2236 // Allow VR composer to use virtual displays.
2237 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2238 int width = 0;
2239 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2240 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2241 int height = 0;
2242 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2243 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2244 int intFormat = 0;
2245 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2246 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2247 auto format = static_cast<android_pixel_format_t>(intFormat);
2248
2249 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2250 }
2251
2252 // TODO: Plumb requested format back up to consumer
2253
2254 sp<VirtualDisplaySurface> vds =
2255 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2256 bqProducer, bqConsumer,
2257 state.displayName);
2258
2259 dispSurface = vds;
2260 producer = vds;
2261 }
2262 } else {
2263 ALOGE_IF(state.surface != nullptr,
2264 "adding a supported display, but rendering "
2265 "surface is provided (%p), ignoring it",
2266 state.surface.get());
2267
2268 hwcId = state.type;
2269 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2270 producer = bqProducer;
2271 }
2272
2273 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002274
Lloyd Pique347200f2017-12-14 17:00:15 -08002275 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002276 bool hasWideColorSupport = false;
2277 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002278 std::vector<ColorMode> modes =
Lloyd Piquefcd86612017-12-14 17:15:36 -08002279 getHwComposer().getColorModes(state.type);
Peiyong Lina52f0292018-03-14 17:26:31 -07002280 for (ColorMode colorMode : modes) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002281 switch (colorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002282 case ColorMode::DISPLAY_P3:
2283 case ColorMode::ADOBE_RGB:
2284 case ColorMode::DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002285 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002286 break;
2287 default:
2288 break;
2289 }
2290 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002291 }
2292
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002293 bool hasHdrSupport = false;
2294 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2295 getHwComposer().getHdrCapabilities(state.type);
2296 if (hdrCapabilities) {
2297 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2298 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2299 hasHdrSupport = iter != types.cend();
2300 }
2301
Lloyd Pique347200f2017-12-14 17:00:15 -08002302 sp<DisplayDevice> hw =
2303 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002304 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002305 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306
Peiyong Lina52f0292018-03-14 17:26:31 -07002307 ColorMode defaultColorMode = ColorMode::NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002308 if (hasWideColorSupport) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002309 defaultColorMode = ColorMode::SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002310 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002311 setActiveColorModeInternal(hw, defaultColorMode);
2312 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002313 hw->setLayerStack(state.layerStack);
2314 hw->setProjection(state.orientation, state.viewport, state.frame);
2315 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002316
Lloyd Pique347200f2017-12-14 17:00:15 -08002317 mDisplays.add(display, hw);
2318 if (!state.isVirtualDisplay()) {
2319 mEventThread->onHotplugReceived(state.type, true);
2320 }
2321 }
2322 }
2323 }
2324 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002325
2326 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002327}
2328
Mathias Agopian87baae12012-07-31 12:38:26 -07002329void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002330{
Dan Stoza7dde5992015-05-22 09:51:44 -07002331 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002332 mCurrentState.traverseInZOrder([](Layer* layer) {
2333 layer->notifyAvailableFrames();
2334 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 /*
2337 * Traversal of the children
2338 * (perform the transaction for each of them if needed)
2339 */
2340
Mathias Agopian3559b072012-08-15 13:46:03 -07002341 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002342 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002344 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345
2346 const uint32_t flags = layer->doTransaction(0);
2347 if (flags & Layer::eVisibleRegion)
2348 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002349 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350 }
2351
2352 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002353 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354 */
2355
Mathias Agopiane57f2922012-08-09 16:29:12 -07002356 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002357 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002358 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002359 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360
Mathias Agopian84300952012-11-21 16:02:13 -08002361 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2362 // The transform hint might have changed for some layers
2363 // (either because a display has changed, or because a layer
2364 // as changed).
2365 //
2366 // Walk through all the layers in currentLayers,
2367 // and update their transform hint.
2368 //
2369 // If a layer is visible only on a single display, then that
2370 // display is used to calculate the hint, otherwise we use the
2371 // default display.
2372 //
2373 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2374 // the hint is set before we acquire a buffer from the surface texture.
2375 //
2376 // NOTE: layer transactions have taken place already, so we use their
2377 // drawing state. However, SurfaceFlinger's own transaction has not
2378 // happened yet, so we must use the current state layer list
2379 // (soon to become the drawing state list).
2380 //
2381 sp<const DisplayDevice> disp;
2382 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002383 bool first = true;
2384 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002385 // NOTE: we rely on the fact that layers are sorted by
2386 // layerStack first (so we don't have to traverse the list
2387 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002388 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002389 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002390 currentlayerStack = layerStack;
2391 // figure out if this layerstack is mirrored
2392 // (more than one display) if so, pick the default display,
2393 // if not, pick the only display it's on.
2394 disp.clear();
2395 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2396 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002397 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002398 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002399 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002400 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002401 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002402 break;
2403 }
2404 }
2405 }
2406 }
Chet Haase91d25932013-04-11 15:24:55 -07002407
Robert Carr56a0b9a2017-12-04 16:06:13 -08002408 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002409 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002410 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2411 // redraw after transform hint changes. See bug 8508397.
2412
2413 // could be null when this layer is using a layerStack
2414 // that is not visible on any display. Also can occur at
2415 // screen off/on times.
2416 disp = getDefaultDisplayDeviceLocked();
2417 }
2418 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002419 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002420 if (disp != nullptr) {
2421 layer->updateTransformHint(disp);
2422 }
Robert Carr2047fae2016-11-28 14:09:09 -08002423
2424 first = false;
2425 });
Mathias Agopian84300952012-11-21 16:02:13 -08002426 }
2427
2428
Mathias Agopian3559b072012-08-15 13:46:03 -07002429 /*
2430 * Perform our own transaction if needed
2431 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002432
2433 if (mLayersAdded) {
2434 mLayersAdded = false;
2435 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002436 mVisibleRegionsDirty = true;
2437 }
2438
2439 // some layers might have been removed, so
2440 // we need to update the regions they're exposing.
2441 if (mLayersRemoved) {
2442 mLayersRemoved = false;
2443 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002444 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002445 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002446 // this layer is not visible anymore
2447 // TODO: we could traverse the tree from front to back and
2448 // compute the actual visible region
2449 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 Region visibleReg;
2451 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002452 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002453 }
Robert Carr2047fae2016-11-28 14:09:09 -08002454 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455 }
2456
2457 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002458
2459 updateCursorAsync();
2460}
2461
2462void SurfaceFlinger::updateCursorAsync()
2463{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2465 auto& displayDevice = mDisplays[displayId];
2466 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002467 continue;
2468 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469
2470 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2471 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002472 }
2473 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002474}
2475
2476void SurfaceFlinger::commitTransaction()
2477{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002478 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002479 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002480 for (const auto& l : mLayersPendingRemoval) {
2481 recordBufferingStats(l->getName().string(),
2482 l->getOccupancyHistory(true));
2483 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002484 }
2485 mLayersPendingRemoval.clear();
2486 }
2487
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002488 // If this transaction is part of a window animation then the next frame
2489 // we composite should be considered an animation as well.
2490 mAnimCompositionPending = mAnimTransactionPending;
2491
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002493 mDrawingState.traverseInZOrder([](Layer* layer) {
2494 layer->commitChildList();
2495 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002496 mTransactionPending = false;
2497 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002498 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499}
2500
Chia-I Wuab0c3192017-08-01 11:29:00 -07002501void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002502 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503{
Mathias Agopian841cde52012-03-01 15:44:37 -08002504 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002505 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507 Region aboveOpaqueLayers;
2508 Region aboveCoveredLayers;
2509 Region dirty;
2510
Mathias Agopian87baae12012-07-31 12:38:26 -07002511 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512
Robert Carr2047fae2016-11-28 14:09:09 -08002513 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002515 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516
Jesse Hall01e29052013-02-19 16:13:35 -08002517 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002518 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002519 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002520
Mathias Agopianab028732010-03-16 16:41:46 -07002521 /*
2522 * opaqueRegion: area of a surface that is fully opaque.
2523 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002525
2526 /*
2527 * visibleRegion: area of a surface that is visible on screen
2528 * and not fully transparent. This is essentially the layer's
2529 * footprint minus the opaque regions above it.
2530 * Areas covered by a translucent surface are considered visible.
2531 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002533
2534 /*
2535 * coveredRegion: area of a surface that is covered by all
2536 * visible regions above it (which includes the translucent areas).
2537 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002539
Jesse Halla8026d22012-09-25 13:25:04 -07002540 /*
2541 * transparentRegion: area of a surface that is hinted to be completely
2542 * transparent. This is only used to tell when the layer has no visible
2543 * non-transparent regions and can be removed from the layer list. It
2544 * does not affect the visibleRegion of this layer or any layers
2545 * beneath it. The hint may not be correct if apps don't respect the
2546 * SurfaceView restrictions (which, sadly, some don't).
2547 */
2548 Region transparentRegion;
2549
Mathias Agopianab028732010-03-16 16:41:46 -07002550
2551 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002552 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002553 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002556 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002557 if (!visibleRegion.isEmpty()) {
2558 // Remove the transparent area from the visible region
2559 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002560 if (tr.preserveRects()) {
2561 // transform the transparent region
2562 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002564 // transformation too complex, can't do the
2565 // transparent region optimization.
2566 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002567 }
Mathias Agopianab028732010-03-16 16:41:46 -07002568 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569
Mathias Agopianab028732010-03-16 16:41:46 -07002570 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002571 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002572 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002573 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2574 // the opaque region is the layer's footprint
2575 opaqueRegion = visibleRegion;
2576 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 }
2578 }
2579
Robert Carre5f4f692018-01-12 13:12:28 -08002580 if (visibleRegion.isEmpty()) {
2581 layer->clearVisibilityRegions();
2582 return;
2583 }
2584
Mathias Agopianab028732010-03-16 16:41:46 -07002585 // Clip the covered region to the visible region
2586 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2587
2588 // Update aboveCoveredLayers for next (lower) layer
2589 aboveCoveredLayers.orSelf(visibleRegion);
2590
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 // subtract the opaque region covered by the layers above us
2592 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593
2594 // compute this layer's dirty region
2595 if (layer->contentDirty) {
2596 // we need to invalidate the whole region
2597 dirty = visibleRegion;
2598 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002599 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 layer->contentDirty = false;
2601 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002602 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002603 * the exposed region consists of two components:
2604 * 1) what's VISIBLE now and was COVERED before
2605 * 2) what's EXPOSED now less what was EXPOSED before
2606 *
2607 * note that (1) is conservative, we start with the whole
2608 * visible region but only keep what used to be covered by
2609 * something -- which mean it may have been exposed.
2610 *
2611 * (2) handles areas that were not covered by anything but got
2612 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002613 */
Mathias Agopianab028732010-03-16 16:41:46 -07002614 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002615 const Region oldVisibleRegion = layer->visibleRegion;
2616 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002617 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2618 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 }
2620 dirty.subtractSelf(aboveOpaqueLayers);
2621
2622 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002623 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624
Mathias Agopianab028732010-03-16 16:41:46 -07002625 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002627
Jesse Halla8026d22012-09-25 13:25:04 -07002628 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 layer->setVisibleRegion(visibleRegion);
2630 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002631 layer->setVisibleNonTransparentRegion(
2632 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002633 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
Mathias Agopian87baae12012-07-31 12:38:26 -07002635 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636}
2637
Chia-I Wuab0c3192017-08-01 11:29:00 -07002638void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002639 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002640 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002641 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002642 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002643 }
2644 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002645}
2646
Dan Stoza6b9454d2014-11-07 16:00:59 -08002647bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 ALOGV("handlePageFlip");
2650
Brian Andersond6927fb2016-07-23 23:37:30 -07002651 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652
Mathias Agopian4fec8732012-06-29 14:12:52 -07002653 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002654 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002655 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002656
2657 // Store the set of layers that need updates. This set must not change as
2658 // buffers are being latched, as this could result in a deadlock.
2659 // Example: Two producers share the same command stream and:
2660 // 1.) Layer 0 is latched
2661 // 2.) Layer 0 gets a new frame
2662 // 2.) Layer 1 gets a new frame
2663 // 3.) Layer 1 is latched.
2664 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2665 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002666 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002667 if (layer->hasQueuedFrame()) {
2668 frameQueued = true;
2669 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002670 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002671 } else {
2672 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002673 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002674 } else {
2675 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002676 }
Robert Carr2047fae2016-11-28 14:09:09 -08002677 });
2678
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002680 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002681 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002682 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002683 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002684 newDataLatched = true;
2685 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002686 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002687
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002688 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689
2690 // If we will need to wake up at some time in the future to deal with a
2691 // queued frame that shouldn't be displayed during this vsync period, wake
2692 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002693 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002694 signalLayerUpdate();
2695 }
2696
2697 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002698 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699}
2700
Mathias Agopianad456f92011-01-13 17:53:01 -08002701void SurfaceFlinger::invalidateHwcGeometry()
2702{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002704}
2705
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002706
Fabien Sanglard830b8472016-11-30 16:35:58 -08002707void SurfaceFlinger::doDisplayComposition(
2708 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002709 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710{
Dan Stoza71433162014-02-04 16:22:36 -08002711 // We only need to actually compose the display if:
2712 // 1) It is being handled by hardware composer, which may need this to
2713 // keep its virtual display state machine in sync, or
2714 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002715 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002716 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002718 return;
2719 }
2720
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002722 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002723
2724 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002725 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726}
2727
Chia-I Wub02087d2017-11-09 10:19:54 -08002728bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002729{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002731
Chia-I Wub02087d2017-11-09 10:19:54 -08002732 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002733 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002735
2736 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002737 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2738 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002739 if (applyColorMatrix) {
2740 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2741 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2742 }
2743
David Sodman105b7dc2017-11-04 20:28:14 -07002744 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 if (hasClientComposition) {
2746 ALOGV("hasClientComposition");
2747
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002748 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002749 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002750 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002751 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2752 }
2753 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2754
Chia-I Wu7f402902017-11-09 12:51:10 -08002755 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002756 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002758 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002759
2760 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002761 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002762 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2763 }
2764 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002765 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002766
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002767 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002768 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002770 // when using overlays, we assume a fully transparent framebuffer
2771 // NOTE: we could reduce how much we need to clear, for instance
2772 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002773 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002774 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002775 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002776 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002777 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002778 // we're left with the letterbox region
2779 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002781
2782 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002784
Mathias Agopianb9494d52012-04-18 02:28:45 -07002785 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002786 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002787 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002788 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002789 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002790 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002791
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002793 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002794 // scissor on the main display. It should never be needed
2795 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 const Rect& bounds(displayDevice->getBounds());
2797 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002798 if (scissor != bounds) {
2799 // scissor doesn't match the screen's dimensions, so we
2800 // need to clear everything outside of it and enable
2801 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002802
Mathias Agopianf45c5102012-10-24 16:29:17 -07002803 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002805 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002806 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002807 }
2808 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002809 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002810
Mathias Agopian85d751c2012-08-29 16:59:24 -07002811 /*
2812 * and then, render the layers targeted at the framebuffer
2813 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002814
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("Rendering client layers");
2816 const Transform& displayTransform = displayDevice->getTransform();
2817 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002818 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 bool firstLayer = true;
2820 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002821 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 displayTransform.transform(layer->visibleRegion)));
2823 ALOGV("Layer: %s", layer->getName().string());
2824 ALOGV(" Composition type: %s",
2825 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002826 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 switch (layer->getCompositionType(hwcId)) {
2828 case HWC2::Composition::Cursor:
2829 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002830 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002832 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002834 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002836 // never clear the very first layer since we're
2837 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002838 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002839 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002840 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002841 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002843 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002844 break;
2845 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002847 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002848 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 } else {
2850 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002851 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002852 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002853 }
2854 } else {
2855 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002857 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002859 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002860 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002861 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002862 }
2863 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002864
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002865 if (applyColorMatrix) {
2866 getRenderEngine().setupColorTransform(oldColorMatrix);
2867 }
2868
Mathias Agopianf45c5102012-10-24 16:29:17 -07002869 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002870 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002871 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Fabien Sanglard830b8472016-11-30 16:35:58 -08002874void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2875 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002876 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002877 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878}
2879
Dan Stoza7d89d062015-04-30 13:29:25 -07002880status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002881 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002882 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 const sp<Layer>& lbc,
2884 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002885{
Dan Stoza7d89d062015-04-30 13:29:25 -07002886 // add this layer to the current state list
2887 {
2888 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002890 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2891 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002892 return NO_MEMORY;
2893 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 if (parent == nullptr) {
2895 mCurrentState.layersSortedByZ.add(lbc);
2896 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002897 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002898 ALOGE("addClientLayer called with a removed parent");
2899 return NAME_NOT_FOUND;
2900 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901 parent->addChild(lbc);
2902 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002903
Dan Stoza101d8dc2018-02-27 15:42:25 -08002904 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002905 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2906 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2907 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2908 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2909 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910 mLayersAdded = true;
2911 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002912 }
2913
Mathias Agopian96f08192010-06-02 23:28:45 -07002914 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002915 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002916
Dan Stoza7d89d062015-04-30 13:29:25 -07002917 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002918}
2919
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002920status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002921 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002922 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2923}
Robert Carr7f9b8992017-03-10 11:08:39 -08002924
chaviwca27f252018-02-06 16:46:39 -08002925status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2926 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002927 if (layer->isPendingRemoval()) {
2928 return NO_ERROR;
2929 }
2930
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002932 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002933 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002934 if (topLevelOnly) {
2935 return NO_ERROR;
2936 }
2937
Chia-I Wu98f1c102017-05-30 14:54:08 -07002938 sp<Layer> ancestor = p;
2939 while (ancestor->getParent() != nullptr) {
2940 ancestor = ancestor->getParent();
2941 }
2942 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2943 ALOGE("removeLayer called with a layer whose parent has been removed");
2944 return NAME_NOT_FOUND;
2945 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002946
2947 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002948 } else {
2949 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002950 }
2951
Robert Carr136e2f62017-02-08 17:54:29 -08002952 // As a matter of normal operation, the LayerCleaner will produce a second
2953 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2954 // so we will succeed in promoting it, but it's already been removed
2955 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2956 // otherwise something has gone wrong and we are leaking the layer.
2957 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002958 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2959 layer->getName().string(),
2960 (p != nullptr) ? p->getName().string() : "no-parent");
2961 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002962 } else if (index < 0) {
2963 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002964 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002965
Chia-I Wuc6657022017-08-15 11:18:17 -07002966 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002967 mLayersPendingRemoval.add(layer);
2968 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002969 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002970 setTransactionFlags(eTransactionNeeded);
2971 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972}
2973
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002974uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002975 return android_atomic_release_load(&mTransactionFlags);
2976}
2977
Mathias Agopian3f844832013-08-07 21:24:32 -07002978uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2980}
2981
Mathias Agopian3f844832013-08-07 21:24:32 -07002982uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2984 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002985 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 }
2987 return old;
2988}
2989
chaviwca27f252018-02-06 16:46:39 -08002990bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
2991 for (const ComposerState& state : states) {
2992 // Here we need to check that the interface we're given is indeed
2993 // one of our own. A malicious client could give us a nullptr
2994 // IInterface, or one of its own or even one of our own but a
2995 // different type. All these situations would cause us to crash.
2996 if (state.client == nullptr) {
2997 return true;
2998 }
2999
3000 sp<IBinder> binder = IInterface::asBinder(state.client);
3001 if (binder == nullptr) {
3002 return true;
3003 }
3004
3005 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3006 return true;
3007 }
3008 }
3009 return false;
3010}
3011
Mathias Agopian8b33f032012-07-24 20:43:54 -07003012void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003013 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003014 const Vector<DisplayState>& displays,
3015 uint32_t flags)
3016{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003017 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003018 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003019 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020
chaviwca27f252018-02-06 16:46:39 -08003021 if (containsAnyInvalidClientState(states)) {
3022 return;
3023 }
3024
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003025 if (flags & eAnimation) {
3026 // For window updates that are part of an animation we must wait for
3027 // previous animation "frames" to be handled.
3028 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003029 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003030 if (CC_UNLIKELY(err != NO_ERROR)) {
3031 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003032 // caller after a few seconds.
3033 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3034 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003035 mAnimTransactionPending = false;
3036 break;
3037 }
3038 }
3039 }
3040
chaviwca27f252018-02-06 16:46:39 -08003041 for (const DisplayState& display : displays) {
3042 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003043 }
3044
chaviwca27f252018-02-06 16:46:39 -08003045 for (const ComposerState& state : states) {
3046 transactionFlags |= setClientStateLocked(state);
3047 }
3048
3049 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3050 // as destroyed should only occur after setting all other states. This is to allow for a
3051 // child re-parent to happen before marking its original parent as destroyed (which would
3052 // then mark the child as destroyed).
3053 for (const ComposerState& state : states) {
3054 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003055 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003056
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003057 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3058 // anyway. This can be used as a flush mechanism for previous async transactions.
3059 // Empty animation transaction can be used to simulate back-pressure, so also force a
3060 // transaction for empty animation transactions.
3061 if (transactionFlags == 0 &&
3062 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003063 transactionFlags = eTransactionNeeded;
3064 }
3065
Mathias Agopian386aa982011-11-07 21:58:03 -08003066 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003067 if (mInterceptor->isEnabled()) {
3068 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003069 }
Irvel468051e2016-06-13 16:44:44 -07003070
Mathias Agopian386aa982011-11-07 21:58:03 -08003071 // this triggers the transaction
3072 setTransactionFlags(transactionFlags);
3073
3074 // if this is a synchronous transaction, wait for it to take effect
3075 // before returning.
3076 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003077 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003078 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003079 if (flags & eAnimation) {
3080 mAnimTransactionPending = true;
3081 }
3082 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003083 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3084 if (CC_UNLIKELY(err != NO_ERROR)) {
3085 // just in case something goes wrong in SF, return to the
3086 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003087 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3088 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003089 break;
3090 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003091 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 }
3093}
3094
Mathias Agopiane57f2922012-08-09 16:29:12 -07003095uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3096{
Jesse Hall9a143922012-10-04 16:29:19 -07003097 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3098 if (dpyIdx < 0)
3099 return 0;
3100
Mathias Agopiane57f2922012-08-09 16:29:12 -07003101 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003102 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003103 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003104 const uint32_t what = s.what;
3105 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003106 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003107 disp.surface = s.surface;
3108 flags |= eDisplayTransactionNeeded;
3109 }
3110 }
3111 if (what & DisplayState::eLayerStackChanged) {
3112 if (disp.layerStack != s.layerStack) {
3113 disp.layerStack = s.layerStack;
3114 flags |= eDisplayTransactionNeeded;
3115 }
3116 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003117 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003118 if (disp.orientation != s.orientation) {
3119 disp.orientation = s.orientation;
3120 flags |= eDisplayTransactionNeeded;
3121 }
3122 if (disp.frame != s.frame) {
3123 disp.frame = s.frame;
3124 flags |= eDisplayTransactionNeeded;
3125 }
3126 if (disp.viewport != s.viewport) {
3127 disp.viewport = s.viewport;
3128 flags |= eDisplayTransactionNeeded;
3129 }
3130 }
Michael Lentine47e45402014-07-18 15:34:25 -07003131 if (what & DisplayState::eDisplaySizeChanged) {
3132 if (disp.width != s.width) {
3133 disp.width = s.width;
3134 flags |= eDisplayTransactionNeeded;
3135 }
3136 if (disp.height != s.height) {
3137 disp.height = s.height;
3138 flags |= eDisplayTransactionNeeded;
3139 }
3140 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003141 }
3142 return flags;
3143}
3144
chaviwca27f252018-02-06 16:46:39 -08003145uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3146 const layer_state_t& s = composerState.state;
3147 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3148
Mathias Agopian13127d82013-03-05 17:47:11 -08003149 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003150 if (layer == nullptr) {
3151 return 0;
3152 }
3153
3154 if (layer->isPendingRemoval()) {
3155 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3156 return 0;
3157 }
3158
3159 uint32_t flags = 0;
3160
3161 const uint32_t what = s.what;
3162 bool geometryAppliesWithResize =
3163 what & layer_state_t::eGeometryAppliesWithResize;
3164 if (what & layer_state_t::ePositionChanged) {
3165 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3166 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003167 }
chaviw8b3871a2017-11-01 17:41:01 -07003168 }
3169 if (what & layer_state_t::eLayerChanged) {
3170 // NOTE: index needs to be calculated before we update the state
3171 const auto& p = layer->getParent();
3172 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003173 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003174 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003175 mCurrentState.layersSortedByZ.removeAt(idx);
3176 mCurrentState.layersSortedByZ.add(layer);
3177 // we need traversal (state changed)
3178 // AND transaction (list changed)
3179 flags |= eTransactionNeeded|eTraversalNeeded;
3180 }
chaviw8b3871a2017-11-01 17:41:01 -07003181 } else {
3182 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003183 flags |= eTransactionNeeded|eTraversalNeeded;
3184 }
3185 }
chaviw8b3871a2017-11-01 17:41:01 -07003186 }
3187 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003188 // NOTE: index needs to be calculated before we update the state
3189 const auto& p = layer->getParent();
3190 if (p == nullptr) {
3191 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3192 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3193 mCurrentState.layersSortedByZ.removeAt(idx);
3194 mCurrentState.layersSortedByZ.add(layer);
3195 // we need traversal (state changed)
3196 // AND transaction (list changed)
3197 flags |= eTransactionNeeded|eTraversalNeeded;
3198 }
3199 } else {
3200 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3201 flags |= eTransactionNeeded|eTraversalNeeded;
3202 }
chaviw8b3871a2017-11-01 17:41:01 -07003203 }
3204 }
3205 if (what & layer_state_t::eSizeChanged) {
3206 if (layer->setSize(s.w, s.h)) {
3207 flags |= eTraversalNeeded;
3208 }
3209 }
3210 if (what & layer_state_t::eAlphaChanged) {
3211 if (layer->setAlpha(s.alpha))
3212 flags |= eTraversalNeeded;
3213 }
3214 if (what & layer_state_t::eColorChanged) {
3215 if (layer->setColor(s.color))
3216 flags |= eTraversalNeeded;
3217 }
3218 if (what & layer_state_t::eMatrixChanged) {
3219 if (layer->setMatrix(s.matrix))
3220 flags |= eTraversalNeeded;
3221 }
3222 if (what & layer_state_t::eTransparentRegionChanged) {
3223 if (layer->setTransparentRegionHint(s.transparentRegion))
3224 flags |= eTraversalNeeded;
3225 }
3226 if (what & layer_state_t::eFlagsChanged) {
3227 if (layer->setFlags(s.flags, s.mask))
3228 flags |= eTraversalNeeded;
3229 }
3230 if (what & layer_state_t::eCropChanged) {
3231 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3232 flags |= eTraversalNeeded;
3233 }
3234 if (what & layer_state_t::eFinalCropChanged) {
3235 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3236 flags |= eTraversalNeeded;
3237 }
3238 if (what & layer_state_t::eLayerStackChanged) {
3239 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3240 // We only allow setting layer stacks for top level layers,
3241 // everything else inherits layer stack from its parent.
3242 if (layer->hasParent()) {
3243 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3244 layer->getName().string());
3245 } else if (idx < 0) {
3246 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3247 "that also does not appear in the top level layer list. Something"
3248 " has gone wrong.", layer->getName().string());
3249 } else if (layer->setLayerStack(s.layerStack)) {
3250 mCurrentState.layersSortedByZ.removeAt(idx);
3251 mCurrentState.layersSortedByZ.add(layer);
3252 // we need traversal (state changed)
3253 // AND transaction (list changed)
3254 flags |= eTransactionNeeded|eTraversalNeeded;
3255 }
3256 }
3257 if (what & layer_state_t::eDeferTransaction) {
3258 if (s.barrierHandle != nullptr) {
3259 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3260 } else if (s.barrierGbp != nullptr) {
3261 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3262 if (authenticateSurfaceTextureLocked(gbp)) {
3263 const auto& otherLayer =
3264 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3265 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3266 } else {
3267 ALOGE("Attempt to defer transaction to to an"
3268 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003269 }
3270 }
chaviw8b3871a2017-11-01 17:41:01 -07003271 // We don't trigger a traversal here because if no other state is
3272 // changed, we don't want this to cause any more work
3273 }
3274 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003275 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003276 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003277 if (!hadParent) {
3278 mCurrentState.layersSortedByZ.remove(layer);
3279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003281 }
chaviw8b3871a2017-11-01 17:41:01 -07003282 }
3283 if (what & layer_state_t::eReparentChildren) {
3284 if (layer->reparentChildren(s.reparentHandle)) {
3285 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003286 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 }
chaviw8b3871a2017-11-01 17:41:01 -07003288 if (what & layer_state_t::eDetachChildren) {
3289 layer->detachChildren();
3290 }
3291 if (what & layer_state_t::eOverrideScalingModeChanged) {
3292 layer->setOverrideScalingMode(s.overrideScalingMode);
3293 // We don't trigger a traversal here because if no other state is
3294 // changed, we don't want this to cause any more work
3295 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003296 return flags;
3297}
3298
chaviwca27f252018-02-06 16:46:39 -08003299void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3300 const layer_state_t& state = composerState.state;
3301 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3302
3303 sp<Layer> layer(client->getLayerUser(state.surface));
3304 if (layer == nullptr) {
3305 return;
3306 }
3307
3308 if (layer->isPendingRemoval()) {
3309 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3310 return;
3311 }
3312
3313 if (state.what & layer_state_t::eDestroySurface) {
3314 removeLayerLocked(mStateLock, layer);
3315 }
3316}
3317
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003318status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003319 const String8& name,
3320 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003321 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003322 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3323 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003325 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003326 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003327 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003328 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003329 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003330
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003331 status_t result = NO_ERROR;
3332
3333 sp<Layer> layer;
3334
Cody Northropbc755282017-03-31 12:00:08 -06003335 String8 uniqueName = getUniqueLayerName(name);
3336
Mathias Agopian3165cc22012-08-08 19:42:09 -07003337 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3338 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003339 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003340 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003341 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003343 break;
chaviw13fdc492017-06-27 12:40:18 -07003344 case ISurfaceComposerClient::eFXSurfaceColor:
3345 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003346 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003347 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003348 break;
3349 default:
3350 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 break;
3352 }
3353
Dan Stoza7d89d062015-04-30 13:29:25 -07003354 if (result != NO_ERROR) {
3355 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003357
Chia-I Wuab0c3192017-08-01 11:29:00 -07003358 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3359 // TODO b/64227542
3360 if (windowType == 441731) {
3361 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3362 layer->setPrimaryDisplayOnly();
3363 }
3364
Albert Chaulk479c60c2017-01-27 14:21:34 -05003365 layer->setInfo(windowType, ownerUid);
3366
Robert Carr1f0a16a2016-10-24 16:27:39 -07003367 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003368 if (result != NO_ERROR) {
3369 return result;
3370 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003371 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003372
3373 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003374 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375}
3376
Cody Northropbc755282017-03-31 12:00:08 -06003377String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3378{
3379 bool matchFound = true;
3380 uint32_t dupeCounter = 0;
3381
3382 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3383 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3384
3385 // Loop over layers until we're sure there is no matching name
3386 while (matchFound) {
3387 matchFound = false;
3388 mDrawingState.traverseInZOrder([&](Layer* layer) {
3389 if (layer->getName() == uniqueName) {
3390 matchFound = true;
3391 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3392 }
3393 });
3394 }
3395
3396 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3397
3398 return uniqueName;
3399}
3400
David Sodman0c69cad2017-08-21 12:12:51 -07003401status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003402 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3403 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003404{
3405 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003406 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003407 case PIXEL_FORMAT_TRANSPARENT:
3408 case PIXEL_FORMAT_TRANSLUCENT:
3409 format = PIXEL_FORMAT_RGBA_8888;
3410 break;
3411 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003412 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 break;
3414 }
3415
David Sodman0c69cad2017-08-21 12:12:51 -07003416 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3417 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003418 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003419 *handle = layer->getHandle();
3420 *gbp = layer->getProducer();
3421 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003423
David Sodman0c69cad2017-08-21 12:12:51 -07003424 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003425 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003426}
3427
chaviw13fdc492017-06-27 12:40:18 -07003428status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003429 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003430 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003431{
chaviw13fdc492017-06-27 12:40:18 -07003432 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003433 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003434 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003435}
3436
Mathias Agopianac9fa422013-02-11 16:40:36 -08003437status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438{
Robert Carr9524cb32017-02-13 11:32:32 -08003439 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003440 status_t err = NO_ERROR;
3441 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003442 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003443 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003444 err = removeLayer(l);
3445 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3446 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003447 }
3448 return err;
3449}
3450
Mathias Agopian13127d82013-03-05 17:47:11 -08003451status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003452{
Mathias Agopian67106042013-03-14 19:18:13 -07003453 // called by ~LayerCleaner() when all references to the IBinder (handle)
3454 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003455 sp<Layer> l = layer.promote();
3456 if (l == nullptr) {
3457 // The layer has already been removed, carry on
3458 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003459 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003460 // If we have a parent, then we can continue to live as long as it does.
3461 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003462}
3463
Mathias Agopianb60314a2012-04-10 22:09:54 -07003464// ---------------------------------------------------------------------------
3465
Andy McFadden13a082e2012-08-24 10:16:42 -07003466void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003467 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003468 Vector<ComposerState> state;
3469 Vector<DisplayState> displays;
3470 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003471 d.what = DisplayState::eDisplayProjectionChanged |
3472 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003473 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003474 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003475 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003476 d.frame.makeInvalid();
3477 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003478 d.width = 0;
3479 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003480 displays.add(d);
3481 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003482 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3483 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003484
David Sodman105b7dc2017-11-04 20:28:14 -07003485 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003486 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003487 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003488
Brian Andersond0010582017-03-07 13:20:31 -08003489 // Use phase of 0 since phase is not known.
3490 // Use latency of 0, which will snap to the ideal latency.
3491 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003492}
3493
3494void SurfaceFlinger::initializeDisplays() {
3495 class MessageScreenInitialized : public MessageBase {
3496 SurfaceFlinger* flinger;
3497 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003498 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003499 virtual bool handler() {
3500 flinger->onInitializeDisplays();
3501 return true;
3502 }
3503 };
3504 sp<MessageBase> msg = new MessageScreenInitialized(this);
3505 postMessageAsync(msg); // we may be called from main thread, use async message
3506}
3507
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003508void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003509 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3511 this);
3512 int32_t type = hw->getDisplayType();
3513 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003514
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003515 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003516 return;
3517 }
3518
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003519 hw->setPowerMode(mode);
3520 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3521 ALOGW("Trying to set power mode for virtual display");
3522 return;
3523 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003524
Lloyd Pique4d234852018-01-22 17:21:36 -08003525 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003526 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003527 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3528 if (idx < 0) {
3529 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3530 return;
3531 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003532 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003533 }
3534
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003536 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003537 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003538 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3539 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003540 // FIXME: eventthread only knows about the main display right now
3541 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003542 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003543 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003545 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003546 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003547 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003548
3549 struct sched_param param = {0};
3550 param.sched_priority = 1;
3551 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3552 ALOGW("Couldn't set SCHED_FIFO on display on");
3553 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003554 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003555 // Turn off the display
3556 struct sched_param param = {0};
3557 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3558 ALOGW("Couldn't set SCHED_OTHER on display off");
3559 }
3560
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003561 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3562 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003563 disableHardwareVsync(true); // also cancels any in-progress resync
3564
Mathias Agopiancde87a32012-09-13 14:09:01 -07003565 // FIXME: eventthread only knows about the main display right now
3566 mEventThread->onScreenReleased();
3567 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003568
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003569 getHwComposer().setPowerMode(type, mode);
3570 mVisibleRegionsDirty = true;
3571 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003572 } else if (mode == HWC_POWER_MODE_DOZE ||
3573 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003574 // Update display while dozing
3575 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003576 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3577 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003578 // FIXME: eventthread only knows about the main display right now
3579 mEventThread->onScreenAcquired();
3580 resyncToHardwareVsync(true);
3581 }
3582 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3583 // Leave display going to doze
3584 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3585 disableHardwareVsync(true); // also cancels any in-progress resync
3586 // FIXME: eventthread only knows about the main display right now
3587 mEventThread->onScreenReleased();
3588 }
3589 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003590 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003591 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003592 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003593 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003594}
3595
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003596void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3597 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003598 SurfaceFlinger& mFlinger;
3599 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003601 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003602 MessageSetPowerMode(SurfaceFlinger& flinger,
3603 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3604 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003605 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003606 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003607 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003608 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003609 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003610 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003611 ALOGW("Attempt to set power mode = %d for virtual display",
3612 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003613 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003614 mFlinger.setPowerModeInternal(
3615 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003616 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003617 return true;
3618 }
3619 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003620 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003621 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003622}
3623
3624// ---------------------------------------------------------------------------
3625
Lloyd Pique755e3192018-01-31 16:46:15 -08003626status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3627 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003629
Mathias Agopianbd115332013-04-18 16:41:04 -07003630 IPCThreadState* ipc = IPCThreadState::self();
3631 const int pid = ipc->getCallingPid();
3632 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003633
Mathias Agopianbd115332013-04-18 16:41:04 -07003634 if ((uid != AID_SHELL) &&
3635 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003636 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003637 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003639 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003640 // (this would indicate SF is stuck, but we want to be able to
3641 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003642 status_t err = mStateLock.timedLock(s2ns(1));
3643 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003644 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003645 result.appendFormat(
3646 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3647 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003648 }
3649
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003650 bool dumpAll = true;
3651 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003652 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003653
3654 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003655 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003656 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3657 dumpAll = false;
3658 }
3659
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003660 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003661 if ((index < numArgs) &&
3662 (args[index] == String16("--list"))) {
3663 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003664 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003665 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003666 }
3667
3668 if ((index < numArgs) &&
3669 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003670 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003671 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003672 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003673 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003674
3675 if ((index < numArgs) &&
3676 (args[index] == String16("--latency-clear"))) {
3677 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003678 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003679 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003680 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003681
3682 if ((index < numArgs) &&
3683 (args[index] == String16("--dispsync"))) {
3684 index++;
3685 mPrimaryDispSync.dump(result);
3686 dumpAll = false;
3687 }
Dan Stozab90cf072015-03-05 11:05:59 -08003688
3689 if ((index < numArgs) &&
3690 (args[index] == String16("--static-screen"))) {
3691 index++;
3692 dumpStaticScreenStats(result);
3693 dumpAll = false;
3694 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003695
3696 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003697 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003698 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003699 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003700 dumpAll = false;
3701 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003702
3703 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3704 index++;
3705 dumpWideColorInfo(result);
3706 dumpAll = false;
3707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003709
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003710 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003711 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003712 }
3713
Mathias Agopian9795c422009-08-26 16:36:26 -07003714 if (locked) {
3715 mStateLock.unlock();
3716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 }
3718 write(fd, result.string(), result.size());
3719 return NO_ERROR;
3720}
3721
Dan Stozac7014012014-02-14 15:03:43 -08003722void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3723 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003724{
Robert Carr2047fae2016-11-28 14:09:09 -08003725 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003726 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003727 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003728}
3729
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003730void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003731 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003732{
3733 String8 name;
3734 if (index < args.size()) {
3735 name = String8(args[index]);
3736 index++;
3737 }
3738
David Sodman105b7dc2017-11-04 20:28:14 -07003739 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003740 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003741 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003742
3743 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003744 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003745 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003746 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003747 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003748 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003749 }
Robert Carr2047fae2016-11-28 14:09:09 -08003750 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003751 }
3752}
3753
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003754void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003755 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003756{
3757 String8 name;
3758 if (index < args.size()) {
3759 name = String8(args[index]);
3760 index++;
3761 }
3762
Robert Carr2047fae2016-11-28 14:09:09 -08003763 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003764 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003765 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003766 }
Robert Carr2047fae2016-11-28 14:09:09 -08003767 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003768
Svetoslavd85084b2014-03-20 10:28:31 -07003769 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003770}
3771
Jamie Gennis6547ff42013-07-16 20:12:42 -07003772// This should only be called from the main thread. Otherwise it would need
3773// the lock and should use mCurrentState rather than mDrawingState.
3774void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003775 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003776 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003777 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003778
3779 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3780}
3781
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003782void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003783{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003784 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003785
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003786 if (isLayerTripleBufferingDisabled())
3787 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003788
3789 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003790 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003791 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003792 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003793 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3794 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003795 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003796}
3797
Dan Stozab90cf072015-03-05 11:05:59 -08003798void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3799{
3800 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003801 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3802 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003803 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003804 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003805 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3806 b + 1, bucketTimeSec, percent);
3807 }
David Sodman4a36e932017-11-07 14:29:47 -08003808 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003809 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003810 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003811 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003812 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003813}
3814
Dan Stozae77c7662016-05-13 11:37:28 -07003815void SurfaceFlinger::recordBufferingStats(const char* layerName,
3816 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003817 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3818 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003819 for (const auto& segment : history) {
3820 if (!segment.usedThirdBuffer) {
3821 stats.twoBufferTime += segment.totalTime;
3822 }
3823 if (segment.occupancyAverage < 1.0f) {
3824 stats.doubleBufferedTime += segment.totalTime;
3825 } else if (segment.occupancyAverage < 2.0f) {
3826 stats.tripleBufferedTime += segment.totalTime;
3827 }
3828 ++stats.numSegments;
3829 stats.totalTime += segment.totalTime;
3830 }
3831}
3832
Brian Andersond6927fb2016-07-23 23:37:30 -07003833void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3834 result.appendFormat("Layer frame timestamps:\n");
3835
3836 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3837 const size_t count = currentLayers.size();
3838 for (size_t i=0 ; i<count ; i++) {
3839 currentLayers[i]->dumpFrameEvents(result);
3840 }
3841}
3842
Dan Stozae77c7662016-05-13 11:37:28 -07003843void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3844 result.append("Buffering stats:\n");
3845 result.append(" [Layer name] <Active time> <Two buffer> "
3846 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003847 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003848 typedef std::tuple<std::string, float, float, float> BufferTuple;
3849 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003850 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003851 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003852 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003853 if (stats.numSegments == 0) {
3854 continue;
3855 }
3856 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3857 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3858 stats.totalTime;
3859 float doubleBufferRatio = static_cast<float>(
3860 stats.doubleBufferedTime) / stats.totalTime;
3861 float tripleBufferRatio = static_cast<float>(
3862 stats.tripleBufferedTime) / stats.totalTime;
3863 sorted.insert({activeTime, {name, twoBufferRatio,
3864 doubleBufferRatio, tripleBufferRatio}});
3865 }
3866 for (const auto& sortedPair : sorted) {
3867 float activeTime = sortedPair.first;
3868 const BufferTuple& values = sortedPair.second;
3869 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3870 std::get<0>(values).c_str(), activeTime,
3871 std::get<1>(values), std::get<2>(values),
3872 std::get<3>(values));
3873 }
3874 result.append("\n");
3875}
3876
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003877void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3878 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003879 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003880
3881 // TODO: print out if wide-color mode is active or not
3882
3883 for (size_t d = 0; d < mDisplays.size(); d++) {
3884 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3885 int32_t hwcId = displayDevice->getHwcDisplayId();
3886 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3887 continue;
3888 }
3889
3890 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003891 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003892 for (auto&& mode : modes) {
3893 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3894 }
3895
Peiyong Lina52f0292018-03-14 17:26:31 -07003896 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003897 result.appendFormat(" Current color mode: %s (%d)\n",
3898 decodeColorMode(currentMode).c_str(), currentMode);
3899 }
3900 result.append("\n");
3901}
3902
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003903LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003904 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003905 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3906 const State& state = useDrawing ? mDrawingState : mCurrentState;
3907 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003908 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003909 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003910 });
3911
3912 return layersProto;
3913}
3914
Mathias Agopian74d211a2013-04-22 16:55:35 +02003915void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3916 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003917{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003918 bool colorize = false;
3919 if (index < args.size()
3920 && (args[index] == String16("--color"))) {
3921 colorize = true;
3922 index++;
3923 }
3924
3925 Colorizer colorizer(colorize);
3926
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003927 // figure out if we're stuck somewhere
3928 const nsecs_t now = systemTime();
3929 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3930 const nsecs_t inTransaction(mDebugInTransaction);
3931 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3932 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3933
3934 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003935 * Dump library configuration.
3936 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003937
3938 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003939 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003940 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003941 appendSfConfigString(result);
3942 appendUiConfigString(result);
3943 appendGuiConfigString(result);
3944 result.append("\n");
3945
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003946 result.append("\nWide-Color information:\n");
3947 dumpWideColorInfo(result);
3948
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003949 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003950 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003951 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003952 result.append(SyncFeatures::getInstance().toString());
3953 result.append("\n");
3954
David Sodman105b7dc2017-11-04 20:28:14 -07003955 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003956
Andy McFadden41d67d72014-04-25 16:58:34 -07003957 colorizer.bold(result);
3958 result.append("DispSync configuration: ");
3959 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003960 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003961 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003962 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003963 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003964 result.append("\n");
3965
Dan Stozab90cf072015-03-05 11:05:59 -08003966 // Dump static screen stats
3967 result.append("\n");
3968 dumpStaticScreenStats(result);
3969 result.append("\n");
3970
Dan Stozae77c7662016-05-13 11:37:28 -07003971 dumpBufferingStats(result);
3972
Andy McFadden4803b742012-09-24 19:07:20 -07003973 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974 * Dump the visible layer list
3975 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003976 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003977 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07003978 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
3979 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003980 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003981
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003982 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003983 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07003984 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003985
3986 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003987 * Dump Display state
3988 */
3989
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003990 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003991 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003992 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003993 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3994 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003995 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003996 }
3997
3998 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003999 * Dump SurfaceFlinger global state
4000 */
4001
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004002 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004003 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004005
Mathias Agopian888c8222012-08-04 21:10:38 -07004006 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004007 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004008
David Sodmanbc815282017-11-05 18:57:52 -08004009 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004010
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004011 if (hw) {
4012 hw->undefinedRegion.dump(result, "undefinedRegion");
4013 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4014 hw->getOrientation(), hw->isDisplayOn());
4015 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004016 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004017 " last eglSwapBuffers() time: %f us\n"
4018 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004019 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004020 " refresh-rate : %f fps\n"
4021 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004022 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004023 " gpu_to_cpu_unsupported : %d\n"
4024 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004025 mLastSwapBufferTime/1000.0,
4026 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004027 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004028 1e9 / activeConfig->getVsyncPeriod(),
4029 activeConfig->getDpiX(),
4030 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004031 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032
Mathias Agopian74d211a2013-04-22 16:55:35 +02004033 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004034 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004035
Mathias Agopian74d211a2013-04-22 16:55:35 +02004036 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004038
4039 /*
4040 * VSYNC state
4041 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004042 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004043 result.append("\n");
4044
4045 /*
4046 * HWC layer minidump
4047 */
4048 for (size_t d = 0; d < mDisplays.size(); d++) {
4049 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4050 int32_t hwcId = displayDevice->getHwcDisplayId();
4051 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4052 continue;
4053 }
4054
4055 result.appendFormat("Display %d HWC layers:\n", hwcId);
4056 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004057 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004058 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004059 });
Dan Stozae22aec72016-08-01 13:20:59 -07004060 result.append("\n");
4061 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004062
4063 /*
4064 * Dump HWComposer state
4065 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004066 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004067 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004068 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004069 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004070 result.appendFormat(" h/w composer %s\n",
4071 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004072 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004073
4074 /*
4075 * Dump gralloc state
4076 */
4077 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4078 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004079
4080 /*
4081 * Dump VrFlinger state if in use.
4082 */
4083 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4084 result.append("VrFlinger state:\n");
4085 result.append(mVrFlinger->Dump().c_str());
4086 result.append("\n");
4087 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004088}
4089
Mathias Agopian13127d82013-03-05 17:47:11 -08004090const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004091SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004092 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004093 wp<IBinder> dpy;
4094 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4095 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4096 dpy = mDisplays.keyAt(i);
4097 break;
4098 }
4099 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004100 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004101 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4102 // Just use the primary display so we have something to return
4103 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4104 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004105 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004106}
4107
Keun young Park63f165f2012-08-31 10:53:36 -07004108bool SurfaceFlinger::startDdmConnection()
4109{
4110 void* libddmconnection_dso =
4111 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4112 if (!libddmconnection_dso) {
4113 return false;
4114 }
4115 void (*DdmConnection_start)(const char* name);
4116 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004117 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004118 if (!DdmConnection_start) {
4119 dlclose(libddmconnection_dso);
4120 return false;
4121 }
4122 (*DdmConnection_start)(getServiceName());
4123 return true;
4124}
4125
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004126status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 switch (code) {
4128 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004129 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004131 case CLEAR_ANIMATION_FRAME_STATS:
4132 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004133 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004134 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004135 case ENABLE_VSYNC_INJECTIONS:
4136 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 {
4138 // codes that require permission check
4139 IPCThreadState* ipc = IPCThreadState::self();
4140 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004141 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004142 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004143 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004144 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004145 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004147 break;
4148 }
Robert Carr1db73f62016-12-21 12:58:51 -08004149 /*
4150 * Calling setTransactionState is safe, because you need to have been
4151 * granted a reference to Client* and Handle* to do anything with it.
4152 *
4153 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4154 */
4155 case SET_TRANSACTION_STATE:
4156 case CREATE_SCOPED_CONNECTION:
4157 {
4158 return OK;
4159 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004160 case CAPTURE_SCREEN:
4161 {
4162 // codes that require permission check
4163 IPCThreadState* ipc = IPCThreadState::self();
4164 const int pid = ipc->getCallingPid();
4165 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004166 if ((uid != AID_GRAPHICS) &&
4167 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004168 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004169 return PERMISSION_DENIED;
4170 }
4171 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004172 }
chaviwa76b2712017-09-20 12:02:26 -07004173 case CAPTURE_LAYERS: {
4174 IPCThreadState* ipc = IPCThreadState::self();
4175 const int pid = ipc->getCallingPid();
4176 const int uid = ipc->getCallingUid();
4177 if ((uid != AID_GRAPHICS) &&
4178 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4179 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4180 return PERMISSION_DENIED;
4181 }
4182 break;
4183 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004185 return OK;
4186}
4187
4188status_t SurfaceFlinger::onTransact(
4189 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4190{
4191 status_t credentialCheck = CheckTransactCodeCredentials(code);
4192 if (credentialCheck != OK) {
4193 return credentialCheck;
4194 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004195
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004196 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4197 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004198 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004199 IPCThreadState* ipc = IPCThreadState::self();
4200 const int uid = ipc->getCallingUid();
4201 if (CC_UNLIKELY(uid != AID_SYSTEM
4202 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004203 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004204 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004205 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206 return PERMISSION_DENIED;
4207 }
4208 int n;
4209 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004210 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004211 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004212 return NO_ERROR;
4213 case 1002: // SHOW_UPDATES
4214 n = data.readInt32();
4215 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004216 invalidateHwcGeometry();
4217 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004218 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004219 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004220 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004221 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004223 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004224 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004225 setTransactionFlags(
4226 eTransactionNeeded|
4227 eDisplayTransactionNeeded|
4228 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004229 return NO_ERROR;
4230 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004231 case 1006:{ // send empty update
4232 signalRefresh();
4233 return NO_ERROR;
4234 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004235 case 1008: // toggle use of hw composer
4236 n = data.readInt32();
4237 mDebugDisableHWC = n ? 1 : 0;
4238 invalidateHwcGeometry();
4239 repaintEverything();
4240 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004241 case 1009: // toggle use of transform hint
4242 n = data.readInt32();
4243 mDebugDisableTransformHint = n ? 1 : 0;
4244 invalidateHwcGeometry();
4245 repaintEverything();
4246 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004247 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004248 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004249 reply->writeInt32(0);
4250 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004251 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004252 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004253 return NO_ERROR;
4254 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004255 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004256 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004257 return NO_ERROR;
4258 }
4259 case 1014: {
4260 // daltonize
4261 n = data.readInt32();
4262 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004263 case 1:
4264 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4265 break;
4266 case 2:
4267 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4268 break;
4269 case 3:
4270 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4271 break;
4272 default:
4273 mDaltonizer.setType(ColorBlindnessType::None);
4274 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004275 }
4276 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004277 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004278 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004279 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004280 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004281 invalidateHwcGeometry();
4282 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004283 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004284 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004285 case 1015: {
4286 // apply a color matrix
4287 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004288 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004289 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004290 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004291 for (size_t j = 0; j < 4; j++) {
4292 mColorMatrix[i][j] = data.readFloat();
4293 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004294 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004295 } else {
4296 mColorMatrix = mat4();
4297 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004298
4299 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4300 // the division by w in the fragment shader
4301 float4 lastRow(transpose(mColorMatrix)[3]);
4302 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4303 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4304 }
4305
Alan Viverette9c5a3332013-09-12 20:04:35 -07004306 invalidateHwcGeometry();
4307 repaintEverything();
4308 return NO_ERROR;
4309 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004310 // This is an experimental interface
4311 // Needs to be shifted to proper binder interface when we productize
4312 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004313 n = data.readInt32();
4314 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004315 return NO_ERROR;
4316 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004317 case 1017: {
4318 n = data.readInt32();
4319 mForceFullDamage = static_cast<bool>(n);
4320 return NO_ERROR;
4321 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004322 case 1018: { // Modify Choreographer's phase offset
4323 n = data.readInt32();
4324 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4325 return NO_ERROR;
4326 }
4327 case 1019: { // Modify SurfaceFlinger's phase offset
4328 n = data.readInt32();
4329 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4330 return NO_ERROR;
4331 }
Irvel468051e2016-06-13 16:44:44 -07004332 case 1020: { // Layer updates interceptor
4333 n = data.readInt32();
4334 if (n) {
4335 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004336 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004337 }
4338 else{
4339 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004340 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004341 }
4342 return NO_ERROR;
4343 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004344 case 1021: { // Disable HWC virtual displays
4345 n = data.readInt32();
4346 mUseHwcVirtualDisplays = !n;
4347 return NO_ERROR;
4348 }
Romain Guy0147a172017-06-01 13:53:56 -07004349 case 1022: { // Set saturation boost
4350 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4351
4352 invalidateHwcGeometry();
4353 repaintEverything();
4354 return NO_ERROR;
4355 }
Romain Guy54f154a2017-10-24 21:40:32 +01004356 case 1023: { // Set native mode
4357 mForceNativeColorMode = data.readInt32() == 1;
4358
4359 invalidateHwcGeometry();
4360 repaintEverything();
4361 return NO_ERROR;
4362 }
4363 case 1024: { // Is wide color gamut rendering/color management supported?
4364 reply->writeBool(hasWideColorDisplay);
4365 return NO_ERROR;
4366 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004367 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004368 n = data.readInt32();
4369 if (n) {
4370 ALOGV("LayerTracing enabled");
4371 mTracing.enable();
4372 doTracing("tracing.enable");
4373 reply->writeInt32(NO_ERROR);
4374 } else {
4375 ALOGV("LayerTracing disabled");
4376 status_t err = mTracing.disable();
4377 reply->writeInt32(err);
4378 }
4379 return NO_ERROR;
4380 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004381 case 1026: { // Get layer tracing status
4382 reply->writeBool(mTracing.isEnabled());
4383 return NO_ERROR;
4384 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004385 }
4386 }
4387 return err;
4388}
4389
Steven Thomas6d8110b2017-08-31 18:24:21 -07004390void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004391 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004392 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004393}
4394
Steven Thomas6d8110b2017-08-31 18:24:21 -07004395void SurfaceFlinger::repaintEverything() {
4396 ConditionalLock _l(mStateLock,
4397 std::this_thread::get_id() != mMainThreadId);
4398 repaintEverythingLocked();
4399}
4400
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004401// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4402class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004403public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004404 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4405 ~WindowDisconnector() {
4406 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004407 }
4408
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004409private:
4410 ANativeWindow* mWindow;
4411 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004412};
4413
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004414status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4415 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4416 int32_t minLayerZ, int32_t maxLayerZ,
4417 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004418 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004419 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004420
chaviwa76b2712017-09-20 12:02:26 -07004421 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4422
4423 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004424 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4425
chaviwa76b2712017-09-20 12:02:26 -07004426 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4427
4428 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4429 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004430 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004431}
4432
4433status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004434 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004435 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004436 ATRACE_CALL();
4437
4438 class LayerRenderArea : public RenderArea {
4439 public:
Robert Carr578038f2018-03-09 12:25:24 -08004440 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4441 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4442 : RenderArea(reqHeight, reqWidth),
4443 mLayer(layer),
4444 mCrop(crop),
4445 mFlinger(flinger),
4446 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004447 Rect getBounds() const override {
4448 const Layer::State& layerState(mLayer->getDrawingState());
4449 return Rect(layerState.active.w, layerState.active.h);
4450 }
4451 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4452 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4453 bool isSecure() const override { return false; }
4454 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004455 const Transform& getTransform() const { return mTransform; }
4456
4457 class ReparentForDrawing {
4458 public:
4459 const sp<Layer>& oldParent;
4460 const sp<Layer>& newParent;
4461
4462 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4463 : oldParent(oldParent), newParent(newParent) {
4464 oldParent->reparentChildrenForDrawing(newParent);
4465 }
4466 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4467 };
4468
4469 void render(std::function<void()> drawLayers) override {
4470 if (!mChildrenOnly) {
4471 mTransform = mLayer->getTransform().inverse();
4472 drawLayers();
4473 } else {
4474 Rect bounds = getBounds();
4475 screenshotParentLayer =
4476 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4477 bounds.getWidth(), bounds.getHeight(), 0);
4478
4479 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4480 drawLayers();
4481 }
4482 }
chaviwa76b2712017-09-20 12:02:26 -07004483
chaviw7206d492017-11-10 16:16:12 -08004484 Rect getSourceCrop() const override {
4485 if (mCrop.isEmpty()) {
4486 return getBounds();
4487 } else {
4488 return mCrop;
4489 }
4490 }
chaviwa76b2712017-09-20 12:02:26 -07004491 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004492 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004493
4494 private:
chaviw7206d492017-11-10 16:16:12 -08004495 const sp<Layer> mLayer;
4496 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004497
4498 // In the "childrenOnly" case we reparent the children to a screenshot
4499 // layer which has no properties set and which does not draw.
4500 sp<ContainerLayer> screenshotParentLayer;
4501 Transform mTransform;
4502
4503 SurfaceFlinger* mFlinger;
4504 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004505 };
4506
4507 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4508 auto parent = layerHandle->owner.promote();
4509
chaviw7206d492017-11-10 16:16:12 -08004510 if (parent == nullptr || parent->isPendingRemoval()) {
4511 ALOGE("captureLayers called with a removed parent");
4512 return NAME_NOT_FOUND;
4513 }
4514
Robert Carr578038f2018-03-09 12:25:24 -08004515 const int uid = IPCThreadState::self()->getCallingUid();
4516 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4517 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4518 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4519 return PERMISSION_DENIED;
4520 }
4521
chaviw7206d492017-11-10 16:16:12 -08004522 Rect crop(sourceCrop);
4523 if (sourceCrop.width() <= 0) {
4524 crop.left = 0;
4525 crop.right = parent->getCurrentState().active.w;
4526 }
4527
4528 if (sourceCrop.height() <= 0) {
4529 crop.top = 0;
4530 crop.bottom = parent->getCurrentState().active.h;
4531 }
4532
4533 int32_t reqWidth = crop.width() * frameScale;
4534 int32_t reqHeight = crop.height() * frameScale;
4535
Robert Carr578038f2018-03-09 12:25:24 -08004536 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004537
Robert Carr578038f2018-03-09 12:25:24 -08004538 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004539 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4540 if (!layer->isVisible()) {
4541 return;
Robert Carr578038f2018-03-09 12:25:24 -08004542 } else if (childrenOnly && layer == parent.get()) {
4543 return;
chaviwa76b2712017-09-20 12:02:26 -07004544 }
4545 visitor(layer);
4546 });
4547 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004548 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004549}
4550
4551status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4552 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004553 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004554 bool useIdentityTransform) {
4555 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004556
chaviwa76b2712017-09-20 12:02:26 -07004557 renderArea.updateDimensions();
4558
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004559 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4560 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4561 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4562 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004563
4564 // This mutex protects syncFd and captureResult for communication of the return values from the
4565 // main thread back to this Binder thread
4566 std::mutex captureMutex;
4567 std::condition_variable captureCondition;
4568 std::unique_lock<std::mutex> captureLock(captureMutex);
4569 int syncFd = -1;
4570 std::optional<status_t> captureResult;
4571
Robert Carr03480e22018-01-04 16:02:06 -08004572 const int uid = IPCThreadState::self()->getCallingUid();
4573 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4574
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004575 sp<LambdaMessage> message = new LambdaMessage([&]() {
4576 // If there is a refresh pending, bug out early and tell the binder thread to try again
4577 // after the refresh.
4578 if (mRefreshPending) {
4579 ATRACE_NAME("Skipping screenshot for now");
4580 std::unique_lock<std::mutex> captureLock(captureMutex);
4581 captureResult = std::make_optional<status_t>(EAGAIN);
4582 captureCondition.notify_one();
4583 return;
4584 }
4585
4586 status_t result = NO_ERROR;
4587 int fd = -1;
4588 {
4589 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004590 renderArea.render([&]() {
4591 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4592 useIdentityTransform, forSystem, &fd);
4593 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004594 }
4595
4596 {
4597 std::unique_lock<std::mutex> captureLock(captureMutex);
4598 syncFd = fd;
4599 captureResult = std::make_optional<status_t>(result);
4600 captureCondition.notify_one();
4601 }
4602 });
4603
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004604 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004605 if (result == NO_ERROR) {
4606 captureCondition.wait(captureLock, [&]() { return captureResult; });
4607 while (*captureResult == EAGAIN) {
4608 captureResult.reset();
4609 result = postMessageAsync(message);
4610 if (result != NO_ERROR) {
4611 return result;
4612 }
4613 captureCondition.wait(captureLock, [&]() { return captureResult; });
4614 }
4615 result = *captureResult;
4616 }
4617
4618 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004619 sync_wait(syncFd, -1);
4620 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004621 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004622
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004623 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004624}
4625
chaviwa76b2712017-09-20 12:02:26 -07004626void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4627 TraverseLayersFunction traverseLayers, bool yswap,
4628 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004629 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004630
Lloyd Pique144e1162017-12-20 16:44:52 -08004631 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004632
4633 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004634 const auto raWidth = renderArea.getWidth();
4635 const auto raHeight = renderArea.getHeight();
4636
4637 const auto reqWidth = renderArea.getReqWidth();
4638 const auto reqHeight = renderArea.getReqHeight();
4639 Rect sourceCrop = renderArea.getSourceCrop();
4640
4641 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4642 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004643
Dan Stozac1879002014-05-22 15:59:05 -07004644 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004645 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004646 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004647 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004648 }
4649
4650 // ensure that sourceCrop is inside screen
4651 if (sourceCrop.left < 0) {
4652 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4653 }
chaviwa76b2712017-09-20 12:02:26 -07004654 if (sourceCrop.right > raWidth) {
4655 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004656 }
4657 if (sourceCrop.top < 0) {
4658 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4659 }
chaviwa76b2712017-09-20 12:02:26 -07004660 if (sourceCrop.bottom > raHeight) {
4661 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004662 }
4663
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004664 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004665 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004666 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004667 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4668 }
4669 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004670
Mathias Agopian180f10d2013-04-10 22:55:41 -07004671 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004672 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004673
4674 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004675 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4676 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004677 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004678
4679 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004680 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004681
chaviwa76b2712017-09-20 12:02:26 -07004682 traverseLayers([&](Layer* layer) {
4683 if (filtering) layer->setFiltering(true);
4684 layer->draw(renderArea, useIdentityTransform);
4685 if (filtering) layer->setFiltering(false);
4686 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004687}
4688
chaviwa76b2712017-09-20 12:02:26 -07004689status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4690 TraverseLayersFunction traverseLayers,
4691 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004692 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004693 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004694 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004695 ATRACE_CALL();
4696
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004697 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004698
4699 traverseLayers([&](Layer* layer) {
4700 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4701 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004702
Robert Carr03480e22018-01-04 16:02:06 -08004703 // We allow the system server to take screenshots of secure layers for
4704 // use in situations like the Screen-rotation animation and place
4705 // the impetus on WindowManager to not persist them.
4706 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004707 ALOGW("FB is protected: PERMISSION_DENIED");
4708 return PERMISSION_DENIED;
4709 }
4710
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004711 // this binds the given EGLImage as a framebuffer for the
4712 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004713 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004714 if (bufferBond.getStatus() != NO_ERROR) {
4715 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004716 return INVALID_OPERATION;
4717 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004718
Dan Stozaabcda352017-06-01 14:37:39 -07004719 // this will in fact render into our dequeued buffer
4720 // via an FBO, which means we didn't have to create
4721 // an EGLSurface and therefore we're not
4722 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004723 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004724
Dan Stozaabcda352017-06-01 14:37:39 -07004725 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004726 getRenderEngine().finish();
4727 *outSyncFd = -1;
4728
chaviwa76b2712017-09-20 12:02:26 -07004729 const auto reqWidth = renderArea.getReqWidth();
4730 const auto reqHeight = renderArea.getReqHeight();
4731
Dan Stozaabcda352017-06-01 14:37:39 -07004732 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4733 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004734 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004735 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004736 } else {
4737 base::unique_fd syncFd = getRenderEngine().flush();
4738 if (syncFd < 0) {
4739 getRenderEngine().finish();
4740 }
4741 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004742 }
4743
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004744 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004745}
4746
Mathias Agopiand5556842013-09-19 17:08:37 -07004747void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004748 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004749 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004750 for (size_t y = 0; y < h; y++) {
4751 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4752 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004753 if (p[x] != 0xFF000000) return;
4754 }
4755 }
chaviwa76b2712017-09-20 12:02:26 -07004756 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004757
Robert Carr2047fae2016-11-28 14:09:09 -08004758 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004759 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004760 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004761 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4762 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4763 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4764 static_cast<float>(state.color.a));
4765 i++;
4766 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004767 }
4768}
4769
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004770// ---------------------------------------------------------------------------
4771
Dan Stoza412903f2017-04-27 13:42:17 -07004772void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4773 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004774}
4775
Dan Stoza412903f2017-04-27 13:42:17 -07004776void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4777 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004778}
4779
chaviwa76b2712017-09-20 12:02:26 -07004780void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4781 int32_t maxLayerZ,
4782 const LayerVector::Visitor& visitor) {
4783 // We loop through the first level of layers without traversing,
4784 // as we need to interpret min/max layer Z in the top level Z space.
4785 for (const auto& layer : mDrawingState.layersSortedByZ) {
4786 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4787 continue;
4788 }
4789 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004790 // relative layers are traversed in Layer::traverseInZOrder
4791 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004792 continue;
4793 }
4794 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004795 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4796 return;
4797 }
chaviwa76b2712017-09-20 12:02:26 -07004798 if (!layer->isVisible()) {
4799 return;
4800 }
4801 visitor(layer);
4802 });
4803 }
4804}
4805
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004806}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004807
4808
4809#if defined(__gl_h_)
4810#error "don't include gl/gl.h in this file"
4811#endif
4812
4813#if defined(__gl2_h_)
4814#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004815#endif