blob: e5a15d58af8b85a14a8e892244efe4095e834623 [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),
Robert Carr0d480722017-01-10 16:42:54 -0800189 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700191 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700192 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700193 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800194 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800195 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700196 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800197 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800198 mCreateBufferQueue(&BufferQueue::createBufferQueue) {}
199
200SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800201 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800202
203 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
205
206 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
208
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800209 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
214
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
217
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
219 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
220
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 // Vr flinger is only enabled on Daydream ready devices.
222 useVrFlinger = getBool< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::useVrFlinger>(false);
224
Fabien Sanglard1971b632017-03-10 14:50:03 -0800225 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
226 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
227
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228 hasWideColorDisplay =
229 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
230
David Sodman99974d22017-11-28 12:04:33 -0800231 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // debugging stuff...
234 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700237 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 property_get("debug.sf.showupdates", value, "0");
240 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242 property_get("debug.sf.ddms", value, "0");
243 mDebugDDMS = atoi(value);
244 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700245 if (!startDdmConnection()) {
246 // start failed, and DDMS debugging not enabled
247 mDebugDDMS = 0;
248 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700250 ALOGI_IF(mDebugRegion, "showupdates enabled");
251 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700252
253 property_get("debug.sf.disable_backpressure", value, "0");
254 mPropagateBackpressure = !atoi(value);
255 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700256
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800257 property_get("debug.sf.enable_hwc_vds", value, "0");
258 mUseHwcVirtualDisplays = atoi(value);
259 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800261 property_get("ro.sf.disable_triple_buffer", value, "1");
262 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800263 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700264
Dan Stoza0a0158c2018-03-16 13:38:54 -0700265 // TODO (b/74616334): Reduce the default value once we isolate the leak
266 const size_t defaultListSize = 4 * MAX_LAYERS;
267 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
268 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
269
Romain Guy11d63f42017-07-20 12:47:14 -0700270 // We should be reading 'persist.sys.sf.color_saturation' here
271 // but since /data may be encrypted, we need to wait until after vold
272 // comes online to attempt to read the property. The property is
273 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800274
275 if (useTrebleTestingOverride()) {
276 // Without the override SurfaceFlinger cannot connect to HIDL
277 // services that are not listed in the manifests. Considered
278 // deriving the setting from the set service name, but it
279 // would be brittle if the name that's not 'default' is used
280 // for production purposes later on.
281 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
282 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283}
284
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800285void SurfaceFlinger::onFirstRef()
286{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800287 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800288}
289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290SurfaceFlinger::~SurfaceFlinger()
291{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292}
293
Dan Stozac7014012014-02-14 15:03:43 -0800294void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295{
296 // the window manager died on us. prepare its eulogy.
297
Andy McFadden13a082e2012-08-24 10:16:42 -0700298 // restore initial conditions (default device unblank, etc)
299 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800300
301 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700302 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800303}
304
Robert Carr1db73f62016-12-21 12:58:51 -0800305static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700306 status_t err = client->initCheck();
307 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800308 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309 }
Robert Carr1db73f62016-12-21 12:58:51 -0800310 return nullptr;
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
314 return initClient(new Client(this));
315}
316
317sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
318 const sp<IGraphicBufferProducer>& gbp) {
319 if (authenticateSurfaceTexture(gbp) == false) {
320 return nullptr;
321 }
322 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
323 if (layer == nullptr) {
324 return nullptr;
325 }
326
327 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328}
329
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700330sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
331 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700332{
333 class DisplayToken : public BBinder {
334 sp<SurfaceFlinger> flinger;
335 virtual ~DisplayToken() {
336 // no more references, this display must be terminated
337 Mutex::Autolock _l(flinger->mStateLock);
338 flinger->mCurrentState.displays.removeItem(this);
339 flinger->setTransactionFlags(eDisplayTransactionNeeded);
340 }
341 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700342 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343 : flinger(flinger) {
344 }
345 };
346
347 sp<BBinder> token = new DisplayToken(this);
348
349 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700350 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700351 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700352 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700353 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700354 return token;
355}
356
Jesse Hall6c913be2013-08-08 12:15:49 -0700357void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
358 Mutex::Autolock _l(mStateLock);
359
360 ssize_t idx = mCurrentState.displays.indexOfKey(display);
361 if (idx < 0) {
362 ALOGW("destroyDisplay: invalid display token");
363 return;
364 }
365
366 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
367 if (!info.isVirtualDisplay()) {
368 ALOGE("destroyDisplay called for non-virtual display");
369 return;
370 }
Irvelffc9efc2016-07-27 15:16:37 -0700371 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700372 mCurrentState.displays.removeItemsAt(idx);
373 setTransactionFlags(eDisplayTransactionNeeded);
374}
375
Mathias Agopiane57f2922012-08-09 16:29:12 -0700376sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700377 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700378 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800379 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700380 }
Jesse Hall692c7232012-11-08 15:41:56 -0800381 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700382}
383
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800384void SurfaceFlinger::bootFinished()
385{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700386 if (mStartPropertySetThread->join() != NO_ERROR) {
387 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800388 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 const nsecs_t now = systemTime();
390 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000391 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700392
393 // wait patiently for the window manager death
394 const String16 name("window");
395 sp<IBinder> window(defaultServiceManager()->getService(name));
396 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700397 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700398 }
399
Steven Thomas050b2c82017-03-06 11:45:16 -0800400 if (mVrFlinger) {
401 mVrFlinger->OnBootFinished();
402 }
403
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700404 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700405 // formerly we would just kill the process, but we now ask it to exit so it
406 // can choose where to stop the animation.
407 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700408
409 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
410 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
411 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700412
Thierry Strudel2924d012017-08-14 15:19:37 -0700413 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700414 readPersistentProperties();
415 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700416 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417}
418
Mathias Agopian3f844832013-08-07 21:24:32 -0700419void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700420 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800421 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700422 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700423 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800424 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
425 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700427 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700428 return true;
429 }
430 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432}
433
Lloyd Piquee83f9312018-02-01 12:53:17 -0800434class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 const char* name) :
438 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700439 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700440 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000441 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
442 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700443 mDispSync(dispSync),
444 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 mVsyncMutex(),
446 mPhaseOffset(phaseOffset),
447 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700448
Lloyd Piquee83f9312018-02-01 12:53:17 -0800449 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700450
Lloyd Piquee83f9312018-02-01 12:53:17 -0800451 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700452 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000454 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 static_cast<DispSync::Callback*>(this));
456 if (err != NO_ERROR) {
457 ALOGE("error registering vsync callback: %s (%d)",
458 strerror(-err), err);
459 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700460 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 } else {
462 status_t err = mDispSync->removeEventListener(
463 static_cast<DispSync::Callback*>(this));
464 if (err != NO_ERROR) {
465 ALOGE("error unregistering vsync callback: %s (%d)",
466 strerror(-err), err);
467 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700468 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700470 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700471 }
472
Lloyd Piquee83f9312018-02-01 12:53:17 -0800473 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700475 mCallback = callback;
476 }
477
Lloyd Piquee83f9312018-02-01 12:53:17 -0800478 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 Mutex::Autolock lock(mVsyncMutex);
480
481 // Normalize phaseOffset to [0, period)
482 auto period = mDispSync->getPeriod();
483 phaseOffset %= period;
484 if (phaseOffset < 0) {
485 // If we're here, then phaseOffset is in (-period, 0). After this
486 // operation, it will be in (0, period)
487 phaseOffset += period;
488 }
489 mPhaseOffset = phaseOffset;
490
491 // If we're not enabled, we don't need to mess with the listeners
492 if (!mEnabled) {
493 return;
494 }
495
496 // Remove the listener with the old offset
497 status_t err = mDispSync->removeEventListener(
498 static_cast<DispSync::Callback*>(this));
499 if (err != NO_ERROR) {
500 ALOGE("error unregistering vsync callback: %s (%d)",
501 strerror(-err), err);
502 }
503
504 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000505 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 static_cast<DispSync::Callback*>(this));
507 if (err != NO_ERROR) {
508 ALOGE("error registering vsync callback: %s (%d)",
509 strerror(-err), err);
510 }
511 }
512
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513private:
514 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800515 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700517 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 callback = mCallback;
519
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700520 if (mTraceVsync) {
521 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700522 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700523 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 }
525
Peiyong Lin566a3b42018-01-09 18:22:43 -0800526 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 callback->onVSyncEvent(when);
528 }
529 }
530
Tim Murray4a4e4a22016-04-19 16:29:23 +0000531 const char* const mName;
532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 int mValue;
534
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700535 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700536 const String8 mVsyncOnLabel;
537 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700538
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540
541 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543
544 Mutex mVsyncMutex; // Protects the following
545 nsecs_t mPhaseOffset;
546 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547};
548
Lloyd Piquee83f9312018-02-01 12:53:17 -0800549class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700550public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800551 InjectVSyncSource() = default;
552 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700553
Lloyd Piquee83f9312018-02-01 12:53:17 -0800554 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700555 std::lock_guard<std::mutex> lock(mCallbackMutex);
556 mCallback = callback;
557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700560 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700561 if (mCallback) {
562 mCallback->onVSyncEvent(when);
563 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700564 }
565
Lloyd Piquee83f9312018-02-01 12:53:17 -0800566 void setVSyncEnabled(bool) override {}
567 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700568
569private:
570 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800571 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700572};
573
Wei Wangf9b05ee2017-07-19 20:59:39 -0700574// Do not call property_set on main thread which will be blocked by init
575// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700576void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700577 ALOGI( "SurfaceFlinger's main thread ready to run. "
578 "Initializing graphics H/W...");
579
Thierry Strudel2924d012017-08-14 15:19:37 -0700580 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900581
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800583
Steven Thomasb02664d2017-07-26 18:48:28 -0700584 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800585 mEventThreadSource =
586 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
587 true, "app");
588 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
589 "appEventThread");
590 mSfEventThreadSource =
591 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
592 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800593
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800594 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
595 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800596 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800599 getBE().mRenderEngine =
600 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
601 hasWideColorDisplay
602 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
603 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800604 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700605
606 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
607 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800608 getBE().mHwc.reset(
609 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700610 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800611 // Process any initial hotplug and resulting display changes.
612 processDisplayHotplugEventsLocked();
613 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
614 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800615
Lloyd Piquefcd86612017-12-14 17:15:36 -0800616 // make the default display GLContext current so that we can create textures
617 // when creating Layers (which may happens before we render something)
618 getDefaultDisplayDeviceLocked()->makeCurrent();
619
Steven Thomas050b2c82017-03-06 11:45:16 -0800620 if (useVrFlinger) {
621 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700622 // This callback is called from the vr flinger dispatch thread. We
623 // need to call signalTransaction(), which requires holding
624 // mStateLock when we're not on the main thread. Acquiring
625 // mStateLock from the vr flinger dispatch thread might trigger a
626 // deadlock in surface flinger (see b/66916578), so post a message
627 // to be handled on the main thread instead.
628 sp<LambdaMessage> message = new LambdaMessage([=]() {
629 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
630 mVrFlingerRequestsDisplay = requestDisplay;
631 signalTransaction();
632 });
633 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 };
David Sodman105b7dc2017-11-04 20:28:14 -0700635 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
636 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800637 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800638 if (!mVrFlinger) {
639 ALOGE("Failed to start vrflinger");
640 }
641 }
642
Lloyd Pique755e3192018-01-31 16:46:15 -0800643 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
644 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
645 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700646
Mathias Agopian92a979a2012-08-02 18:32:23 -0700647 // initialize our drawing state
648 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700649
Andy McFadden13a082e2012-08-24 10:16:42 -0700650 // set initial conditions (e.g. unblank default device)
651 initializeDisplays();
652
David Sodmanbc815282017-11-05 18:57:52 -0800653 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700654
Wei Wangf9b05ee2017-07-19 20:59:39 -0700655 // Inform native graphics APIs whether the present timestamp is supported:
656 if (getHwComposer().hasCapability(
657 HWC2::Capability::PresentFenceIsNotReliable)) {
658 mStartPropertySetThread = new StartPropertySetThread(false);
659 } else {
660 mStartPropertySetThread = new StartPropertySetThread(true);
661 }
662
663 if (mStartPropertySetThread->Start() != NO_ERROR) {
664 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700668}
669
Romain Guy11d63f42017-07-20 12:47:14 -0700670void SurfaceFlinger::readPersistentProperties() {
671 char value[PROPERTY_VALUE_MAX];
672
673 property_get("persist.sys.sf.color_saturation", value, "1.0");
674 mSaturation = atof(value);
675 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100676
677 property_get("persist.sys.sf.native_mode", value, "0");
678 mForceNativeColorMode = atoi(value) == 1;
679 if (mForceNativeColorMode) {
680 ALOGV("Forcing native color mode");
681 }
Romain Guy11d63f42017-07-20 12:47:14 -0700682}
683
Mathias Agopiana67e4182012-06-19 17:26:12 -0700684void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800685 // Start boot animation service by setting a property mailbox
686 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800688 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700689 if (mStartPropertySetThread->join() != NO_ERROR) {
690 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700692}
693
Mathias Agopian875d8e12013-06-07 15:35:48 -0700694size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800695 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700696}
697
Mathias Agopian875d8e12013-06-07 15:35:48 -0700698size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800699 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700700}
701
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800703
Jamie Gennis582270d2011-08-17 18:19:00 -0700704bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800705 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800706 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800707 return authenticateSurfaceTextureLocked(bufferProducer);
708}
709
710bool SurfaceFlinger::authenticateSurfaceTextureLocked(
711 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800712 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800713 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800714}
715
Brian Anderson6b376712017-04-04 10:51:39 -0700716status_t SurfaceFlinger::getSupportedFrameTimestamps(
717 std::vector<FrameEvent>* outSupported) const {
718 *outSupported = {
719 FrameEvent::REQUESTED_PRESENT,
720 FrameEvent::ACQUIRE,
721 FrameEvent::LATCH,
722 FrameEvent::FIRST_REFRESH_START,
723 FrameEvent::LAST_REFRESH_START,
724 FrameEvent::GPU_COMPOSITION_DONE,
725 FrameEvent::DEQUEUE_READY,
726 FrameEvent::RELEASE,
727 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700728 ConditionalLock _l(mStateLock,
729 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700730 if (!getHwComposer().hasCapability(
731 HWC2::Capability::PresentFenceIsNotReliable)) {
732 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
733 }
734 return NO_ERROR;
735}
736
Dan Stoza7f7da322014-05-02 15:26:25 -0700737status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
738 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800739 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700740 return BAD_VALUE;
741 }
742
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500743 if (!display.get())
744 return NAME_NOT_FOUND;
745
Jesse Hall692c7232012-11-08 15:41:56 -0800746 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700747 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800748 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700749 type = i;
750 break;
751 }
752 }
753
754 if (type < 0) {
755 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700756 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758 // TODO: Not sure if display density should handled by SF any longer
759 class Density {
760 static int getDensityFromProperty(char const* propName) {
761 char property[PROPERTY_VALUE_MAX];
762 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800763 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700764 density = atoi(property);
765 }
766 return density;
767 }
768 public:
769 static int getEmuDensity() {
770 return getDensityFromProperty("qemu.sf.lcd_density"); }
771 static int getBuildDensity() {
772 return getDensityFromProperty("ro.sf.lcd_density"); }
773 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700774
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700776
Steven Thomas6d8110b2017-08-31 18:24:21 -0700777 ConditionalLock _l(mStateLock,
778 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 DisplayInfo info = DisplayInfo();
781
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 float xdpi = hwConfig->getDpiX();
783 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700784
785 if (type == DisplayDevice::DISPLAY_PRIMARY) {
786 // The density of the device is provided by a build property
787 float density = Density::getBuildDensity() / 160.0f;
788 if (density == 0) {
789 // the build doesn't provide a density -- this is wrong!
790 // use xdpi instead
791 ALOGE("ro.sf.lcd_density must be defined as a build property");
792 density = xdpi / 160.0f;
793 }
794 if (Density::getEmuDensity()) {
795 // if "qemu.sf.lcd_density" is specified, it overrides everything
796 xdpi = ydpi = density = Density::getEmuDensity();
797 density /= 160.0f;
798 }
799 info.density = density;
800
801 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800803 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700804 } else {
805 // TODO: where should this value come from?
806 static const int TV_DENSITY = 213;
807 info.density = TV_DENSITY / 160.0f;
808 info.orientation = 0;
809 }
810
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 info.w = hwConfig->getWidth();
812 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 info.xdpi = xdpi;
814 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900816 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817
Andy McFadden91b2ca82014-06-13 14:04:23 -0700818 // This is how far in advance a buffer must be queued for
819 // presentation at a given time. If you want a buffer to appear
820 // on the screen at time N, you must submit the buffer before
821 // (N - presentationDeadline).
822 //
823 // Normally it's one full refresh period (to give SF a chance to
824 // latch the buffer), but this can be reduced by configuring a
825 // DispSync offset. Any additional delays introduced by the hardware
826 // composer or panel must be accounted for here.
827 //
828 // We add an additional 1ms to allow for processing time and
829 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800831 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700832
833 // All non-virtual displays are currently considered secure.
834 info.secure = true;
835
Michael Wright28f24d02016-07-12 13:30:53 -0700836 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 }
838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 return NO_ERROR;
840}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700841
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800842status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700843 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800844 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700845 return BAD_VALUE;
846 }
847
848 // FIXME for now we always return stats for the primary display
849 memset(stats, 0, sizeof(*stats));
850 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
851 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
852 return NO_ERROR;
853}
854
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700855int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800856 if (display == nullptr) {
857 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800858 return BAD_VALUE;
859 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700860
861 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800862 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700863 return device->getActiveConfig();
864 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700865
Dan Stoza24a42e92015-03-09 10:04:11 -0700866 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700869void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
870 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
871 this);
872 int32_t type = hw->getDisplayType();
873 int currentMode = hw->getActiveConfig();
874
875 if (mode == currentMode) {
876 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
877 return;
878 }
879
880 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
881 ALOGW("Trying to set config for virtual display");
882 return;
883 }
884
885 hw->setActiveConfig(mode);
886 getHwComposer().setActiveConfig(type, mode);
887}
888
889status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
890 class MessageSetActiveConfig: public MessageBase {
891 SurfaceFlinger& mFlinger;
892 sp<IBinder> mDisplay;
893 int mMode;
894 public:
895 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
896 int mode) :
897 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
898 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700899 Vector<DisplayInfo> configs;
900 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700901 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700902 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700903 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700904 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700905 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800907 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700909 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
911 ALOGW("Attempt to set active config = %d for virtual display",
912 mMode);
913 } else {
914 mFlinger.setActiveConfigInternal(hw, mMode);
915 }
916 return true;
917 }
918 };
919 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
920 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700921 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700922}
Michael Wright28f24d02016-07-12 13:30:53 -0700923status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700924 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700925 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
926 return BAD_VALUE;
927 }
928
929 if (!display.get()) {
930 return NAME_NOT_FOUND;
931 }
932
933 int32_t type = NAME_NOT_FOUND;
934 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
935 if (display == mBuiltinDisplays[i]) {
936 type = i;
937 break;
938 }
939 }
940
941 if (type < 0) {
942 return type;
943 }
944
Peiyong Lina52f0292018-03-14 17:26:31 -0700945 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700946 {
947 ConditionalLock _l(mStateLock,
948 std::this_thread::get_id() != mMainThreadId);
949 modes = getHwComposer().getColorModes(type);
950 }
Michael Wright28f24d02016-07-12 13:30:53 -0700951 outColorModes->clear();
952 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
953
954 return NO_ERROR;
955}
956
Peiyong Lina52f0292018-03-14 17:26:31 -0700957ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700958 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700959 if (device != nullptr) {
960 return device->getActiveColorMode();
961 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700962 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700963}
964
965void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700966 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700967 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700968 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700969
970 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700971 return;
972 }
973
974 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
975 ALOGW("Trying to set config for virtual display");
976 return;
977 }
978
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600979 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
980 hw->getDisplayType());
981
Michael Wright28f24d02016-07-12 13:30:53 -0700982 hw->setActiveColorMode(mode);
983 getHwComposer().setActiveColorMode(type, mode);
984}
985
986
987status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700989 class MessageSetActiveColorMode: public MessageBase {
990 SurfaceFlinger& mFlinger;
991 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -0700993 public:
994 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -0700995 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -0700996 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
997 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -0700998 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -0700999 mFlinger.getDisplayColorModes(mDisplay, &modes);
1000 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001002 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1003 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001004 return true;
1005 }
1006 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1007 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001008 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1009 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001010 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001011 ALOGW("Attempt to set active color mode %s %d for virtual display",
1012 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001013 } else {
1014 mFlinger.setActiveColorModeInternal(hw, mMode);
1015 }
1016 return true;
1017 }
1018 };
1019 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1020 postMessageSync(msg);
1021 return NO_ERROR;
1022}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001023
Svetoslavd85084b2014-03-20 10:28:31 -07001024status_t SurfaceFlinger::clearAnimationFrameStats() {
1025 Mutex::Autolock _l(mStateLock);
1026 mAnimFrameTracker.clearStats();
1027 return NO_ERROR;
1028}
1029
1030status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1031 Mutex::Autolock _l(mStateLock);
1032 mAnimFrameTracker.getStats(outStats);
1033 return NO_ERROR;
1034}
1035
Dan Stozac4f471e2016-03-24 09:31:08 -07001036status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1037 HdrCapabilities* outCapabilities) const {
1038 Mutex::Autolock _l(mStateLock);
1039
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001040 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001041 if (displayDevice == nullptr) {
1042 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1043 return BAD_VALUE;
1044 }
1045
1046 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001047 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001048 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001049 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1050 // insert HDR10 as we will force client composition for HDR10
1051 // layers
1052 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1053 types.push_back(HAL_HDR_HDR10);
1054
1055 *outCapabilities = HdrCapabilities(types,
1056 capabilities->getDesiredMaxLuminance(),
1057 capabilities->getDesiredMaxAverageLuminance(),
1058 capabilities->getDesiredMinLuminance());
1059 } else {
1060 *outCapabilities = std::move(*capabilities);
1061 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001062 } else {
1063 return BAD_VALUE;
1064 }
1065
1066 return NO_ERROR;
1067}
1068
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1071 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073 if (mInjectVSyncs == enable) {
1074 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001075 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076
1077 if (enable) {
1078 ALOGV("VSync Injections enabled");
1079 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001080 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001081 mInjectorEventThread =
1082 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1083 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001085 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 } else {
1087 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001088 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089 }
1090
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001092 });
1093 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094 return NO_ERROR;
1095}
1096
1097status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 Mutex::Autolock _l(mStateLock);
1099
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 if (!mInjectVSyncs) {
1101 ALOGE("VSync Injections not enabled");
1102 return BAD_VALUE;
1103 }
1104 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1105 ALOGV("Injecting VSync inside SurfaceFlinger");
1106 mVSyncInjector->onInjectSyncEvent(when);
1107 }
1108 return NO_ERROR;
1109}
1110
Lloyd Pique755e3192018-01-31 16:46:15 -08001111status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1112 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001113 IPCThreadState* ipc = IPCThreadState::self();
1114 const int pid = ipc->getCallingPid();
1115 const int uid = ipc->getCallingUid();
1116 if ((uid != AID_SHELL) &&
1117 !PermissionCache::checkPermission(sDump, pid, uid)) {
1118 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1119 return PERMISSION_DENIED;
1120 }
1121
1122 // Try to acquire a lock for 1s, fail gracefully
1123 const status_t err = mStateLock.timedLock(s2ns(1));
1124 const bool locked = (err == NO_ERROR);
1125 if (!locked) {
1126 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1127 return TIMED_OUT;
1128 }
1129
1130 outLayers->clear();
1131 mCurrentState.traverseInZOrder([&](Layer* layer) {
1132 outLayers->push_back(layer->getLayerDebugInfo());
1133 });
1134
1135 mStateLock.unlock();
1136 return NO_ERROR;
1137}
1138
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001139// ----------------------------------------------------------------------------
1140
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001141sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1142 ISurfaceComposer::VsyncSource vsyncSource) {
1143 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1144 return mSFEventThread->createEventConnection();
1145 } else {
1146 return mEventThread->createEventConnection();
1147 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001148}
1149
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001150// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151
1152void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001153 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001154}
1155
1156void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001157 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158}
1159
1160void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001161 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162}
1163
1164void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001165 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001166 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167}
1168
1169status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001170 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001171 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001172}
1173
1174status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001175 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001176 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177 if (res == NO_ERROR) {
1178 msg->wait();
1179 }
1180 return res;
1181}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001183void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001184 do {
1185 waitForEvent();
1186 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001187}
1188
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189void SurfaceFlinger::enableHardwareVsync() {
1190 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001193 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1194 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001196 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001197}
1198
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200 Mutex::Autolock _l(mHWVsyncLock);
1201
Jesse Hall948fe0c2013-10-14 12:56:09 -07001202 if (makeAvailable) {
1203 mHWVsyncAvailable = true;
1204 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001205 // Hardware vsync is not currently available, so abort the resync
1206 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207 return;
1208 }
1209
David Sodman105b7dc2017-11-04 20:28:14 -07001210 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212
1213 mPrimaryDispSync.reset();
1214 mPrimaryDispSync.setPeriod(period);
1215
1216 if (!mPrimaryHWVsyncEnabled) {
1217 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1219 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = true;
1221 }
1222}
1223
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 Mutex::Autolock _l(mHWVsyncLock);
1226 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1228 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryDispSync.endResync();
1230 mPrimaryHWVsyncEnabled = false;
1231 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232 if (makeUnavailable) {
1233 mHWVsyncAvailable = false;
1234 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235}
1236
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237void SurfaceFlinger::resyncWithRateLimit() {
1238 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001239
1240 // No explicit locking is needed here since EventThread holds a lock while calling this method
1241 static nsecs_t sLastResyncAttempted = 0;
1242 const nsecs_t now = systemTime();
1243 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001244 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001245 }
Dan Stoza57164302017-05-08 14:03:54 -07001246 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001247}
1248
Steven Thomasb02664d2017-07-26 18:48:28 -07001249void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1250 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001252 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001253 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001254 return;
1255 }
1256
1257 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001258 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001259 return;
1260 }
1261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263
Jamie Gennisd1700752013-10-14 12:22:52 -07001264 { // Scope for the lock
1265 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001266 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001267 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001269 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001270
1271 if (needsHwVsync) {
1272 enableHardwareVsync();
1273 } else {
1274 disableHardwareVsync(false);
1275 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001276}
1277
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001279 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1280 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001281}
1282
Lloyd Pique715a2c12017-12-14 17:18:08 -08001283void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1284 HWC2::Connection connection) {
1285 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1286 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001287
Lloyd Piqueba04e622017-12-14 17:11:26 -08001288 // Ignore events that do not have the right sequenceId.
1289 if (sequenceId != getBE().mComposerSequenceId) {
1290 return;
1291 }
1292
Steven Thomasb02664d2017-07-26 18:48:28 -07001293 // Only lock if we're not on the main thread. This function is normally
1294 // called on a hwbinder thread, but for the primary display it's called on
1295 // the main thread with the state lock already held, so don't attempt to
1296 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001297 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001298
Lloyd Pique715a2c12017-12-14 17:18:08 -08001299 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001300
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001301 if (std::this_thread::get_id() == mMainThreadId) {
1302 // Process all pending hot plug events immediately if we are on the main thread.
1303 processDisplayHotplugEventsLocked();
1304 }
1305
Lloyd Piqueba04e622017-12-14 17:11:26 -08001306 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001307}
1308
Steven Thomasb02664d2017-07-26 18:48:28 -07001309void SurfaceFlinger::onRefreshReceived(int sequenceId,
1310 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001311 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001312 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001315 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001316}
1317
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001320 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 getHwComposer().setVsyncEnabled(disp,
1322 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001323}
1324
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001326void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001328 // Clear the drawing state so that the logic inside of
1329 // handleTransactionLocked will fire. It will determine the delta between
1330 // mCurrentState and mDrawingState and re-apply all changes when we make the
1331 // transition.
1332 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001333 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001334 mDisplays.clear();
1335}
1336
Steven Thomas050b2c82017-03-06 11:45:16 -08001337void SurfaceFlinger::updateVrFlinger() {
1338 if (!mVrFlinger)
1339 return;
1340 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001341 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001342 return;
1343 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001344
David Sodman105b7dc2017-11-04 20:28:14 -07001345 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 ALOGE("Vr flinger is only supported for remote hardware composer"
1347 " service connections. Ignoring request to transition to vr"
1348 " flinger.");
1349 mVrFlingerRequestsDisplay = false;
1350 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001351 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 int currentDisplayPowerMode = getDisplayDeviceLocked(
1356 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001363 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001364 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1365 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001366 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001367
David Sodman105b7dc2017-11-04 20:28:14 -07001368 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1369 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001370
1371 if (vrFlingerRequestsDisplay) {
1372 mVrFlinger->GrantDisplayOwnership();
1373 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376
1377 mVisibleRegionsDirty = true;
1378 invalidateHwcGeometry();
1379
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001380 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1382 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1383 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001386 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 const nsecs_t period = activeConfig->getVsyncPeriod();
1388 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 // Use phase of 0 since phase is not known.
1391 // Use latency of 0, which will snap to the ideal latency.
1392 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001393
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394 android_atomic_or(1, &mRepaintEverything);
1395 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396}
1397
Mathias Agopian4fec8732012-06-29 14:12:52 -07001398void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001399 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001400 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001401 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001402 bool frameMissed = !mHadClientComposition &&
1403 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001404 (mPreviousPresentFence->getSignalTime() ==
1405 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001406 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001407 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001408 signalLayerUpdate();
1409 break;
1410 }
1411
Steven Thomas050b2c82017-03-06 11:45:16 -08001412 // Now that we're going to make it to the handleMessageTransaction()
1413 // call below it's safe to call updateVrFlinger(), which will
1414 // potentially trigger a display handoff.
1415 updateVrFlinger();
1416
Dan Stoza6b9454d2014-11-07 16:00:59 -08001417 bool refreshNeeded = handleMessageTransaction();
1418 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001419 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001420 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001421 // Signal a refresh if a transaction modified the window state,
1422 // a new buffer was latched, or if HWC has requested a full
1423 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424 signalRefresh();
1425 }
1426 break;
1427 }
1428 case MessageQueue::REFRESH: {
1429 handleMessageRefresh();
1430 break;
1431 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432 }
1433}
1434
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001436 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001437 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001438 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001439 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001440 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001441 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001442}
1443
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001447}
1448
1449void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001450 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001451
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001452 mRefreshPending = false;
1453
Pablo Ceballos40845df2016-01-25 17:41:15 -08001454 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001455
Brian Andersond6927fb2016-07-23 23:37:30 -07001456 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001457 rebuildLayerStacks();
1458 setUpHWComposer();
1459 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001460 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001461 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001462 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001463
David Sodman105b7dc2017-11-04 20:28:14 -07001464 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001465
1466 mHadClientComposition = false;
1467 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1468 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1469 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001470 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001471 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001472
Dan Stoza9e56aa02015-11-02 13:00:03 -08001473 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001474}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476void SurfaceFlinger::doDebugFlashRegions()
1477{
1478 // is debugging enabled
1479 if (CC_LIKELY(!mDebugRegion))
1480 return;
1481
1482 const bool repaintEverything = mRepaintEverything;
1483 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1484 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001485 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001486 // transform the dirty region into this screen's coordinate space
1487 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1488 if (!dirtyRegion.isEmpty()) {
1489 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001490 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491
1492 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001493 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001494 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001495 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1496
Mathias Agopianda27af92012-09-13 18:17:13 -07001497 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498 }
1499 }
1500 }
1501
1502 postFramebuffer();
1503
1504 if (mDebugRegion > 1) {
1505 usleep(mDebugRegion * 1000);
1506 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001507
Dan Stoza9e56aa02015-11-02 13:00:03 -08001508 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001509 auto& displayDevice = mDisplays[displayId];
1510 if (!displayDevice->isDisplayOn()) {
1511 continue;
1512 }
1513
David Sodman105b7dc2017-11-04 20:28:14 -07001514 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1515 ALOGE_IF(result != NO_ERROR,
1516 "prepareFrame for display %zd failed:"
1517 " %d (%s)",
1518 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001519 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520}
1521
Adrian Roos1e1a1282017-11-01 19:05:31 +01001522void SurfaceFlinger::doTracing(const char* where) {
1523 ATRACE_CALL();
1524 ATRACE_NAME(where);
1525 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001526 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001527 }
1528}
1529
Brian Andersond6927fb2016-07-23 23:37:30 -07001530void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001532 ATRACE_CALL();
1533 ALOGV("preComposition");
1534
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001536 mDrawingState.traverseInZOrder([&](Layer* layer) {
1537 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538 needExtraInvalidate = true;
1539 }
Robert Carr2047fae2016-11-28 14:09:09 -08001540 });
1541
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542 if (needExtraInvalidate) {
1543 signalLayerUpdate();
1544 }
1545}
1546
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001547void SurfaceFlinger::updateCompositorTiming(
1548 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1549 std::shared_ptr<FenceTime>& presentFenceTime) {
1550 // Update queue of past composite+present times and determine the
1551 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001552 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001553 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001554 while (!getBE().mCompositePresentTimes.empty()) {
1555 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001556 // Cached values should have been updated before calling this method,
1557 // which helps avoid duplicate syscalls.
1558 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1559 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1560 break;
1561 }
1562 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001563 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564 }
1565
1566 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001567 while (getBE().mCompositePresentTimes.size() > 16) {
1568 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001569 }
1570
Brian Andersond0010582017-03-07 13:20:31 -08001571 setCompositorTimingSnapped(
1572 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1573}
1574
1575void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1576 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001577 // Integer division and modulo round toward 0 not -inf, so we need to
1578 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001579 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001580 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1581 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1582
Brian Andersond0010582017-03-07 13:20:31 -08001583 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1584 if (idealLatency <= 0) {
1585 idealLatency = vsyncInterval;
1586 }
1587
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588 // Snap the latency to a value that removes scheduling jitter from the
1589 // composition and present times, which often have >1ms of jitter.
1590 // Reducing jitter is important if an app attempts to extrapolate
1591 // something (such as user input) to an accurate diasplay time.
1592 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1593 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001594 nsecs_t bias = vsyncInterval / 2;
1595 int64_t extraVsyncs =
1596 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1597 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1598 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599
David Sodman99974d22017-11-28 12:04:33 -08001600 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1601 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1602 getBE().mCompositorTiming.interval = vsyncInterval;
1603 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604}
1605
1606void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001608 ATRACE_CALL();
1609 ALOGV("postComposition");
1610
Brian Anderson3546a3f2016-07-14 11:51:14 -07001611 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001612 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001613 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001614 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001615 }
1616
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001617 // |mStateLock| not needed as we are on the main thread
1618 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001619
David Sodman73beded2017-11-15 11:56:06 -08001620 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001621 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001622 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001623 glCompositionDoneFenceTime =
1624 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001625 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001626 } else {
1627 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1628 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001629
David Sodman73beded2017-11-15 11:56:06 -08001630 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001631 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001632 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001633 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001634
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1636 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1637
1638 // We use the refreshStartTime which might be sampled a little later than
1639 // when we started doing work for this frame, but that should be okay
1640 // since updateCompositorTiming has snapping logic.
1641 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001642 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001643 CompositorTiming compositorTiming;
1644 {
David Sodman99974d22017-11-28 12:04:33 -08001645 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1646 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001647 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648
Robert Carr2047fae2016-11-28 14:09:09 -08001649 mDrawingState.traverseInZOrder([&](Layer* layer) {
1650 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001651 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001652 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001653 recordBufferingStats(layer->getName().string(),
1654 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001655 }
Robert Carr2047fae2016-11-28 14:09:09 -08001656 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001657
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001658 if (presentFenceTime->isValid()) {
1659 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001660 enableHardwareVsync();
1661 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001662 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001663 }
1664 }
1665
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001666 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001667 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001668 enableHardwareVsync();
1669 }
1670 }
1671
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001672 if (mAnimCompositionPending) {
1673 mAnimCompositionPending = false;
1674
Brian Anderson4e606e32017-03-16 15:34:57 -07001675 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001676 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001677 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001678 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001679 // The HWC doesn't support present fences, so use the refresh
1680 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001682 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001683 mAnimFrameTracker.setActualPresentTime(presentTime);
1684 }
1685 mAnimFrameTracker.advanceFrame();
1686 }
Dan Stozab90cf072015-03-05 11:05:59 -08001687
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001688 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1689 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001690 return;
1691 }
1692
1693 nsecs_t currentTime = systemTime();
1694 if (mHasPoweredOff) {
1695 mHasPoweredOff = false;
1696 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001697 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001699 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1700 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001701 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001702 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001703 }
David Sodman4a36e932017-11-07 14:29:47 -08001704 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001705 }
David Sodman4a36e932017-11-07 14:29:47 -08001706 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707}
1708
1709void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 ATRACE_CALL();
1711 ALOGV("rebuildLayerStacks");
1712
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001714 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001715 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001716 mVisibleRegionsDirty = false;
1717 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001718
Jeff Sharkey76488112017-02-27 14:15:18 -07001719 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1720 Region opaqueRegion;
1721 Region dirtyRegion;
1722 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001723 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001724 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1725 const Transform& tr(displayDevice->getTransform());
1726 const Rect bounds(displayDevice->getBounds());
1727 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001728 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001729
Jeff Sharkey76488112017-02-27 14:15:18 -07001730 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001731 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001732 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1733 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001734 Region drawRegion(tr.transform(
1735 layer->visibleNonTransparentRegion));
1736 drawRegion.andSelf(bounds);
1737 if (!drawRegion.isEmpty()) {
1738 layersSortedByZ.add(layer);
1739 } else {
1740 // Clear out the HWC layer if this layer was
1741 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001742 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001743 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001744 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001745 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001746 // WM changes displayDevice->layerStack upon sleep/awake.
1747 // Here we make sure we delete the HWC layers even if
1748 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001749 hwcLayerDestroyed = layer->destroyHwcLayer(
1750 displayDevice->getHwcDisplayId());
1751 }
1752
1753 // If a layer is not going to get a release fence because
1754 // it is invisible, but it is also going to release its
1755 // old buffer, add it to the list of layers needing
1756 // fences.
1757 if (hwcLayerDestroyed) {
1758 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1759 mLayersWithQueuedFrames.cend(), layer);
1760 if (found != mLayersWithQueuedFrames.cend()) {
1761 layersNeedingFences.add(layer);
1762 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001763 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 });
1765 }
1766 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001767 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001768 displayDevice->undefinedRegion.set(bounds);
1769 displayDevice->undefinedRegion.subtractSelf(
1770 tr.transform(opaqueRegion));
1771 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001772 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001773 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001774}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001775
Romain Guy0147a172017-06-01 13:53:56 -07001776mat4 SurfaceFlinger::computeSaturationMatrix() const {
1777 if (mSaturation == 1.0f) {
1778 return mat4();
1779 }
1780
1781 // Rec.709 luma coefficients
1782 float3 luminance{0.213f, 0.715f, 0.072f};
1783 luminance *= 1.0f - mSaturation;
1784 return mat4(
1785 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1786 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1787 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1788 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1789 );
1790}
1791
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001792// pickColorMode translates a given dataspace into the best available color mode.
1793// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001794ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001795 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001796 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001797 }
1798
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001799 switch (dataSpace) {
1800 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1801 // system expects.
1802 case HAL_DATASPACE_UNKNOWN:
1803 case HAL_DATASPACE_SRGB:
1804 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001805 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001806 break;
1807
1808 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001809 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001810 break;
1811
1812 default:
1813 // TODO (courtneygo): Do we want to assert an error here?
1814 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1815 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001816 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001817 break;
1818 }
1819}
1820
Romain Guy0147a172017-06-01 13:53:56 -07001821android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001822 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001823 // Only support sRGB and Display-P3 right now.
1824 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1825 return HAL_DATASPACE_DISPLAY_P3;
1826 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001827 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1828 return HAL_DATASPACE_DISPLAY_P3;
1829 }
1830 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1831 return HAL_DATASPACE_DISPLAY_P3;
1832 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001833 if (!hasHdr) {
1834 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1835 return HAL_DATASPACE_DISPLAY_P3;
1836 }
1837 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1838 return HAL_DATASPACE_DISPLAY_P3;
1839 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001840 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001841
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001842 return HAL_DATASPACE_V0_SRGB;
1843}
1844
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001846 ATRACE_CALL();
1847 ALOGV("setUpHWComposer");
1848
Jesse Hall028dc8f2013-08-20 16:35:32 -07001849 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001850 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1851 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1852 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1853
1854 // If nothing has changed (!dirty), don't recompose.
1855 // If something changed, but we don't currently have any visible layers,
1856 // and didn't when we last did a composition, then skip it this time.
1857 // The second rule does two things:
1858 // - When all layers are removed from a display, we'll emit one black
1859 // frame, then nothing more until we get new layers.
1860 // - When a display is created with a private layer stack, we won't
1861 // emit any black frames until a layer is added to the layer stack.
1862 bool mustRecompose = dirty && !(empty && wasEmpty);
1863
1864 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1865 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1866 mustRecompose ? "doing" : "skipping",
1867 dirty ? "+" : "-",
1868 empty ? "+" : "-",
1869 wasEmpty ? "+" : "-");
1870
Dan Stoza71433162014-02-04 16:22:36 -08001871 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001872
1873 if (mustRecompose) {
1874 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1875 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001876 }
1877
Dan Stoza9e56aa02015-11-02 13:00:03 -08001878 // build the h/w work list
1879 if (CC_UNLIKELY(mGeometryInvalid)) {
1880 mGeometryInvalid = false;
1881 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1882 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1883 const auto hwcId = displayDevice->getHwcDisplayId();
1884 if (hwcId >= 0) {
1885 const Vector<sp<Layer>>& currentLayers(
1886 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001887 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001888 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001890 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001893 }
1894 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001895
Robert Carrae060832016-11-28 10:51:00 -08001896 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001897 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001899 }
1900 }
1901 }
1902 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 }
Riley Andrews03414a12014-07-01 14:22:59 -07001904
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001905
Romain Guy0147a172017-06-01 13:53:56 -07001906 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001907
Dan Stoza9e56aa02015-11-02 13:00:03 -08001908 // Set the per-frame data
1909 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1910 auto& displayDevice = mDisplays[displayId];
1911 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001912
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 if (hwcId < 0) {
1914 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001915 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001916 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001917 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001918 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1919 "display %zd: %d", displayId, result);
1920 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001922 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1923 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001924 !displayDevice->getHdrSupport()) {
1925 layer->forceClientComposition(hwcId);
1926 }
1927
chaviwc9232ed2017-11-14 15:31:15 -08001928 if (layer->getForceClientComposition(hwcId)) {
1929 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1930 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1931 continue;
1932 }
1933
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 layer->setPerFrameData(displayDevice);
1935 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001936
1937 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001938 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001939 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1940
1941 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001942 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1943 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001944 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1945 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1946 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1947 }
1948 newColorMode = pickColorMode(newDataSpace);
1949
Thierry Strudel2924d012017-08-14 15:19:37 -07001950 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001951 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 }
1953
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001954 mPreviousColorMatrix = colorMatrix;
1955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001957 auto& displayDevice = mDisplays[displayId];
1958 if (!displayDevice->isDisplayOn()) {
1959 continue;
1960 }
1961
David Sodman105b7dc2017-11-04 20:28:14 -07001962 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1964 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001965 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001966}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968void SurfaceFlinger::doComposition() {
1969 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 ALOGV("doComposition");
1971
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001972 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001973 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001974 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001975 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001976 // transform the dirty region into this screen's coordinate space
1977 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001978
1979 // repaint the framebuffer (if needed)
1980 doDisplayComposition(hw, dirtyRegion);
1981
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001983 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001984 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001985 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001986 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001987}
1988
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989void SurfaceFlinger::postFramebuffer()
1990{
Mathias Agopian841cde52012-03-01 15:44:37 -08001991 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001993
Mathias Agopiana44b0412011-10-16 18:46:35 -07001994 const nsecs_t now = systemTime();
1995 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001996
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1998 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001999 if (!displayDevice->isDisplayOn()) {
2000 continue;
2001 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 const auto hwcId = displayDevice->getHwcDisplayId();
2003 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002004 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002005 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002006 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002007 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002009 // The layer buffer from the previous frame (if any) is released
2010 // by HWC only when the release fence from this frame (if any) is
2011 // signaled. Always get the release fence from HWC first.
2012 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002013 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002014
2015 // If the layer was client composited in the previous frame, we
2016 // need to merge with the previous client target acquire fence.
2017 // Since we do not track that, always merge with the current
2018 // client target acquire fence when it is available, even though
2019 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002021 releaseFence = Fence::merge("LayerRelease", releaseFence,
2022 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002023 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002024
Dan Stoza9e56aa02015-11-02 13:00:03 -08002025 layer->onLayerDisplayed(releaseFence);
2026 }
Chia-I Wu83806892017-11-16 10:50:20 -08002027
2028 // We've got a list of layers needing fences, that are disjoint with
2029 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2030 // supply them with the present fence.
2031 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002032 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002033 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2034 layer->onLayerDisplayed(presentFence);
2035 }
2036 }
2037
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002039 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002040 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002041 }
2042
Mathias Agopiana44b0412011-10-16 18:46:35 -07002043 mLastSwapBufferTime = systemTime() - now;
2044 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002045
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002046 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002047 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2048 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2049 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2050 logFrameStats();
2051 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002053}
2054
Mathias Agopian87baae12012-07-31 12:38:26 -07002055void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056{
Mathias Agopian841cde52012-03-01 15:44:37 -08002057 ATRACE_CALL();
2058
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002059 // here we keep a copy of the drawing state (that is the state that's
2060 // going to be overwritten by handleTransactionLocked()) outside of
2061 // mStateLock so that the side-effects of the State assignment
2062 // don't happen with mStateLock held (which can cause deadlocks).
2063 State drawingState(mDrawingState);
2064
Mathias Agopianca4d3602011-05-19 15:38:14 -07002065 Mutex::Autolock _l(mStateLock);
2066 const nsecs_t now = systemTime();
2067 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002068
Mathias Agopianca4d3602011-05-19 15:38:14 -07002069 // Here we're guaranteed that some transaction flags are set
2070 // so we can call handleTransactionLocked() unconditionally.
2071 // We call getTransactionFlags(), which will also clear the flags,
2072 // with mStateLock held to guarantee that mCurrentState won't change
2073 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002074
Mathias Agopiane57f2922012-08-09 16:29:12 -07002075 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002076 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002077
Mathias Agopianca4d3602011-05-19 15:38:14 -07002078 mLastTransactionTime = systemTime() - now;
2079 mDebugInTransaction = 0;
2080 invalidateHwcGeometry();
2081 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002082}
2083
Lloyd Pique715a2c12017-12-14 17:18:08 -08002084DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2085 HWC2::Connection connection) const {
2086 // Figure out whether the event is for the primary display or an
2087 // external display by matching the Hwc display id against one for a
2088 // connected display. If we did not find a match, we then check what
2089 // displays are not already connected to determine the type. If we don't
2090 // have a connected primary display, we assume the new display is meant to
2091 // be the primary display, and then if we don't have an external display,
2092 // we assume it is that.
2093 const auto primaryDisplayId =
2094 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2095 const auto externalDisplayId =
2096 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2097 if (primaryDisplayId && primaryDisplayId == display) {
2098 return DisplayDevice::DISPLAY_PRIMARY;
2099 } else if (externalDisplayId && externalDisplayId == display) {
2100 return DisplayDevice::DISPLAY_EXTERNAL;
2101 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2102 return DisplayDevice::DISPLAY_PRIMARY;
2103 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2104 return DisplayDevice::DISPLAY_EXTERNAL;
2105 }
2106
2107 return DisplayDevice::DISPLAY_ID_INVALID;
2108}
2109
Lloyd Piqueba04e622017-12-14 17:11:26 -08002110void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2111 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002112 auto displayType = determineDisplayType(event.display, event.connection);
2113 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2114 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2115 continue;
2116 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002117
2118 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2119 ALOGE("External displays are not supported by the vr hardware composer.");
2120 continue;
2121 }
2122
Lloyd Pique715a2c12017-12-14 17:18:08 -08002123 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002124
2125 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002126 if (!mBuiltinDisplays[displayType].get()) {
2127 ALOGV("Creating built in display %d", displayType);
2128 mBuiltinDisplays[displayType] = new BBinder();
2129 // All non-virtual displays are currently considered secure.
2130 DisplayDeviceState info(displayType, true);
2131 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2132 "Built-in Screen" : "External Screen";
2133 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2134 mInterceptor.saveDisplayCreation(info);
2135 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002136 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002137 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002138
Lloyd Piquefcd86612017-12-14 17:15:36 -08002139 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2140 if (idx >= 0) {
2141 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2142 mInterceptor.saveDisplayDeletion(info.displayId);
2143 mCurrentState.displays.removeItemsAt(idx);
2144 }
2145 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002146 }
2147
2148 processDisplayChangesLocked();
2149 }
2150
2151 mPendingHotplugEvents.clear();
2152}
2153
Lloyd Pique347200f2017-12-14 17:00:15 -08002154void SurfaceFlinger::processDisplayChangesLocked() {
2155 // here we take advantage of Vector's copy-on-write semantics to
2156 // improve performance by skipping the transaction entirely when
2157 // know that the lists are identical
2158 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2159 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2160 if (!curr.isIdenticalTo(draw)) {
2161 mVisibleRegionsDirty = true;
2162 const size_t cc = curr.size();
2163 size_t dc = draw.size();
2164
2165 // find the displays that were removed
2166 // (ie: in drawing state but not in current state)
2167 // also handle displays that changed
2168 // (ie: displays that are in both lists)
2169 for (size_t i = 0; i < dc;) {
2170 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2171 if (j < 0) {
2172 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002173 // Call makeCurrent() on the primary display so we can
2174 // be sure that nothing associated with this display
2175 // is current.
2176 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2177 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2178 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2179 if (hw != nullptr) hw->disconnect(getHwComposer());
2180 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2181 mEventThread->onHotplugReceived(draw[i].type, false);
2182 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002183 } else {
2184 // this display is in both lists. see if something changed.
2185 const DisplayDeviceState& state(curr[j]);
2186 const wp<IBinder>& display(curr.keyAt(j));
2187 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2188 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2189 if (state_binder != draw_binder) {
2190 // changing the surface is like destroying and
2191 // recreating the DisplayDevice, so we just remove it
2192 // from the drawing state, so that it get re-added
2193 // below.
2194 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2195 if (hw != nullptr) hw->disconnect(getHwComposer());
2196 mDisplays.removeItem(display);
2197 mDrawingState.displays.removeItemsAt(i);
2198 dc--;
2199 // at this point we must loop to the next item
2200 continue;
2201 }
2202
2203 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2204 if (disp != nullptr) {
2205 if (state.layerStack != draw[i].layerStack) {
2206 disp->setLayerStack(state.layerStack);
2207 }
2208 if ((state.orientation != draw[i].orientation) ||
2209 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2210 disp->setProjection(state.orientation, state.viewport, state.frame);
2211 }
2212 if (state.width != draw[i].width || state.height != draw[i].height) {
2213 disp->setDisplaySize(state.width, state.height);
2214 }
2215 }
2216 }
2217 ++i;
2218 }
2219
2220 // find displays that were added
2221 // (ie: in current state but not in drawing state)
2222 for (size_t i = 0; i < cc; i++) {
2223 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2224 const DisplayDeviceState& state(curr[i]);
2225
2226 sp<DisplaySurface> dispSurface;
2227 sp<IGraphicBufferProducer> producer;
2228 sp<IGraphicBufferProducer> bqProducer;
2229 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002230 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002231
2232 int32_t hwcId = -1;
2233 if (state.isVirtualDisplay()) {
2234 // Virtual displays without a surface are dormant:
2235 // they have external state (layer stack, projection,
2236 // etc.) but no internal state (i.e. a DisplayDevice).
2237 if (state.surface != nullptr) {
2238 // Allow VR composer to use virtual displays.
2239 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2240 int width = 0;
2241 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2242 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2243 int height = 0;
2244 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2245 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2246 int intFormat = 0;
2247 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2248 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2249 auto format = static_cast<android_pixel_format_t>(intFormat);
2250
2251 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2252 }
2253
2254 // TODO: Plumb requested format back up to consumer
2255
2256 sp<VirtualDisplaySurface> vds =
2257 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2258 bqProducer, bqConsumer,
2259 state.displayName);
2260
2261 dispSurface = vds;
2262 producer = vds;
2263 }
2264 } else {
2265 ALOGE_IF(state.surface != nullptr,
2266 "adding a supported display, but rendering "
2267 "surface is provided (%p), ignoring it",
2268 state.surface.get());
2269
2270 hwcId = state.type;
2271 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2272 producer = bqProducer;
2273 }
2274
2275 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002276
Lloyd Pique347200f2017-12-14 17:00:15 -08002277 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002278 bool hasWideColorSupport = false;
2279 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002280 std::vector<ColorMode> modes =
Lloyd Piquefcd86612017-12-14 17:15:36 -08002281 getHwComposer().getColorModes(state.type);
Peiyong Lina52f0292018-03-14 17:26:31 -07002282 for (ColorMode colorMode : modes) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002283 switch (colorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002284 case ColorMode::DISPLAY_P3:
2285 case ColorMode::ADOBE_RGB:
2286 case ColorMode::DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002287 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002288 break;
2289 default:
2290 break;
2291 }
2292 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002293 }
2294
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002295 bool hasHdrSupport = false;
2296 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2297 getHwComposer().getHdrCapabilities(state.type);
2298 if (hdrCapabilities) {
2299 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2300 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2301 hasHdrSupport = iter != types.cend();
2302 }
2303
Lloyd Pique347200f2017-12-14 17:00:15 -08002304 sp<DisplayDevice> hw =
2305 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002306 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002307 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002308
Peiyong Lina52f0292018-03-14 17:26:31 -07002309 ColorMode defaultColorMode = ColorMode::NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002310 if (hasWideColorSupport) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002311 defaultColorMode = ColorMode::SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002312 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002313 setActiveColorModeInternal(hw, defaultColorMode);
2314 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002315 hw->setLayerStack(state.layerStack);
2316 hw->setProjection(state.orientation, state.viewport, state.frame);
2317 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002318
Lloyd Pique347200f2017-12-14 17:00:15 -08002319 mDisplays.add(display, hw);
2320 if (!state.isVirtualDisplay()) {
2321 mEventThread->onHotplugReceived(state.type, true);
2322 }
2323 }
2324 }
2325 }
2326 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327
2328 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002329}
2330
Mathias Agopian87baae12012-07-31 12:38:26 -07002331void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002332{
Dan Stoza7dde5992015-05-22 09:51:44 -07002333 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002334 mCurrentState.traverseInZOrder([](Layer* layer) {
2335 layer->notifyAvailableFrames();
2336 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 /*
2339 * Traversal of the children
2340 * (perform the transaction for each of them if needed)
2341 */
2342
Mathias Agopian3559b072012-08-15 13:46:03 -07002343 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002344 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002346 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347
2348 const uint32_t flags = layer->doTransaction(0);
2349 if (flags & Layer::eVisibleRegion)
2350 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002351 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352 }
2353
2354 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002355 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 */
2357
Mathias Agopiane57f2922012-08-09 16:29:12 -07002358 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002359 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002360 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002361 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362
Mathias Agopian84300952012-11-21 16:02:13 -08002363 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2364 // The transform hint might have changed for some layers
2365 // (either because a display has changed, or because a layer
2366 // as changed).
2367 //
2368 // Walk through all the layers in currentLayers,
2369 // and update their transform hint.
2370 //
2371 // If a layer is visible only on a single display, then that
2372 // display is used to calculate the hint, otherwise we use the
2373 // default display.
2374 //
2375 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2376 // the hint is set before we acquire a buffer from the surface texture.
2377 //
2378 // NOTE: layer transactions have taken place already, so we use their
2379 // drawing state. However, SurfaceFlinger's own transaction has not
2380 // happened yet, so we must use the current state layer list
2381 // (soon to become the drawing state list).
2382 //
2383 sp<const DisplayDevice> disp;
2384 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002385 bool first = true;
2386 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002387 // NOTE: we rely on the fact that layers are sorted by
2388 // layerStack first (so we don't have to traverse the list
2389 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002390 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002391 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002392 currentlayerStack = layerStack;
2393 // figure out if this layerstack is mirrored
2394 // (more than one display) if so, pick the default display,
2395 // if not, pick the only display it's on.
2396 disp.clear();
2397 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2398 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002399 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002400 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002401 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002402 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002403 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002404 break;
2405 }
2406 }
2407 }
2408 }
Chet Haase91d25932013-04-11 15:24:55 -07002409
Robert Carr56a0b9a2017-12-04 16:06:13 -08002410 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002411 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002412 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2413 // redraw after transform hint changes. See bug 8508397.
2414
2415 // could be null when this layer is using a layerStack
2416 // that is not visible on any display. Also can occur at
2417 // screen off/on times.
2418 disp = getDefaultDisplayDeviceLocked();
2419 }
2420 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002421 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002422 if (disp != nullptr) {
2423 layer->updateTransformHint(disp);
2424 }
Robert Carr2047fae2016-11-28 14:09:09 -08002425
2426 first = false;
2427 });
Mathias Agopian84300952012-11-21 16:02:13 -08002428 }
2429
2430
Mathias Agopian3559b072012-08-15 13:46:03 -07002431 /*
2432 * Perform our own transaction if needed
2433 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002434
2435 if (mLayersAdded) {
2436 mLayersAdded = false;
2437 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002438 mVisibleRegionsDirty = true;
2439 }
2440
2441 // some layers might have been removed, so
2442 // we need to update the regions they're exposing.
2443 if (mLayersRemoved) {
2444 mLayersRemoved = false;
2445 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002446 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002447 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002448 // this layer is not visible anymore
2449 // TODO: we could traverse the tree from front to back and
2450 // compute the actual visible region
2451 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 Region visibleReg;
2453 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002454 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002455 }
Robert Carr2047fae2016-11-28 14:09:09 -08002456 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 }
2458
2459 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002460
2461 updateCursorAsync();
2462}
2463
2464void SurfaceFlinger::updateCursorAsync()
2465{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002466 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2467 auto& displayDevice = mDisplays[displayId];
2468 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002469 continue;
2470 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471
2472 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2473 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002474 }
2475 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002476}
2477
2478void SurfaceFlinger::commitTransaction()
2479{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002480 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002481 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002482 for (const auto& l : mLayersPendingRemoval) {
2483 recordBufferingStats(l->getName().string(),
2484 l->getOccupancyHistory(true));
2485 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002486 }
2487 mLayersPendingRemoval.clear();
2488 }
2489
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002490 // If this transaction is part of a window animation then the next frame
2491 // we composite should be considered an animation as well.
2492 mAnimCompositionPending = mAnimTransactionPending;
2493
Mathias Agopian4fec8732012-06-29 14:12:52 -07002494 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002495 mDrawingState.traverseInZOrder([](Layer* layer) {
2496 layer->commitChildList();
2497 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002498 mTransactionPending = false;
2499 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002500 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501}
2502
Chia-I Wuab0c3192017-08-01 11:29:00 -07002503void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002504 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505{
Mathias Agopian841cde52012-03-01 15:44:37 -08002506 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002507 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 Region aboveOpaqueLayers;
2510 Region aboveCoveredLayers;
2511 Region dirty;
2512
Mathias Agopian87baae12012-07-31 12:38:26 -07002513 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514
Robert Carr2047fae2016-11-28 14:09:09 -08002515 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002517 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
Jesse Hall01e29052013-02-19 16:13:35 -08002519 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002520 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002521 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002522
Mathias Agopianab028732010-03-16 16:41:46 -07002523 /*
2524 * opaqueRegion: area of a surface that is fully opaque.
2525 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002527
2528 /*
2529 * visibleRegion: area of a surface that is visible on screen
2530 * and not fully transparent. This is essentially the layer's
2531 * footprint minus the opaque regions above it.
2532 * Areas covered by a translucent surface are considered visible.
2533 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002535
2536 /*
2537 * coveredRegion: area of a surface that is covered by all
2538 * visible regions above it (which includes the translucent areas).
2539 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002541
Jesse Halla8026d22012-09-25 13:25:04 -07002542 /*
2543 * transparentRegion: area of a surface that is hinted to be completely
2544 * transparent. This is only used to tell when the layer has no visible
2545 * non-transparent regions and can be removed from the layer list. It
2546 * does not affect the visibleRegion of this layer or any layers
2547 * beneath it. The hint may not be correct if apps don't respect the
2548 * SurfaceView restrictions (which, sadly, some don't).
2549 */
2550 Region transparentRegion;
2551
Mathias Agopianab028732010-03-16 16:41:46 -07002552
2553 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002554 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002555 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002556 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002558 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002559 if (!visibleRegion.isEmpty()) {
2560 // Remove the transparent area from the visible region
2561 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002562 if (tr.preserveRects()) {
2563 // transform the transparent region
2564 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002565 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002566 // transformation too complex, can't do the
2567 // transparent region optimization.
2568 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 }
Mathias Agopianab028732010-03-16 16:41:46 -07002570 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571
Mathias Agopianab028732010-03-16 16:41:46 -07002572 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002574 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002575 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2576 // the opaque region is the layer's footprint
2577 opaqueRegion = visibleRegion;
2578 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 }
2580 }
2581
Robert Carre5f4f692018-01-12 13:12:28 -08002582 if (visibleRegion.isEmpty()) {
2583 layer->clearVisibilityRegions();
2584 return;
2585 }
2586
Mathias Agopianab028732010-03-16 16:41:46 -07002587 // Clip the covered region to the visible region
2588 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2589
2590 // Update aboveCoveredLayers for next (lower) layer
2591 aboveCoveredLayers.orSelf(visibleRegion);
2592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 // subtract the opaque region covered by the layers above us
2594 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595
2596 // compute this layer's dirty region
2597 if (layer->contentDirty) {
2598 // we need to invalidate the whole region
2599 dirty = visibleRegion;
2600 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002601 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 layer->contentDirty = false;
2603 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002604 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002605 * the exposed region consists of two components:
2606 * 1) what's VISIBLE now and was COVERED before
2607 * 2) what's EXPOSED now less what was EXPOSED before
2608 *
2609 * note that (1) is conservative, we start with the whole
2610 * visible region but only keep what used to be covered by
2611 * something -- which mean it may have been exposed.
2612 *
2613 * (2) handles areas that were not covered by anything but got
2614 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002615 */
Mathias Agopianab028732010-03-16 16:41:46 -07002616 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002617 const Region oldVisibleRegion = layer->visibleRegion;
2618 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002619 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2620 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 }
2622 dirty.subtractSelf(aboveOpaqueLayers);
2623
2624 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002625 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626
Mathias Agopianab028732010-03-16 16:41:46 -07002627 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002629
Jesse Halla8026d22012-09-25 13:25:04 -07002630 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631 layer->setVisibleRegion(visibleRegion);
2632 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002633 layer->setVisibleNonTransparentRegion(
2634 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002635 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636
Mathias Agopian87baae12012-07-31 12:38:26 -07002637 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638}
2639
Chia-I Wuab0c3192017-08-01 11:29:00 -07002640void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002641 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002642 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002643 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002644 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002645 }
2646 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002647}
2648
Dan Stoza6b9454d2014-11-07 16:00:59 -08002649bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 ALOGV("handlePageFlip");
2652
Brian Andersond6927fb2016-07-23 23:37:30 -07002653 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
Mathias Agopian4fec8732012-06-29 14:12:52 -07002655 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002656 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002657 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002658
2659 // Store the set of layers that need updates. This set must not change as
2660 // buffers are being latched, as this could result in a deadlock.
2661 // Example: Two producers share the same command stream and:
2662 // 1.) Layer 0 is latched
2663 // 2.) Layer 0 gets a new frame
2664 // 2.) Layer 1 gets a new frame
2665 // 3.) Layer 1 is latched.
2666 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2667 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002668 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002669 if (layer->hasQueuedFrame()) {
2670 frameQueued = true;
2671 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002672 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002673 } else {
2674 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002675 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002676 } else {
2677 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002678 }
Robert Carr2047fae2016-11-28 14:09:09 -08002679 });
2680
Dan Stoza9e56aa02015-11-02 13:00:03 -08002681 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002682 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002683 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002684 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002685 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002686 newDataLatched = true;
2687 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002689
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002690 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002691
2692 // If we will need to wake up at some time in the future to deal with a
2693 // queued frame that shouldn't be displayed during this vsync period, wake
2694 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002695 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002696 signalLayerUpdate();
2697 }
2698
2699 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002700 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701}
2702
Mathias Agopianad456f92011-01-13 17:53:01 -08002703void SurfaceFlinger::invalidateHwcGeometry()
2704{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002706}
2707
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002708
Fabien Sanglard830b8472016-11-30 16:35:58 -08002709void SurfaceFlinger::doDisplayComposition(
2710 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002711 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712{
Dan Stoza71433162014-02-04 16:22:36 -08002713 // We only need to actually compose the display if:
2714 // 1) It is being handled by hardware composer, which may need this to
2715 // keep its virtual display state machine in sync, or
2716 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002717 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002718 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002719 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002720 return;
2721 }
2722
Dan Stoza9e56aa02015-11-02 13:00:03 -08002723 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002724 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002725
2726 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002727 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728}
2729
Chia-I Wub02087d2017-11-09 10:19:54 -08002730bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002731{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002733
Chia-I Wub02087d2017-11-09 10:19:54 -08002734 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002735 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002737
2738 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002739 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2740 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002741 if (applyColorMatrix) {
2742 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2743 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2744 }
2745
David Sodman105b7dc2017-11-04 20:28:14 -07002746 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 if (hasClientComposition) {
2748 ALOGV("hasClientComposition");
2749
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002750 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002751 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002752 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002753 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2754 }
2755 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2756
Chia-I Wu7f402902017-11-09 12:51:10 -08002757 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002758 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002760 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002761
2762 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002763 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002764 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2765 }
2766 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002767 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002768
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002769 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002770 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002772 // when using overlays, we assume a fully transparent framebuffer
2773 // NOTE: we could reduce how much we need to clear, for instance
2774 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002775 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002776 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002777 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002778 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002779 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002780 // we're left with the letterbox region
2781 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002783
2784 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002786
Mathias Agopianb9494d52012-04-18 02:28:45 -07002787 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002788 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002789 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002791 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002792 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002793
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002795 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002796 // scissor on the main display. It should never be needed
2797 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 const Rect& bounds(displayDevice->getBounds());
2799 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002800 if (scissor != bounds) {
2801 // scissor doesn't match the screen's dimensions, so we
2802 // need to clear everything outside of it and enable
2803 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002804
Mathias Agopianf45c5102012-10-24 16:29:17 -07002805 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002807 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002808 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002809 }
2810 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002811 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002812
Mathias Agopian85d751c2012-08-29 16:59:24 -07002813 /*
2814 * and then, render the layers targeted at the framebuffer
2815 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002816
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 ALOGV("Rendering client layers");
2818 const Transform& displayTransform = displayDevice->getTransform();
2819 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002820 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 bool firstLayer = true;
2822 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002823 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002824 displayTransform.transform(layer->visibleRegion)));
2825 ALOGV("Layer: %s", layer->getName().string());
2826 ALOGV(" Composition type: %s",
2827 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002828 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 switch (layer->getCompositionType(hwcId)) {
2830 case HWC2::Composition::Cursor:
2831 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002832 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002834 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002836 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002838 // never clear the very first layer since we're
2839 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002840 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002841 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002842 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002843 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002845 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002846 break;
2847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002849 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002850 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002851 } else {
2852 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002853 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002855 }
2856 } else {
2857 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002859 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002860 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002861 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002862 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002863 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002864 }
2865 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002866
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002867 if (applyColorMatrix) {
2868 getRenderEngine().setupColorTransform(oldColorMatrix);
2869 }
2870
Mathias Agopianf45c5102012-10-24 16:29:17 -07002871 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002872 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002873 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874}
2875
Fabien Sanglard830b8472016-11-30 16:35:58 -08002876void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2877 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002878 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002879 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880}
2881
Dan Stoza7d89d062015-04-30 13:29:25 -07002882status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002883 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002884 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 const sp<Layer>& lbc,
2886 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002887{
Dan Stoza7d89d062015-04-30 13:29:25 -07002888 // add this layer to the current state list
2889 {
2890 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002891 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002892 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2893 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002894 return NO_MEMORY;
2895 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 if (parent == nullptr) {
2897 mCurrentState.layersSortedByZ.add(lbc);
2898 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002899 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002900 ALOGE("addClientLayer called with a removed parent");
2901 return NAME_NOT_FOUND;
2902 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 parent->addChild(lbc);
2904 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002905
Dan Stoza101d8dc2018-02-27 15:42:25 -08002906 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002907 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2908 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2909 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2910 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2911 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 mLayersAdded = true;
2913 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002914 }
2915
Mathias Agopian96f08192010-06-02 23:28:45 -07002916 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002917 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002918
Dan Stoza7d89d062015-04-30 13:29:25 -07002919 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002920}
2921
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002922status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002923 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002924 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2925}
Robert Carr7f9b8992017-03-10 11:08:39 -08002926
chaviwca27f252018-02-06 16:46:39 -08002927status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2928 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002929 if (layer->isPendingRemoval()) {
2930 return NO_ERROR;
2931 }
2932
Robert Carr1f0a16a2016-10-24 16:27:39 -07002933 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002934 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002935 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002936 if (topLevelOnly) {
2937 return NO_ERROR;
2938 }
2939
Chia-I Wu98f1c102017-05-30 14:54:08 -07002940 sp<Layer> ancestor = p;
2941 while (ancestor->getParent() != nullptr) {
2942 ancestor = ancestor->getParent();
2943 }
2944 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2945 ALOGE("removeLayer called with a layer whose parent has been removed");
2946 return NAME_NOT_FOUND;
2947 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002948
2949 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002950 } else {
2951 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002952 }
2953
Robert Carr136e2f62017-02-08 17:54:29 -08002954 // As a matter of normal operation, the LayerCleaner will produce a second
2955 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2956 // so we will succeed in promoting it, but it's already been removed
2957 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2958 // otherwise something has gone wrong and we are leaking the layer.
2959 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002960 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2961 layer->getName().string(),
2962 (p != nullptr) ? p->getName().string() : "no-parent");
2963 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002964 } else if (index < 0) {
2965 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002966 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002967
Chia-I Wuc6657022017-08-15 11:18:17 -07002968 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002969 mLayersPendingRemoval.add(layer);
2970 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002971 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002972 setTransactionFlags(eTransactionNeeded);
2973 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974}
2975
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002976uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002977 return android_atomic_release_load(&mTransactionFlags);
2978}
2979
Mathias Agopian3f844832013-08-07 21:24:32 -07002980uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2982}
2983
Mathias Agopian3f844832013-08-07 21:24:32 -07002984uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2986 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002987 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 }
2989 return old;
2990}
2991
chaviwca27f252018-02-06 16:46:39 -08002992bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
2993 for (const ComposerState& state : states) {
2994 // Here we need to check that the interface we're given is indeed
2995 // one of our own. A malicious client could give us a nullptr
2996 // IInterface, or one of its own or even one of our own but a
2997 // different type. All these situations would cause us to crash.
2998 if (state.client == nullptr) {
2999 return true;
3000 }
3001
3002 sp<IBinder> binder = IInterface::asBinder(state.client);
3003 if (binder == nullptr) {
3004 return true;
3005 }
3006
3007 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3008 return true;
3009 }
3010 }
3011 return false;
3012}
3013
Mathias Agopian8b33f032012-07-24 20:43:54 -07003014void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003015 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003016 const Vector<DisplayState>& displays,
3017 uint32_t flags)
3018{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003019 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003020 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003021 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022
chaviwca27f252018-02-06 16:46:39 -08003023 if (containsAnyInvalidClientState(states)) {
3024 return;
3025 }
3026
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003027 if (flags & eAnimation) {
3028 // For window updates that are part of an animation we must wait for
3029 // previous animation "frames" to be handled.
3030 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003031 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003032 if (CC_UNLIKELY(err != NO_ERROR)) {
3033 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003034 // caller after a few seconds.
3035 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3036 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003037 mAnimTransactionPending = false;
3038 break;
3039 }
3040 }
3041 }
3042
chaviwca27f252018-02-06 16:46:39 -08003043 for (const DisplayState& display : displays) {
3044 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003045 }
3046
chaviwca27f252018-02-06 16:46:39 -08003047 for (const ComposerState& state : states) {
3048 transactionFlags |= setClientStateLocked(state);
3049 }
3050
3051 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3052 // as destroyed should only occur after setting all other states. This is to allow for a
3053 // child re-parent to happen before marking its original parent as destroyed (which would
3054 // then mark the child as destroyed).
3055 for (const ComposerState& state : states) {
3056 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003057 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003058
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003059 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3060 // anyway. This can be used as a flush mechanism for previous async transactions.
3061 // Empty animation transaction can be used to simulate back-pressure, so also force a
3062 // transaction for empty animation transactions.
3063 if (transactionFlags == 0 &&
3064 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003065 transactionFlags = eTransactionNeeded;
3066 }
3067
Mathias Agopian386aa982011-11-07 21:58:03 -08003068 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003069 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003070 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003071 }
Irvel468051e2016-06-13 16:44:44 -07003072
Mathias Agopian386aa982011-11-07 21:58:03 -08003073 // this triggers the transaction
3074 setTransactionFlags(transactionFlags);
3075
3076 // if this is a synchronous transaction, wait for it to take effect
3077 // before returning.
3078 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003079 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003080 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003081 if (flags & eAnimation) {
3082 mAnimTransactionPending = true;
3083 }
3084 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003085 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3086 if (CC_UNLIKELY(err != NO_ERROR)) {
3087 // just in case something goes wrong in SF, return to the
3088 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003089 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3090 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003091 break;
3092 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003093 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 }
3095}
3096
Mathias Agopiane57f2922012-08-09 16:29:12 -07003097uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3098{
Jesse Hall9a143922012-10-04 16:29:19 -07003099 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3100 if (dpyIdx < 0)
3101 return 0;
3102
Mathias Agopiane57f2922012-08-09 16:29:12 -07003103 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003104 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003105 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003106 const uint32_t what = s.what;
3107 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003108 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003109 disp.surface = s.surface;
3110 flags |= eDisplayTransactionNeeded;
3111 }
3112 }
3113 if (what & DisplayState::eLayerStackChanged) {
3114 if (disp.layerStack != s.layerStack) {
3115 disp.layerStack = s.layerStack;
3116 flags |= eDisplayTransactionNeeded;
3117 }
3118 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003119 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003120 if (disp.orientation != s.orientation) {
3121 disp.orientation = s.orientation;
3122 flags |= eDisplayTransactionNeeded;
3123 }
3124 if (disp.frame != s.frame) {
3125 disp.frame = s.frame;
3126 flags |= eDisplayTransactionNeeded;
3127 }
3128 if (disp.viewport != s.viewport) {
3129 disp.viewport = s.viewport;
3130 flags |= eDisplayTransactionNeeded;
3131 }
3132 }
Michael Lentine47e45402014-07-18 15:34:25 -07003133 if (what & DisplayState::eDisplaySizeChanged) {
3134 if (disp.width != s.width) {
3135 disp.width = s.width;
3136 flags |= eDisplayTransactionNeeded;
3137 }
3138 if (disp.height != s.height) {
3139 disp.height = s.height;
3140 flags |= eDisplayTransactionNeeded;
3141 }
3142 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003143 }
3144 return flags;
3145}
3146
chaviwca27f252018-02-06 16:46:39 -08003147uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3148 const layer_state_t& s = composerState.state;
3149 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3150
Mathias Agopian13127d82013-03-05 17:47:11 -08003151 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003152 if (layer == nullptr) {
3153 return 0;
3154 }
3155
3156 if (layer->isPendingRemoval()) {
3157 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3158 return 0;
3159 }
3160
3161 uint32_t flags = 0;
3162
3163 const uint32_t what = s.what;
3164 bool geometryAppliesWithResize =
3165 what & layer_state_t::eGeometryAppliesWithResize;
3166 if (what & layer_state_t::ePositionChanged) {
3167 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3168 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003169 }
chaviw8b3871a2017-11-01 17:41:01 -07003170 }
3171 if (what & layer_state_t::eLayerChanged) {
3172 // NOTE: index needs to be calculated before we update the state
3173 const auto& p = layer->getParent();
3174 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003175 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003176 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003177 mCurrentState.layersSortedByZ.removeAt(idx);
3178 mCurrentState.layersSortedByZ.add(layer);
3179 // we need traversal (state changed)
3180 // AND transaction (list changed)
3181 flags |= eTransactionNeeded|eTraversalNeeded;
3182 }
chaviw8b3871a2017-11-01 17:41:01 -07003183 } else {
3184 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003185 flags |= eTransactionNeeded|eTraversalNeeded;
3186 }
3187 }
chaviw8b3871a2017-11-01 17:41:01 -07003188 }
3189 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003190 // NOTE: index needs to be calculated before we update the state
3191 const auto& p = layer->getParent();
3192 if (p == nullptr) {
3193 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3194 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3195 mCurrentState.layersSortedByZ.removeAt(idx);
3196 mCurrentState.layersSortedByZ.add(layer);
3197 // we need traversal (state changed)
3198 // AND transaction (list changed)
3199 flags |= eTransactionNeeded|eTraversalNeeded;
3200 }
3201 } else {
3202 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3203 flags |= eTransactionNeeded|eTraversalNeeded;
3204 }
chaviw8b3871a2017-11-01 17:41:01 -07003205 }
3206 }
3207 if (what & layer_state_t::eSizeChanged) {
3208 if (layer->setSize(s.w, s.h)) {
3209 flags |= eTraversalNeeded;
3210 }
3211 }
3212 if (what & layer_state_t::eAlphaChanged) {
3213 if (layer->setAlpha(s.alpha))
3214 flags |= eTraversalNeeded;
3215 }
3216 if (what & layer_state_t::eColorChanged) {
3217 if (layer->setColor(s.color))
3218 flags |= eTraversalNeeded;
3219 }
3220 if (what & layer_state_t::eMatrixChanged) {
3221 if (layer->setMatrix(s.matrix))
3222 flags |= eTraversalNeeded;
3223 }
3224 if (what & layer_state_t::eTransparentRegionChanged) {
3225 if (layer->setTransparentRegionHint(s.transparentRegion))
3226 flags |= eTraversalNeeded;
3227 }
3228 if (what & layer_state_t::eFlagsChanged) {
3229 if (layer->setFlags(s.flags, s.mask))
3230 flags |= eTraversalNeeded;
3231 }
3232 if (what & layer_state_t::eCropChanged) {
3233 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3234 flags |= eTraversalNeeded;
3235 }
3236 if (what & layer_state_t::eFinalCropChanged) {
3237 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3238 flags |= eTraversalNeeded;
3239 }
3240 if (what & layer_state_t::eLayerStackChanged) {
3241 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3242 // We only allow setting layer stacks for top level layers,
3243 // everything else inherits layer stack from its parent.
3244 if (layer->hasParent()) {
3245 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3246 layer->getName().string());
3247 } else if (idx < 0) {
3248 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3249 "that also does not appear in the top level layer list. Something"
3250 " has gone wrong.", layer->getName().string());
3251 } else if (layer->setLayerStack(s.layerStack)) {
3252 mCurrentState.layersSortedByZ.removeAt(idx);
3253 mCurrentState.layersSortedByZ.add(layer);
3254 // we need traversal (state changed)
3255 // AND transaction (list changed)
3256 flags |= eTransactionNeeded|eTraversalNeeded;
3257 }
3258 }
3259 if (what & layer_state_t::eDeferTransaction) {
3260 if (s.barrierHandle != nullptr) {
3261 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3262 } else if (s.barrierGbp != nullptr) {
3263 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3264 if (authenticateSurfaceTextureLocked(gbp)) {
3265 const auto& otherLayer =
3266 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3267 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3268 } else {
3269 ALOGE("Attempt to defer transaction to to an"
3270 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003271 }
3272 }
chaviw8b3871a2017-11-01 17:41:01 -07003273 // We don't trigger a traversal here because if no other state is
3274 // changed, we don't want this to cause any more work
3275 }
3276 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003277 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003278 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003279 if (!hadParent) {
3280 mCurrentState.layersSortedByZ.remove(layer);
3281 }
chaviw8b3871a2017-11-01 17:41:01 -07003282 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003283 }
chaviw8b3871a2017-11-01 17:41:01 -07003284 }
3285 if (what & layer_state_t::eReparentChildren) {
3286 if (layer->reparentChildren(s.reparentHandle)) {
3287 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003288 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289 }
chaviw8b3871a2017-11-01 17:41:01 -07003290 if (what & layer_state_t::eDetachChildren) {
3291 layer->detachChildren();
3292 }
3293 if (what & layer_state_t::eOverrideScalingModeChanged) {
3294 layer->setOverrideScalingMode(s.overrideScalingMode);
3295 // We don't trigger a traversal here because if no other state is
3296 // changed, we don't want this to cause any more work
3297 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 return flags;
3299}
3300
chaviwca27f252018-02-06 16:46:39 -08003301void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3302 const layer_state_t& state = composerState.state;
3303 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3304
3305 sp<Layer> layer(client->getLayerUser(state.surface));
3306 if (layer == nullptr) {
3307 return;
3308 }
3309
3310 if (layer->isPendingRemoval()) {
3311 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3312 return;
3313 }
3314
3315 if (state.what & layer_state_t::eDestroySurface) {
3316 removeLayerLocked(mStateLock, layer);
3317 }
3318}
3319
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003320status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003321 const String8& name,
3322 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003323 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003324 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3325 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003326{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003327 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003328 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003329 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003330 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003331 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003332
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003333 status_t result = NO_ERROR;
3334
3335 sp<Layer> layer;
3336
Cody Northropbc755282017-03-31 12:00:08 -06003337 String8 uniqueName = getUniqueLayerName(name);
3338
Mathias Agopian3165cc22012-08-08 19:42:09 -07003339 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3340 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003341 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003342 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003343 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003345 break;
chaviw13fdc492017-06-27 12:40:18 -07003346 case ISurfaceComposerClient::eFXSurfaceColor:
3347 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003348 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003349 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003350 break;
3351 default:
3352 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 break;
3354 }
3355
Dan Stoza7d89d062015-04-30 13:29:25 -07003356 if (result != NO_ERROR) {
3357 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003358 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003359
Chia-I Wuab0c3192017-08-01 11:29:00 -07003360 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3361 // TODO b/64227542
3362 if (windowType == 441731) {
3363 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3364 layer->setPrimaryDisplayOnly();
3365 }
3366
Albert Chaulk479c60c2017-01-27 14:21:34 -05003367 layer->setInfo(windowType, ownerUid);
3368
Robert Carr1f0a16a2016-10-24 16:27:39 -07003369 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003370 if (result != NO_ERROR) {
3371 return result;
3372 }
Irvelffc9efc2016-07-27 15:16:37 -07003373 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003374
3375 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003376 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003377}
3378
Cody Northropbc755282017-03-31 12:00:08 -06003379String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3380{
3381 bool matchFound = true;
3382 uint32_t dupeCounter = 0;
3383
3384 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3385 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3386
3387 // Loop over layers until we're sure there is no matching name
3388 while (matchFound) {
3389 matchFound = false;
3390 mDrawingState.traverseInZOrder([&](Layer* layer) {
3391 if (layer->getName() == uniqueName) {
3392 matchFound = true;
3393 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3394 }
3395 });
3396 }
3397
3398 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3399
3400 return uniqueName;
3401}
3402
David Sodman0c69cad2017-08-21 12:12:51 -07003403status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003404 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3405 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003406{
3407 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003408 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409 case PIXEL_FORMAT_TRANSPARENT:
3410 case PIXEL_FORMAT_TRANSLUCENT:
3411 format = PIXEL_FORMAT_RGBA_8888;
3412 break;
3413 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003414 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003415 break;
3416 }
3417
David Sodman0c69cad2017-08-21 12:12:51 -07003418 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3419 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003420 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003421 *handle = layer->getHandle();
3422 *gbp = layer->getProducer();
3423 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003425
David Sodman0c69cad2017-08-21 12:12:51 -07003426 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003427 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428}
3429
chaviw13fdc492017-06-27 12:40:18 -07003430status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003431 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003432 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003433{
chaviw13fdc492017-06-27 12:40:18 -07003434 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003435 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003436 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003437}
3438
Mathias Agopianac9fa422013-02-11 16:40:36 -08003439status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440{
Robert Carr9524cb32017-02-13 11:32:32 -08003441 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003442 status_t err = NO_ERROR;
3443 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003444 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003445 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003446 err = removeLayer(l);
3447 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3448 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003449 }
3450 return err;
3451}
3452
Mathias Agopian13127d82013-03-05 17:47:11 -08003453status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003454{
Mathias Agopian67106042013-03-14 19:18:13 -07003455 // called by ~LayerCleaner() when all references to the IBinder (handle)
3456 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003457 sp<Layer> l = layer.promote();
3458 if (l == nullptr) {
3459 // The layer has already been removed, carry on
3460 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003461 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003462 // If we have a parent, then we can continue to live as long as it does.
3463 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464}
3465
Mathias Agopianb60314a2012-04-10 22:09:54 -07003466// ---------------------------------------------------------------------------
3467
Andy McFadden13a082e2012-08-24 10:16:42 -07003468void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003469 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003470 Vector<ComposerState> state;
3471 Vector<DisplayState> displays;
3472 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003473 d.what = DisplayState::eDisplayProjectionChanged |
3474 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003475 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003476 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003477 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003478 d.frame.makeInvalid();
3479 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003480 d.width = 0;
3481 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003482 displays.add(d);
3483 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003484 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3485 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003486
David Sodman105b7dc2017-11-04 20:28:14 -07003487 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003488 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003489 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003490
Brian Andersond0010582017-03-07 13:20:31 -08003491 // Use phase of 0 since phase is not known.
3492 // Use latency of 0, which will snap to the ideal latency.
3493 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003494}
3495
3496void SurfaceFlinger::initializeDisplays() {
3497 class MessageScreenInitialized : public MessageBase {
3498 SurfaceFlinger* flinger;
3499 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003500 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003501 virtual bool handler() {
3502 flinger->onInitializeDisplays();
3503 return true;
3504 }
3505 };
3506 sp<MessageBase> msg = new MessageScreenInitialized(this);
3507 postMessageAsync(msg); // we may be called from main thread, use async message
3508}
3509
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003511 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003512 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3513 this);
3514 int32_t type = hw->getDisplayType();
3515 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003516
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003517 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003518 return;
3519 }
3520
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003521 hw->setPowerMode(mode);
3522 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3523 ALOGW("Trying to set power mode for virtual display");
3524 return;
3525 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003526
Irvelffc9efc2016-07-27 15:16:37 -07003527 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003528 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003529 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3530 if (idx < 0) {
3531 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3532 return;
3533 }
3534 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3535 }
3536
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003537 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003538 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003539 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003540 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3541 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003542 // FIXME: eventthread only knows about the main display right now
3543 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003544 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003547 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003548 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003549 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003550
3551 struct sched_param param = {0};
3552 param.sched_priority = 1;
3553 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3554 ALOGW("Couldn't set SCHED_FIFO on display on");
3555 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003556 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003557 // Turn off the display
3558 struct sched_param param = {0};
3559 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3560 ALOGW("Couldn't set SCHED_OTHER on display off");
3561 }
3562
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003563 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3564 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003565 disableHardwareVsync(true); // also cancels any in-progress resync
3566
Mathias Agopiancde87a32012-09-13 14:09:01 -07003567 // FIXME: eventthread only knows about the main display right now
3568 mEventThread->onScreenReleased();
3569 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003570
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003571 getHwComposer().setPowerMode(type, mode);
3572 mVisibleRegionsDirty = true;
3573 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003574 } else if (mode == HWC_POWER_MODE_DOZE ||
3575 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003576 // Update display while dozing
3577 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003578 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3579 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003580 // FIXME: eventthread only knows about the main display right now
3581 mEventThread->onScreenAcquired();
3582 resyncToHardwareVsync(true);
3583 }
3584 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3585 // Leave display going to doze
3586 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3587 disableHardwareVsync(true); // also cancels any in-progress resync
3588 // FIXME: eventthread only knows about the main display right now
3589 mEventThread->onScreenReleased();
3590 }
3591 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003592 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003593 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003594 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003595 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003596}
3597
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003598void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3599 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003600 SurfaceFlinger& mFlinger;
3601 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003602 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003603 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003604 MessageSetPowerMode(SurfaceFlinger& flinger,
3605 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3606 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003607 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003608 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003609 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003610 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003611 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003612 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003613 ALOGW("Attempt to set power mode = %d for virtual display",
3614 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003615 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003616 mFlinger.setPowerModeInternal(
3617 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003618 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003619 return true;
3620 }
3621 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003622 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003623 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003624}
3625
3626// ---------------------------------------------------------------------------
3627
Lloyd Pique755e3192018-01-31 16:46:15 -08003628status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3629 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003631
Mathias Agopianbd115332013-04-18 16:41:04 -07003632 IPCThreadState* ipc = IPCThreadState::self();
3633 const int pid = ipc->getCallingPid();
3634 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003635
Mathias Agopianbd115332013-04-18 16:41:04 -07003636 if ((uid != AID_SHELL) &&
3637 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003638 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003639 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003640 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003641 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003642 // (this would indicate SF is stuck, but we want to be able to
3643 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003644 status_t err = mStateLock.timedLock(s2ns(1));
3645 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003646 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003647 result.appendFormat(
3648 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3649 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003650 }
3651
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003652 bool dumpAll = true;
3653 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003654 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003655
3656 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003657 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003658 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3659 dumpAll = false;
3660 }
3661
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003662 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003663 if ((index < numArgs) &&
3664 (args[index] == String16("--list"))) {
3665 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003666 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003667 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003668 }
3669
3670 if ((index < numArgs) &&
3671 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003673 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003674 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003675 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003676
3677 if ((index < numArgs) &&
3678 (args[index] == String16("--latency-clear"))) {
3679 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003680 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003681 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003682 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003683
3684 if ((index < numArgs) &&
3685 (args[index] == String16("--dispsync"))) {
3686 index++;
3687 mPrimaryDispSync.dump(result);
3688 dumpAll = false;
3689 }
Dan Stozab90cf072015-03-05 11:05:59 -08003690
3691 if ((index < numArgs) &&
3692 (args[index] == String16("--static-screen"))) {
3693 index++;
3694 dumpStaticScreenStats(result);
3695 dumpAll = false;
3696 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003697
3698 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003699 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003700 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003701 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003702 dumpAll = false;
3703 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003704
3705 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3706 index++;
3707 dumpWideColorInfo(result);
3708 dumpAll = false;
3709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003711
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003712 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003713 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003714 }
3715
Mathias Agopian9795c422009-08-26 16:36:26 -07003716 if (locked) {
3717 mStateLock.unlock();
3718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719 }
3720 write(fd, result.string(), result.size());
3721 return NO_ERROR;
3722}
3723
Dan Stozac7014012014-02-14 15:03:43 -08003724void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3725 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003726{
Robert Carr2047fae2016-11-28 14:09:09 -08003727 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003728 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003729 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003730}
3731
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003732void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003733 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003734{
3735 String8 name;
3736 if (index < args.size()) {
3737 name = String8(args[index]);
3738 index++;
3739 }
3740
David Sodman105b7dc2017-11-04 20:28:14 -07003741 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003742 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003743 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003744
3745 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003746 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003747 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003748 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003749 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003750 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003751 }
Robert Carr2047fae2016-11-28 14:09:09 -08003752 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003753 }
3754}
3755
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003756void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003757 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003758{
3759 String8 name;
3760 if (index < args.size()) {
3761 name = String8(args[index]);
3762 index++;
3763 }
3764
Robert Carr2047fae2016-11-28 14:09:09 -08003765 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003766 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003767 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003768 }
Robert Carr2047fae2016-11-28 14:09:09 -08003769 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003770
Svetoslavd85084b2014-03-20 10:28:31 -07003771 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003772}
3773
Jamie Gennis6547ff42013-07-16 20:12:42 -07003774// This should only be called from the main thread. Otherwise it would need
3775// the lock and should use mCurrentState rather than mDrawingState.
3776void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003777 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003778 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003779 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003780
3781 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3782}
3783
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003784void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003785{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003786 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003787
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003788 if (isLayerTripleBufferingDisabled())
3789 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003790
3791 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003792 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003793 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003794 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003795 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3796 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003797 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003798}
3799
Dan Stozab90cf072015-03-05 11:05:59 -08003800void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3801{
3802 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003803 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3804 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003805 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003806 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003807 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3808 b + 1, bucketTimeSec, percent);
3809 }
David Sodman4a36e932017-11-07 14:29:47 -08003810 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003811 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003812 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003813 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003814 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003815}
3816
Dan Stozae77c7662016-05-13 11:37:28 -07003817void SurfaceFlinger::recordBufferingStats(const char* layerName,
3818 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003819 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3820 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003821 for (const auto& segment : history) {
3822 if (!segment.usedThirdBuffer) {
3823 stats.twoBufferTime += segment.totalTime;
3824 }
3825 if (segment.occupancyAverage < 1.0f) {
3826 stats.doubleBufferedTime += segment.totalTime;
3827 } else if (segment.occupancyAverage < 2.0f) {
3828 stats.tripleBufferedTime += segment.totalTime;
3829 }
3830 ++stats.numSegments;
3831 stats.totalTime += segment.totalTime;
3832 }
3833}
3834
Brian Andersond6927fb2016-07-23 23:37:30 -07003835void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3836 result.appendFormat("Layer frame timestamps:\n");
3837
3838 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3839 const size_t count = currentLayers.size();
3840 for (size_t i=0 ; i<count ; i++) {
3841 currentLayers[i]->dumpFrameEvents(result);
3842 }
3843}
3844
Dan Stozae77c7662016-05-13 11:37:28 -07003845void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3846 result.append("Buffering stats:\n");
3847 result.append(" [Layer name] <Active time> <Two buffer> "
3848 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003849 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003850 typedef std::tuple<std::string, float, float, float> BufferTuple;
3851 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003852 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003853 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003854 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003855 if (stats.numSegments == 0) {
3856 continue;
3857 }
3858 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3859 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3860 stats.totalTime;
3861 float doubleBufferRatio = static_cast<float>(
3862 stats.doubleBufferedTime) / stats.totalTime;
3863 float tripleBufferRatio = static_cast<float>(
3864 stats.tripleBufferedTime) / stats.totalTime;
3865 sorted.insert({activeTime, {name, twoBufferRatio,
3866 doubleBufferRatio, tripleBufferRatio}});
3867 }
3868 for (const auto& sortedPair : sorted) {
3869 float activeTime = sortedPair.first;
3870 const BufferTuple& values = sortedPair.second;
3871 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3872 std::get<0>(values).c_str(), activeTime,
3873 std::get<1>(values), std::get<2>(values),
3874 std::get<3>(values));
3875 }
3876 result.append("\n");
3877}
3878
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003879void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3880 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003881 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003882
3883 // TODO: print out if wide-color mode is active or not
3884
3885 for (size_t d = 0; d < mDisplays.size(); d++) {
3886 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3887 int32_t hwcId = displayDevice->getHwcDisplayId();
3888 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3889 continue;
3890 }
3891
3892 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003893 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003894 for (auto&& mode : modes) {
3895 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3896 }
3897
Peiyong Lina52f0292018-03-14 17:26:31 -07003898 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003899 result.appendFormat(" Current color mode: %s (%d)\n",
3900 decodeColorMode(currentMode).c_str(), currentMode);
3901 }
3902 result.append("\n");
3903}
3904
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003905LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003906 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003907 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3908 const State& state = useDrawing ? mDrawingState : mCurrentState;
3909 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003910 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003911 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003912 });
3913
3914 return layersProto;
3915}
3916
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3918 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003919{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003920 bool colorize = false;
3921 if (index < args.size()
3922 && (args[index] == String16("--color"))) {
3923 colorize = true;
3924 index++;
3925 }
3926
3927 Colorizer colorizer(colorize);
3928
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929 // figure out if we're stuck somewhere
3930 const nsecs_t now = systemTime();
3931 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3932 const nsecs_t inTransaction(mDebugInTransaction);
3933 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3934 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3935
3936 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003937 * Dump library configuration.
3938 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003939
3940 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003941 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003943 appendSfConfigString(result);
3944 appendUiConfigString(result);
3945 appendGuiConfigString(result);
3946 result.append("\n");
3947
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003948 result.append("\nWide-Color information:\n");
3949 dumpWideColorInfo(result);
3950
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003951 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003952 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003953 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003954 result.append(SyncFeatures::getInstance().toString());
3955 result.append("\n");
3956
David Sodman105b7dc2017-11-04 20:28:14 -07003957 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003958
Andy McFadden41d67d72014-04-25 16:58:34 -07003959 colorizer.bold(result);
3960 result.append("DispSync configuration: ");
3961 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003962 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003963 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003964 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003965 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003966 result.append("\n");
3967
Dan Stozab90cf072015-03-05 11:05:59 -08003968 // Dump static screen stats
3969 result.append("\n");
3970 dumpStaticScreenStats(result);
3971 result.append("\n");
3972
Dan Stozae77c7662016-05-13 11:37:28 -07003973 dumpBufferingStats(result);
3974
Andy McFadden4803b742012-09-24 19:07:20 -07003975 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976 * Dump the visible layer list
3977 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003978 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003979 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07003980 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
3981 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003982 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003983
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003984 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003985 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07003986 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003987
3988 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003989 * Dump Display state
3990 */
3991
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003992 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003993 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003994 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003995 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3996 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003997 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003998 }
3999
4000 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004001 * Dump SurfaceFlinger global state
4002 */
4003
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004005 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004006 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004007
Mathias Agopian888c8222012-08-04 21:10:38 -07004008 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004009 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004010
David Sodmanbc815282017-11-05 18:57:52 -08004011 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004012
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004013 if (hw) {
4014 hw->undefinedRegion.dump(result, "undefinedRegion");
4015 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4016 hw->getOrientation(), hw->isDisplayOn());
4017 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004018 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004019 " last eglSwapBuffers() time: %f us\n"
4020 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004021 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004022 " refresh-rate : %f fps\n"
4023 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004024 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004025 " gpu_to_cpu_unsupported : %d\n"
4026 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004027 mLastSwapBufferTime/1000.0,
4028 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004029 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004030 1e9 / activeConfig->getVsyncPeriod(),
4031 activeConfig->getDpiX(),
4032 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004033 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004034
Mathias Agopian74d211a2013-04-22 16:55:35 +02004035 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004036 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037
Mathias Agopian74d211a2013-04-22 16:55:35 +02004038 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004039 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040
4041 /*
4042 * VSYNC state
4043 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004044 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004045 result.append("\n");
4046
4047 /*
4048 * HWC layer minidump
4049 */
4050 for (size_t d = 0; d < mDisplays.size(); d++) {
4051 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4052 int32_t hwcId = displayDevice->getHwcDisplayId();
4053 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4054 continue;
4055 }
4056
4057 result.appendFormat("Display %d HWC layers:\n", hwcId);
4058 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004059 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004060 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004061 });
Dan Stozae22aec72016-08-01 13:20:59 -07004062 result.append("\n");
4063 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004064
4065 /*
4066 * Dump HWComposer state
4067 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004068 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004069 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004070 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004071 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004072 result.appendFormat(" h/w composer %s\n",
4073 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004074 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004075
4076 /*
4077 * Dump gralloc state
4078 */
4079 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4080 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004081
4082 /*
4083 * Dump VrFlinger state if in use.
4084 */
4085 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4086 result.append("VrFlinger state:\n");
4087 result.append(mVrFlinger->Dump().c_str());
4088 result.append("\n");
4089 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004090}
4091
Mathias Agopian13127d82013-03-05 17:47:11 -08004092const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004093SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004094 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004095 wp<IBinder> dpy;
4096 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4097 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4098 dpy = mDisplays.keyAt(i);
4099 break;
4100 }
4101 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004102 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004103 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4104 // Just use the primary display so we have something to return
4105 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4106 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004107 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004108}
4109
Keun young Park63f165f2012-08-31 10:53:36 -07004110bool SurfaceFlinger::startDdmConnection()
4111{
4112 void* libddmconnection_dso =
4113 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4114 if (!libddmconnection_dso) {
4115 return false;
4116 }
4117 void (*DdmConnection_start)(const char* name);
4118 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004119 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004120 if (!DdmConnection_start) {
4121 dlclose(libddmconnection_dso);
4122 return false;
4123 }
4124 (*DdmConnection_start)(getServiceName());
4125 return true;
4126}
4127
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004128status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004129 switch (code) {
4130 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004131 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004133 case CLEAR_ANIMATION_FRAME_STATS:
4134 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004135 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004136 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004137 case ENABLE_VSYNC_INJECTIONS:
4138 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004139 {
4140 // codes that require permission check
4141 IPCThreadState* ipc = IPCThreadState::self();
4142 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004143 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004144 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004145 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004146 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004147 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004149 break;
4150 }
Robert Carr1db73f62016-12-21 12:58:51 -08004151 /*
4152 * Calling setTransactionState is safe, because you need to have been
4153 * granted a reference to Client* and Handle* to do anything with it.
4154 *
4155 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4156 */
4157 case SET_TRANSACTION_STATE:
4158 case CREATE_SCOPED_CONNECTION:
4159 {
4160 return OK;
4161 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004162 case CAPTURE_SCREEN:
4163 {
4164 // codes that require permission check
4165 IPCThreadState* ipc = IPCThreadState::self();
4166 const int pid = ipc->getCallingPid();
4167 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004168 if ((uid != AID_GRAPHICS) &&
4169 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004170 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004171 return PERMISSION_DENIED;
4172 }
4173 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174 }
chaviwa76b2712017-09-20 12:02:26 -07004175 case CAPTURE_LAYERS: {
4176 IPCThreadState* ipc = IPCThreadState::self();
4177 const int pid = ipc->getCallingPid();
4178 const int uid = ipc->getCallingUid();
4179 if ((uid != AID_GRAPHICS) &&
4180 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4181 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4182 return PERMISSION_DENIED;
4183 }
4184 break;
4185 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004187 return OK;
4188}
4189
4190status_t SurfaceFlinger::onTransact(
4191 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4192{
4193 status_t credentialCheck = CheckTransactCodeCredentials(code);
4194 if (credentialCheck != OK) {
4195 return credentialCheck;
4196 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004198 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4199 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004200 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004201 IPCThreadState* ipc = IPCThreadState::self();
4202 const int uid = ipc->getCallingUid();
4203 if (CC_UNLIKELY(uid != AID_SYSTEM
4204 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004205 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004206 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004207 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208 return PERMISSION_DENIED;
4209 }
4210 int n;
4211 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004212 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004213 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004214 return NO_ERROR;
4215 case 1002: // SHOW_UPDATES
4216 n = data.readInt32();
4217 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004218 invalidateHwcGeometry();
4219 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004220 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004221 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004222 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004223 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004224 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004225 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004226 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004227 setTransactionFlags(
4228 eTransactionNeeded|
4229 eDisplayTransactionNeeded|
4230 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004231 return NO_ERROR;
4232 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004233 case 1006:{ // send empty update
4234 signalRefresh();
4235 return NO_ERROR;
4236 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004237 case 1008: // toggle use of hw composer
4238 n = data.readInt32();
4239 mDebugDisableHWC = n ? 1 : 0;
4240 invalidateHwcGeometry();
4241 repaintEverything();
4242 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004243 case 1009: // toggle use of transform hint
4244 n = data.readInt32();
4245 mDebugDisableTransformHint = n ? 1 : 0;
4246 invalidateHwcGeometry();
4247 repaintEverything();
4248 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004249 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004250 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251 reply->writeInt32(0);
4252 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004253 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004254 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004255 return NO_ERROR;
4256 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004257 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004258 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004259 return NO_ERROR;
4260 }
4261 case 1014: {
4262 // daltonize
4263 n = data.readInt32();
4264 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004265 case 1:
4266 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4267 break;
4268 case 2:
4269 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4270 break;
4271 case 3:
4272 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4273 break;
4274 default:
4275 mDaltonizer.setType(ColorBlindnessType::None);
4276 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004277 }
4278 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004279 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004280 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004281 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004282 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004283 invalidateHwcGeometry();
4284 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004285 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004286 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004287 case 1015: {
4288 // apply a color matrix
4289 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004290 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004291 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004292 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004293 for (size_t j = 0; j < 4; j++) {
4294 mColorMatrix[i][j] = data.readFloat();
4295 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004296 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004297 } else {
4298 mColorMatrix = mat4();
4299 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004300
4301 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4302 // the division by w in the fragment shader
4303 float4 lastRow(transpose(mColorMatrix)[3]);
4304 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4305 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4306 }
4307
Alan Viverette9c5a3332013-09-12 20:04:35 -07004308 invalidateHwcGeometry();
4309 repaintEverything();
4310 return NO_ERROR;
4311 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004312 // This is an experimental interface
4313 // Needs to be shifted to proper binder interface when we productize
4314 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004315 n = data.readInt32();
4316 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004317 return NO_ERROR;
4318 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004319 case 1017: {
4320 n = data.readInt32();
4321 mForceFullDamage = static_cast<bool>(n);
4322 return NO_ERROR;
4323 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004324 case 1018: { // Modify Choreographer's phase offset
4325 n = data.readInt32();
4326 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4327 return NO_ERROR;
4328 }
4329 case 1019: { // Modify SurfaceFlinger's phase offset
4330 n = data.readInt32();
4331 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4332 return NO_ERROR;
4333 }
Irvel468051e2016-06-13 16:44:44 -07004334 case 1020: { // Layer updates interceptor
4335 n = data.readInt32();
4336 if (n) {
4337 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004338 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004339 }
4340 else{
4341 ALOGV("Interceptor disabled");
4342 mInterceptor.disable();
4343 }
4344 return NO_ERROR;
4345 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004346 case 1021: { // Disable HWC virtual displays
4347 n = data.readInt32();
4348 mUseHwcVirtualDisplays = !n;
4349 return NO_ERROR;
4350 }
Romain Guy0147a172017-06-01 13:53:56 -07004351 case 1022: { // Set saturation boost
4352 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4353
4354 invalidateHwcGeometry();
4355 repaintEverything();
4356 return NO_ERROR;
4357 }
Romain Guy54f154a2017-10-24 21:40:32 +01004358 case 1023: { // Set native mode
4359 mForceNativeColorMode = data.readInt32() == 1;
4360
4361 invalidateHwcGeometry();
4362 repaintEverything();
4363 return NO_ERROR;
4364 }
4365 case 1024: { // Is wide color gamut rendering/color management supported?
4366 reply->writeBool(hasWideColorDisplay);
4367 return NO_ERROR;
4368 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004369 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004370 n = data.readInt32();
4371 if (n) {
4372 ALOGV("LayerTracing enabled");
4373 mTracing.enable();
4374 doTracing("tracing.enable");
4375 reply->writeInt32(NO_ERROR);
4376 } else {
4377 ALOGV("LayerTracing disabled");
4378 status_t err = mTracing.disable();
4379 reply->writeInt32(err);
4380 }
4381 return NO_ERROR;
4382 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004383 case 1026: { // Get layer tracing status
4384 reply->writeBool(mTracing.isEnabled());
4385 return NO_ERROR;
4386 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004387 }
4388 }
4389 return err;
4390}
4391
Steven Thomas6d8110b2017-08-31 18:24:21 -07004392void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004393 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004394 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004395}
4396
Steven Thomas6d8110b2017-08-31 18:24:21 -07004397void SurfaceFlinger::repaintEverything() {
4398 ConditionalLock _l(mStateLock,
4399 std::this_thread::get_id() != mMainThreadId);
4400 repaintEverythingLocked();
4401}
4402
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004403// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4404class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004405public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004406 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4407 ~WindowDisconnector() {
4408 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004409 }
4410
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004411private:
4412 ANativeWindow* mWindow;
4413 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004414};
4415
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004416status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4417 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4418 int32_t minLayerZ, int32_t maxLayerZ,
4419 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004420 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004421 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004422
chaviwa76b2712017-09-20 12:02:26 -07004423 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4424
4425 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004426 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4427
chaviwa76b2712017-09-20 12:02:26 -07004428 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4429
4430 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4431 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004432 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004433}
4434
4435status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004436 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004437 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004438 ATRACE_CALL();
4439
4440 class LayerRenderArea : public RenderArea {
4441 public:
Robert Carr578038f2018-03-09 12:25:24 -08004442 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4443 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4444 : RenderArea(reqHeight, reqWidth),
4445 mLayer(layer),
4446 mCrop(crop),
4447 mFlinger(flinger),
4448 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004449 Rect getBounds() const override {
4450 const Layer::State& layerState(mLayer->getDrawingState());
4451 return Rect(layerState.active.w, layerState.active.h);
4452 }
4453 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4454 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4455 bool isSecure() const override { return false; }
4456 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004457 const Transform& getTransform() const { return mTransform; }
4458
4459 class ReparentForDrawing {
4460 public:
4461 const sp<Layer>& oldParent;
4462 const sp<Layer>& newParent;
4463
4464 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4465 : oldParent(oldParent), newParent(newParent) {
4466 oldParent->reparentChildrenForDrawing(newParent);
4467 }
4468 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4469 };
4470
4471 void render(std::function<void()> drawLayers) override {
4472 if (!mChildrenOnly) {
4473 mTransform = mLayer->getTransform().inverse();
4474 drawLayers();
4475 } else {
4476 Rect bounds = getBounds();
4477 screenshotParentLayer =
4478 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4479 bounds.getWidth(), bounds.getHeight(), 0);
4480
4481 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4482 drawLayers();
4483 }
4484 }
chaviwa76b2712017-09-20 12:02:26 -07004485
chaviw7206d492017-11-10 16:16:12 -08004486 Rect getSourceCrop() const override {
4487 if (mCrop.isEmpty()) {
4488 return getBounds();
4489 } else {
4490 return mCrop;
4491 }
4492 }
chaviwa76b2712017-09-20 12:02:26 -07004493 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004494 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004495
4496 private:
chaviw7206d492017-11-10 16:16:12 -08004497 const sp<Layer> mLayer;
4498 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004499
4500 // In the "childrenOnly" case we reparent the children to a screenshot
4501 // layer which has no properties set and which does not draw.
4502 sp<ContainerLayer> screenshotParentLayer;
4503 Transform mTransform;
4504
4505 SurfaceFlinger* mFlinger;
4506 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004507 };
4508
4509 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4510 auto parent = layerHandle->owner.promote();
4511
chaviw7206d492017-11-10 16:16:12 -08004512 if (parent == nullptr || parent->isPendingRemoval()) {
4513 ALOGE("captureLayers called with a removed parent");
4514 return NAME_NOT_FOUND;
4515 }
4516
Robert Carr578038f2018-03-09 12:25:24 -08004517 const int uid = IPCThreadState::self()->getCallingUid();
4518 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4519 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4520 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4521 return PERMISSION_DENIED;
4522 }
4523
chaviw7206d492017-11-10 16:16:12 -08004524 Rect crop(sourceCrop);
4525 if (sourceCrop.width() <= 0) {
4526 crop.left = 0;
4527 crop.right = parent->getCurrentState().active.w;
4528 }
4529
4530 if (sourceCrop.height() <= 0) {
4531 crop.top = 0;
4532 crop.bottom = parent->getCurrentState().active.h;
4533 }
4534
4535 int32_t reqWidth = crop.width() * frameScale;
4536 int32_t reqHeight = crop.height() * frameScale;
4537
Robert Carr578038f2018-03-09 12:25:24 -08004538 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004539
Robert Carr578038f2018-03-09 12:25:24 -08004540 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004541 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4542 if (!layer->isVisible()) {
4543 return;
Robert Carr578038f2018-03-09 12:25:24 -08004544 } else if (childrenOnly && layer == parent.get()) {
4545 return;
chaviwa76b2712017-09-20 12:02:26 -07004546 }
4547 visitor(layer);
4548 });
4549 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004550 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004551}
4552
4553status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4554 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004555 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004556 bool useIdentityTransform) {
4557 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004558
chaviwa76b2712017-09-20 12:02:26 -07004559 renderArea.updateDimensions();
4560
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004561 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4562 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4563 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4564 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004565
4566 // This mutex protects syncFd and captureResult for communication of the return values from the
4567 // main thread back to this Binder thread
4568 std::mutex captureMutex;
4569 std::condition_variable captureCondition;
4570 std::unique_lock<std::mutex> captureLock(captureMutex);
4571 int syncFd = -1;
4572 std::optional<status_t> captureResult;
4573
Robert Carr03480e22018-01-04 16:02:06 -08004574 const int uid = IPCThreadState::self()->getCallingUid();
4575 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4576
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004577 sp<LambdaMessage> message = new LambdaMessage([&]() {
4578 // If there is a refresh pending, bug out early and tell the binder thread to try again
4579 // after the refresh.
4580 if (mRefreshPending) {
4581 ATRACE_NAME("Skipping screenshot for now");
4582 std::unique_lock<std::mutex> captureLock(captureMutex);
4583 captureResult = std::make_optional<status_t>(EAGAIN);
4584 captureCondition.notify_one();
4585 return;
4586 }
4587
4588 status_t result = NO_ERROR;
4589 int fd = -1;
4590 {
4591 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004592 renderArea.render([&]() {
4593 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4594 useIdentityTransform, forSystem, &fd);
4595 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004596 }
4597
4598 {
4599 std::unique_lock<std::mutex> captureLock(captureMutex);
4600 syncFd = fd;
4601 captureResult = std::make_optional<status_t>(result);
4602 captureCondition.notify_one();
4603 }
4604 });
4605
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004606 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004607 if (result == NO_ERROR) {
4608 captureCondition.wait(captureLock, [&]() { return captureResult; });
4609 while (*captureResult == EAGAIN) {
4610 captureResult.reset();
4611 result = postMessageAsync(message);
4612 if (result != NO_ERROR) {
4613 return result;
4614 }
4615 captureCondition.wait(captureLock, [&]() { return captureResult; });
4616 }
4617 result = *captureResult;
4618 }
4619
4620 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004621 sync_wait(syncFd, -1);
4622 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004623 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004624
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004625 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004626}
4627
chaviwa76b2712017-09-20 12:02:26 -07004628void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4629 TraverseLayersFunction traverseLayers, bool yswap,
4630 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004631 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004632
Lloyd Pique144e1162017-12-20 16:44:52 -08004633 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004634
4635 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004636 const auto raWidth = renderArea.getWidth();
4637 const auto raHeight = renderArea.getHeight();
4638
4639 const auto reqWidth = renderArea.getReqWidth();
4640 const auto reqHeight = renderArea.getReqHeight();
4641 Rect sourceCrop = renderArea.getSourceCrop();
4642
4643 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4644 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004645
Dan Stozac1879002014-05-22 15:59:05 -07004646 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004647 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004648 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004649 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004650 }
4651
4652 // ensure that sourceCrop is inside screen
4653 if (sourceCrop.left < 0) {
4654 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4655 }
chaviwa76b2712017-09-20 12:02:26 -07004656 if (sourceCrop.right > raWidth) {
4657 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004658 }
4659 if (sourceCrop.top < 0) {
4660 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4661 }
chaviwa76b2712017-09-20 12:02:26 -07004662 if (sourceCrop.bottom > raHeight) {
4663 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004664 }
4665
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004666 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004667 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004668 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004669 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4670 }
4671 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004672
Mathias Agopian180f10d2013-04-10 22:55:41 -07004673 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004674 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004675
4676 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004677 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4678 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004679 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004680
4681 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004682 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004683
chaviwa76b2712017-09-20 12:02:26 -07004684 traverseLayers([&](Layer* layer) {
4685 if (filtering) layer->setFiltering(true);
4686 layer->draw(renderArea, useIdentityTransform);
4687 if (filtering) layer->setFiltering(false);
4688 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004689}
4690
chaviwa76b2712017-09-20 12:02:26 -07004691status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4692 TraverseLayersFunction traverseLayers,
4693 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004694 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004695 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004696 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004697 ATRACE_CALL();
4698
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004699 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004700
4701 traverseLayers([&](Layer* layer) {
4702 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4703 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004704
Robert Carr03480e22018-01-04 16:02:06 -08004705 // We allow the system server to take screenshots of secure layers for
4706 // use in situations like the Screen-rotation animation and place
4707 // the impetus on WindowManager to not persist them.
4708 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004709 ALOGW("FB is protected: PERMISSION_DENIED");
4710 return PERMISSION_DENIED;
4711 }
4712
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004713 // this binds the given EGLImage as a framebuffer for the
4714 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004715 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004716 if (bufferBond.getStatus() != NO_ERROR) {
4717 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004718 return INVALID_OPERATION;
4719 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004720
Dan Stozaabcda352017-06-01 14:37:39 -07004721 // this will in fact render into our dequeued buffer
4722 // via an FBO, which means we didn't have to create
4723 // an EGLSurface and therefore we're not
4724 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004725 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004726
Dan Stozaabcda352017-06-01 14:37:39 -07004727 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004728 getRenderEngine().finish();
4729 *outSyncFd = -1;
4730
chaviwa76b2712017-09-20 12:02:26 -07004731 const auto reqWidth = renderArea.getReqWidth();
4732 const auto reqHeight = renderArea.getReqHeight();
4733
Dan Stozaabcda352017-06-01 14:37:39 -07004734 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4735 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004736 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004737 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004738 } else {
4739 base::unique_fd syncFd = getRenderEngine().flush();
4740 if (syncFd < 0) {
4741 getRenderEngine().finish();
4742 }
4743 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004744 }
4745
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004746 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004747}
4748
Mathias Agopiand5556842013-09-19 17:08:37 -07004749void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004750 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004751 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004752 for (size_t y = 0; y < h; y++) {
4753 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4754 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004755 if (p[x] != 0xFF000000) return;
4756 }
4757 }
chaviwa76b2712017-09-20 12:02:26 -07004758 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004759
Robert Carr2047fae2016-11-28 14:09:09 -08004760 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004761 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004762 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004763 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4764 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4765 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4766 static_cast<float>(state.color.a));
4767 i++;
4768 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004769 }
4770}
4771
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004772// ---------------------------------------------------------------------------
4773
Dan Stoza412903f2017-04-27 13:42:17 -07004774void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4775 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004776}
4777
Dan Stoza412903f2017-04-27 13:42:17 -07004778void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4779 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004780}
4781
chaviwa76b2712017-09-20 12:02:26 -07004782void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4783 int32_t maxLayerZ,
4784 const LayerVector::Visitor& visitor) {
4785 // We loop through the first level of layers without traversing,
4786 // as we need to interpret min/max layer Z in the top level Z space.
4787 for (const auto& layer : mDrawingState.layersSortedByZ) {
4788 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4789 continue;
4790 }
4791 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004792 // relative layers are traversed in Layer::traverseInZOrder
4793 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004794 continue;
4795 }
4796 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004797 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4798 return;
4799 }
chaviwa76b2712017-09-20 12:02:26 -07004800 if (!layer->isVisible()) {
4801 return;
4802 }
4803 visitor(layer);
4804 });
4805 }
4806}
4807
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004809
4810
4811#if defined(__gl_h_)
4812#error "don't include gl/gl.h in this file"
4813#endif
4814
4815#if defined(__gl2_h_)
4816#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004817#endif