blob: a6e0a9ec980cd8345c591c1abb33ee5baae15981 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
David Sodmanbc815282017-11-05 18:57:52 -0800157SurfaceFlingerBE::SurfaceFlingerBE()
158 : mHwcServiceName(getHwcServiceName()),
159 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800160 mFrameBuckets(),
161 mTotalTime(0),
162 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800163 mComposerSequenceId(0) {
164}
165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166SurfaceFlinger::SurfaceFlinger()
Lloyd Pique12eb4232018-01-17 11:54:43 -0800167 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700169 mTransactionPending(false),
170 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700172 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700173 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800175 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800177 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800178 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700181 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700182 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700183 mDebugInSwapBuffers(0),
184 mLastSwapBufferTime(0),
185 mDebugInTransaction(0),
186 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700187 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700188 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800189 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700191 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700192 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700193 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800194 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800195 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700196 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800197 mMainThreadId(std::this_thread::get_id()),
198 mCreateBufferQueue(&BufferQueue::createBufferQueue) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800200
201 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
203
204 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
206
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800207 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
David Sodman99974d22017-11-28 12:04:33 -0800229 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Dan Stoza0a0158c2018-03-16 13:38:54 -0700263 // TODO (b/74616334): Reduce the default value once we isolate the leak
264 const size_t defaultListSize = 4 * MAX_LAYERS;
265 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
266 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
267
Romain Guy11d63f42017-07-20 12:47:14 -0700268 // We should be reading 'persist.sys.sf.color_saturation' here
269 // but since /data may be encrypted, we need to wait until after vold
270 // comes online to attempt to read the property. The property is
271 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800272
273 if (useTrebleTestingOverride()) {
274 // Without the override SurfaceFlinger cannot connect to HIDL
275 // services that are not listed in the manifests. Considered
276 // deriving the setting from the set service name, but it
277 // would be brittle if the name that's not 'default' is used
278 // for production purposes later on.
279 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281}
282
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800283void SurfaceFlinger::onFirstRef()
284{
285 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800286}
287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288SurfaceFlinger::~SurfaceFlinger()
289{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290}
291
Dan Stozac7014012014-02-14 15:03:43 -0800292void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800293{
294 // the window manager died on us. prepare its eulogy.
295
Andy McFadden13a082e2012-08-24 10:16:42 -0700296 // restore initial conditions (default device unblank, etc)
297 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800298
299 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700300 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800301}
302
Robert Carr1db73f62016-12-21 12:58:51 -0800303static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700304 status_t err = client->initCheck();
305 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307 }
Robert Carr1db73f62016-12-21 12:58:51 -0800308 return nullptr;
309}
310
311sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
312 return initClient(new Client(this));
313}
314
315sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
316 const sp<IGraphicBufferProducer>& gbp) {
317 if (authenticateSurfaceTexture(gbp) == false) {
318 return nullptr;
319 }
320 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
321 if (layer == nullptr) {
322 return nullptr;
323 }
324
325 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326}
327
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700328sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
329 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700330{
331 class DisplayToken : public BBinder {
332 sp<SurfaceFlinger> flinger;
333 virtual ~DisplayToken() {
334 // no more references, this display must be terminated
335 Mutex::Autolock _l(flinger->mStateLock);
336 flinger->mCurrentState.displays.removeItem(this);
337 flinger->setTransactionFlags(eDisplayTransactionNeeded);
338 }
339 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700340 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341 : flinger(flinger) {
342 }
343 };
344
345 sp<BBinder> token = new DisplayToken(this);
346
347 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700348 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700349 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700351 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700352 return token;
353}
354
Jesse Hall6c913be2013-08-08 12:15:49 -0700355void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
356 Mutex::Autolock _l(mStateLock);
357
358 ssize_t idx = mCurrentState.displays.indexOfKey(display);
359 if (idx < 0) {
360 ALOGW("destroyDisplay: invalid display token");
361 return;
362 }
363
364 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
365 if (!info.isVirtualDisplay()) {
366 ALOGE("destroyDisplay called for non-virtual display");
367 return;
368 }
Irvelffc9efc2016-07-27 15:16:37 -0700369 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700370 mCurrentState.displays.removeItemsAt(idx);
371 setTransactionFlags(eDisplayTransactionNeeded);
372}
373
Mathias Agopiane57f2922012-08-09 16:29:12 -0700374sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700375 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700376 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800377 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700378 }
Jesse Hall692c7232012-11-08 15:41:56 -0800379 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700380}
381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382void SurfaceFlinger::bootFinished()
383{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700384 if (mStartPropertySetThread->join() != NO_ERROR) {
385 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800386 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387 const nsecs_t now = systemTime();
388 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000389 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700390
391 // wait patiently for the window manager death
392 const String16 name("window");
393 sp<IBinder> window(defaultServiceManager()->getService(name));
394 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700396 }
397
Steven Thomas050b2c82017-03-06 11:45:16 -0800398 if (mVrFlinger) {
399 mVrFlinger->OnBootFinished();
400 }
401
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700402 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700403 // formerly we would just kill the process, but we now ask it to exit so it
404 // can choose where to stop the animation.
405 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700406
407 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
408 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
409 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700410
Thierry Strudel2924d012017-08-14 15:19:37 -0700411 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700412 readPersistentProperties();
413 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700414 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian3f844832013-08-07 21:24:32 -0700417void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800419 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800422 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
423 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700425 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426 return true;
427 }
428 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700429 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430}
431
Lloyd Piquee83f9312018-02-01 12:53:17 -0800432class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700434 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000435 const char* name) :
436 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700437 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700438 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000439 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
440 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 mDispSync(dispSync),
442 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700443 mVsyncMutex(),
444 mPhaseOffset(phaseOffset),
445 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700446
Lloyd Piquee83f9312018-02-01 12:53:17 -0800447 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448
Lloyd Piquee83f9312018-02-01 12:53:17 -0800449 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700450 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700451 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000452 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 static_cast<DispSync::Callback*>(this));
454 if (err != NO_ERROR) {
455 ALOGE("error registering vsync callback: %s (%d)",
456 strerror(-err), err);
457 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700458 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700459 } else {
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700466 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 }
470
Lloyd Piquee83f9312018-02-01 12:53:17 -0800471 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 mCallback = callback;
474 }
475
Lloyd Piquee83f9312018-02-01 12:53:17 -0800476 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700477 Mutex::Autolock lock(mVsyncMutex);
478
479 // Normalize phaseOffset to [0, period)
480 auto period = mDispSync->getPeriod();
481 phaseOffset %= period;
482 if (phaseOffset < 0) {
483 // If we're here, then phaseOffset is in (-period, 0). After this
484 // operation, it will be in (0, period)
485 phaseOffset += period;
486 }
487 mPhaseOffset = phaseOffset;
488
489 // If we're not enabled, we don't need to mess with the listeners
490 if (!mEnabled) {
491 return;
492 }
493
494 // Remove the listener with the old offset
495 status_t err = mDispSync->removeEventListener(
496 static_cast<DispSync::Callback*>(this));
497 if (err != NO_ERROR) {
498 ALOGE("error unregistering vsync callback: %s (%d)",
499 strerror(-err), err);
500 }
501
502 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000503 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 static_cast<DispSync::Callback*>(this));
505 if (err != NO_ERROR) {
506 ALOGE("error registering vsync callback: %s (%d)",
507 strerror(-err), err);
508 }
509 }
510
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511private:
512 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800513 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 callback = mCallback;
517
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700518 if (mTraceVsync) {
519 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700520 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 }
523
Peiyong Lin566a3b42018-01-09 18:22:43 -0800524 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 callback->onVSyncEvent(when);
526 }
527 }
528
Tim Murray4a4e4a22016-04-19 16:29:23 +0000529 const char* const mName;
530
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 int mValue;
532
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700533 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700534 const String8 mVsyncOnLabel;
535 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700536
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538
539 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800540 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700541
542 Mutex mVsyncMutex; // Protects the following
543 nsecs_t mPhaseOffset;
544 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545};
546
Lloyd Piquee83f9312018-02-01 12:53:17 -0800547class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700548public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800549 InjectVSyncSource() = default;
550 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700551
Lloyd Piquee83f9312018-02-01 12:53:17 -0800552 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700553 std::lock_guard<std::mutex> lock(mCallbackMutex);
554 mCallback = callback;
555 }
556
Lloyd Piquee83f9312018-02-01 12:53:17 -0800557 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700559 if (mCallback) {
560 mCallback->onVSyncEvent(when);
561 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700562 }
563
Lloyd Piquee83f9312018-02-01 12:53:17 -0800564 void setVSyncEnabled(bool) override {}
565 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700566
567private:
568 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700570};
571
Wei Wangf9b05ee2017-07-19 20:59:39 -0700572// Do not call property_set on main thread which will be blocked by init
573// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700575 ALOGI( "SurfaceFlinger's main thread ready to run. "
576 "Initializing graphics H/W...");
577
Thierry Strudel2924d012017-08-14 15:19:37 -0700578 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900579
Steven Thomasb02664d2017-07-26 18:48:28 -0700580 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800583 mEventThreadSource =
584 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
585 true, "app");
586 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
587 "appEventThread");
588 mSfEventThreadSource =
589 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
590 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
591 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
592 "sfEventThread");
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800596 getBE().mRenderEngine =
597 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
598 hasWideColorDisplay
599 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
600 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800601 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700602
603 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
604 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800605 getBE().mHwc.reset(
606 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700607 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800608 // Process any initial hotplug and resulting display changes.
609 processDisplayHotplugEventsLocked();
610 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
611 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800612
Lloyd Piquefcd86612017-12-14 17:15:36 -0800613 // make the default display GLContext current so that we can create textures
614 // when creating Layers (which may happens before we render something)
615 getDefaultDisplayDeviceLocked()->makeCurrent();
616
Steven Thomas050b2c82017-03-06 11:45:16 -0800617 if (useVrFlinger) {
618 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700619 // This callback is called from the vr flinger dispatch thread. We
620 // need to call signalTransaction(), which requires holding
621 // mStateLock when we're not on the main thread. Acquiring
622 // mStateLock from the vr flinger dispatch thread might trigger a
623 // deadlock in surface flinger (see b/66916578), so post a message
624 // to be handled on the main thread instead.
625 sp<LambdaMessage> message = new LambdaMessage([=]() {
626 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
627 mVrFlingerRequestsDisplay = requestDisplay;
628 signalTransaction();
629 });
630 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800631 };
David Sodman105b7dc2017-11-04 20:28:14 -0700632 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
633 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800634 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 if (!mVrFlinger) {
636 ALOGE("Failed to start vrflinger");
637 }
638 }
639
Lloyd Pique755e3192018-01-31 16:46:15 -0800640 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
641 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
642 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700643
Mathias Agopian92a979a2012-08-02 18:32:23 -0700644 // initialize our drawing state
645 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700646
Andy McFadden13a082e2012-08-24 10:16:42 -0700647 // set initial conditions (e.g. unblank default device)
648 initializeDisplays();
649
David Sodmanbc815282017-11-05 18:57:52 -0800650 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700651
Wei Wangf9b05ee2017-07-19 20:59:39 -0700652 // Inform native graphics APIs whether the present timestamp is supported:
653 if (getHwComposer().hasCapability(
654 HWC2::Capability::PresentFenceIsNotReliable)) {
655 mStartPropertySetThread = new StartPropertySetThread(false);
656 } else {
657 mStartPropertySetThread = new StartPropertySetThread(true);
658 }
659
660 if (mStartPropertySetThread->Start() != NO_ERROR) {
661 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800663
Dan Stoza9e56aa02015-11-02 13:00:03 -0800664 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700665}
666
Romain Guy11d63f42017-07-20 12:47:14 -0700667void SurfaceFlinger::readPersistentProperties() {
668 char value[PROPERTY_VALUE_MAX];
669
670 property_get("persist.sys.sf.color_saturation", value, "1.0");
671 mSaturation = atof(value);
672 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100673
674 property_get("persist.sys.sf.native_mode", value, "0");
675 mForceNativeColorMode = atoi(value) == 1;
676 if (mForceNativeColorMode) {
677 ALOGV("Forcing native color mode");
678 }
Romain Guy11d63f42017-07-20 12:47:14 -0700679}
680
Mathias Agopiana67e4182012-06-19 17:26:12 -0700681void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800682 // Start boot animation service by setting a property mailbox
683 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800685 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700686 if (mStartPropertySetThread->join() != NO_ERROR) {
687 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800688 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700689}
690
Mathias Agopian875d8e12013-06-07 15:35:48 -0700691size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800692 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700693}
694
Mathias Agopian875d8e12013-06-07 15:35:48 -0700695size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800696 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700697}
698
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800700
Jamie Gennis582270d2011-08-17 18:19:00 -0700701bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800702 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800703 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800704 return authenticateSurfaceTextureLocked(bufferProducer);
705}
706
707bool SurfaceFlinger::authenticateSurfaceTextureLocked(
708 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800709 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800710 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800711}
712
Brian Anderson6b376712017-04-04 10:51:39 -0700713status_t SurfaceFlinger::getSupportedFrameTimestamps(
714 std::vector<FrameEvent>* outSupported) const {
715 *outSupported = {
716 FrameEvent::REQUESTED_PRESENT,
717 FrameEvent::ACQUIRE,
718 FrameEvent::LATCH,
719 FrameEvent::FIRST_REFRESH_START,
720 FrameEvent::LAST_REFRESH_START,
721 FrameEvent::GPU_COMPOSITION_DONE,
722 FrameEvent::DEQUEUE_READY,
723 FrameEvent::RELEASE,
724 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700725 ConditionalLock _l(mStateLock,
726 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700727 if (!getHwComposer().hasCapability(
728 HWC2::Capability::PresentFenceIsNotReliable)) {
729 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
730 }
731 return NO_ERROR;
732}
733
Dan Stoza7f7da322014-05-02 15:26:25 -0700734status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
735 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800736 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 return BAD_VALUE;
738 }
739
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500740 if (!display.get())
741 return NAME_NOT_FOUND;
742
Jesse Hall692c7232012-11-08 15:41:56 -0800743 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700744 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800745 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700746 type = i;
747 break;
748 }
749 }
750
751 if (type < 0) {
752 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700753 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755 // TODO: Not sure if display density should handled by SF any longer
756 class Density {
757 static int getDensityFromProperty(char const* propName) {
758 char property[PROPERTY_VALUE_MAX];
759 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800760 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 density = atoi(property);
762 }
763 return density;
764 }
765 public:
766 static int getEmuDensity() {
767 return getDensityFromProperty("qemu.sf.lcd_density"); }
768 static int getBuildDensity() {
769 return getDensityFromProperty("ro.sf.lcd_density"); }
770 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700771
Dan Stoza7f7da322014-05-02 15:26:25 -0700772 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700773
Steven Thomas6d8110b2017-08-31 18:24:21 -0700774 ConditionalLock _l(mStateLock,
775 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800776 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 DisplayInfo info = DisplayInfo();
778
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779 float xdpi = hwConfig->getDpiX();
780 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700781
782 if (type == DisplayDevice::DISPLAY_PRIMARY) {
783 // The density of the device is provided by a build property
784 float density = Density::getBuildDensity() / 160.0f;
785 if (density == 0) {
786 // the build doesn't provide a density -- this is wrong!
787 // use xdpi instead
788 ALOGE("ro.sf.lcd_density must be defined as a build property");
789 density = xdpi / 160.0f;
790 }
791 if (Density::getEmuDensity()) {
792 // if "qemu.sf.lcd_density" is specified, it overrides everything
793 xdpi = ydpi = density = Density::getEmuDensity();
794 density /= 160.0f;
795 }
796 info.density = density;
797
798 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800800 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 } else {
802 // TODO: where should this value come from?
803 static const int TV_DENSITY = 213;
804 info.density = TV_DENSITY / 160.0f;
805 info.orientation = 0;
806 }
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 info.w = hwConfig->getWidth();
809 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 info.xdpi = xdpi;
811 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900813 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814
Andy McFadden91b2ca82014-06-13 14:04:23 -0700815 // This is how far in advance a buffer must be queued for
816 // presentation at a given time. If you want a buffer to appear
817 // on the screen at time N, you must submit the buffer before
818 // (N - presentationDeadline).
819 //
820 // Normally it's one full refresh period (to give SF a chance to
821 // latch the buffer), but this can be reduced by configuring a
822 // DispSync offset. Any additional delays introduced by the hardware
823 // composer or panel must be accounted for here.
824 //
825 // We add an additional 1ms to allow for processing time and
826 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800828 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
830 // All non-virtual displays are currently considered secure.
831 info.secure = true;
832
Michael Wright28f24d02016-07-12 13:30:53 -0700833 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 }
835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 return NO_ERROR;
837}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700838
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800839status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700840 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800841 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700842 return BAD_VALUE;
843 }
844
845 // FIXME for now we always return stats for the primary display
846 memset(stats, 0, sizeof(*stats));
847 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
848 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
849 return NO_ERROR;
850}
851
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700852int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800853 if (display == nullptr) {
854 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800855 return BAD_VALUE;
856 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700857
858 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800859 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700860 return device->getActiveConfig();
861 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700862
Dan Stoza24a42e92015-03-09 10:04:11 -0700863 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700864}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700865
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700866void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
867 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
868 this);
869 int32_t type = hw->getDisplayType();
870 int currentMode = hw->getActiveConfig();
871
872 if (mode == currentMode) {
873 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
874 return;
875 }
876
877 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
878 ALOGW("Trying to set config for virtual display");
879 return;
880 }
881
882 hw->setActiveConfig(mode);
883 getHwComposer().setActiveConfig(type, mode);
884}
885
886status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
887 class MessageSetActiveConfig: public MessageBase {
888 SurfaceFlinger& mFlinger;
889 sp<IBinder> mDisplay;
890 int mMode;
891 public:
892 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
893 int mode) :
894 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
895 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700896 Vector<DisplayInfo> configs;
897 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700898 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700899 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700900 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700901 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700902 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700903 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800904 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700905 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700906 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700907 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
908 ALOGW("Attempt to set active config = %d for virtual display",
909 mMode);
910 } else {
911 mFlinger.setActiveConfigInternal(hw, mMode);
912 }
913 return true;
914 }
915 };
916 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
917 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700918 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700919}
Michael Wright28f24d02016-07-12 13:30:53 -0700920status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700921 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700922 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
923 return BAD_VALUE;
924 }
925
926 if (!display.get()) {
927 return NAME_NOT_FOUND;
928 }
929
930 int32_t type = NAME_NOT_FOUND;
931 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
932 if (display == mBuiltinDisplays[i]) {
933 type = i;
934 break;
935 }
936 }
937
938 if (type < 0) {
939 return type;
940 }
941
Peiyong Lina52f0292018-03-14 17:26:31 -0700942 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700943 {
944 ConditionalLock _l(mStateLock,
945 std::this_thread::get_id() != mMainThreadId);
946 modes = getHwComposer().getColorModes(type);
947 }
Michael Wright28f24d02016-07-12 13:30:53 -0700948 outColorModes->clear();
949 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
950
951 return NO_ERROR;
952}
953
Peiyong Lina52f0292018-03-14 17:26:31 -0700954ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700955 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700956 if (device != nullptr) {
957 return device->getActiveColorMode();
958 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700959 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700960}
961
962void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700963 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700964 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700965 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700966
967 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700968 return;
969 }
970
971 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
972 ALOGW("Trying to set config for virtual display");
973 return;
974 }
975
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600976 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
977 hw->getDisplayType());
978
Michael Wright28f24d02016-07-12 13:30:53 -0700979 hw->setActiveColorMode(mode);
980 getHwComposer().setActiveColorMode(type, mode);
981}
982
983
984status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700985 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700986 class MessageSetActiveColorMode: public MessageBase {
987 SurfaceFlinger& mFlinger;
988 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -0700990 public:
991 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -0700993 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
994 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -0700995 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -0700996 mFlinger.getDisplayColorModes(mDisplay, &modes);
997 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -0700998 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600999 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1000 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001001 return true;
1002 }
1003 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1004 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1006 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001007 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001008 ALOGW("Attempt to set active color mode %s %d for virtual display",
1009 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001010 } else {
1011 mFlinger.setActiveColorModeInternal(hw, mMode);
1012 }
1013 return true;
1014 }
1015 };
1016 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1017 postMessageSync(msg);
1018 return NO_ERROR;
1019}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001020
Svetoslavd85084b2014-03-20 10:28:31 -07001021status_t SurfaceFlinger::clearAnimationFrameStats() {
1022 Mutex::Autolock _l(mStateLock);
1023 mAnimFrameTracker.clearStats();
1024 return NO_ERROR;
1025}
1026
1027status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1028 Mutex::Autolock _l(mStateLock);
1029 mAnimFrameTracker.getStats(outStats);
1030 return NO_ERROR;
1031}
1032
Dan Stozac4f471e2016-03-24 09:31:08 -07001033status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1034 HdrCapabilities* outCapabilities) const {
1035 Mutex::Autolock _l(mStateLock);
1036
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001037 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001038 if (displayDevice == nullptr) {
1039 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1040 return BAD_VALUE;
1041 }
1042
1043 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001044 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001045 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001046 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1047 // insert HDR10 as we will force client composition for HDR10
1048 // layers
1049 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1050 types.push_back(HAL_HDR_HDR10);
1051
1052 *outCapabilities = HdrCapabilities(types,
1053 capabilities->getDesiredMaxLuminance(),
1054 capabilities->getDesiredMaxAverageLuminance(),
1055 capabilities->getDesiredMinLuminance());
1056 } else {
1057 *outCapabilities = std::move(*capabilities);
1058 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001059 } else {
1060 return BAD_VALUE;
1061 }
1062
1063 return NO_ERROR;
1064}
1065
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1068 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 if (mInjectVSyncs == enable) {
1071 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073
1074 if (enable) {
1075 ALOGV("VSync Injections enabled");
1076 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001077 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001078 mInjectorEventThread =
1079 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1080 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001082 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 } else {
1084 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001085 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 }
1087
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089 });
1090 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 return NO_ERROR;
1092}
1093
1094status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001095 Mutex::Autolock _l(mStateLock);
1096
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097 if (!mInjectVSyncs) {
1098 ALOGE("VSync Injections not enabled");
1099 return BAD_VALUE;
1100 }
1101 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1102 ALOGV("Injecting VSync inside SurfaceFlinger");
1103 mVSyncInjector->onInjectSyncEvent(when);
1104 }
1105 return NO_ERROR;
1106}
1107
Lloyd Pique755e3192018-01-31 16:46:15 -08001108status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1109 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001110 IPCThreadState* ipc = IPCThreadState::self();
1111 const int pid = ipc->getCallingPid();
1112 const int uid = ipc->getCallingUid();
1113 if ((uid != AID_SHELL) &&
1114 !PermissionCache::checkPermission(sDump, pid, uid)) {
1115 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1116 return PERMISSION_DENIED;
1117 }
1118
1119 // Try to acquire a lock for 1s, fail gracefully
1120 const status_t err = mStateLock.timedLock(s2ns(1));
1121 const bool locked = (err == NO_ERROR);
1122 if (!locked) {
1123 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1124 return TIMED_OUT;
1125 }
1126
1127 outLayers->clear();
1128 mCurrentState.traverseInZOrder([&](Layer* layer) {
1129 outLayers->push_back(layer->getLayerDebugInfo());
1130 });
1131
1132 mStateLock.unlock();
1133 return NO_ERROR;
1134}
1135
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001136// ----------------------------------------------------------------------------
1137
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001138sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1139 ISurfaceComposer::VsyncSource vsyncSource) {
1140 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1141 return mSFEventThread->createEventConnection();
1142 } else {
1143 return mEventThread->createEventConnection();
1144 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001145}
1146
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001147// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148
1149void SurfaceFlinger::waitForEvent() {
1150 mEventQueue.waitMessage();
1151}
1152
1153void SurfaceFlinger::signalTransaction() {
1154 mEventQueue.invalidate();
1155}
1156
1157void SurfaceFlinger::signalLayerUpdate() {
1158 mEventQueue.invalidate();
1159}
1160
1161void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001162 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 mEventQueue.refresh();
1164}
1165
1166status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001167 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001168 return mEventQueue.postMessage(msg, reltime);
1169}
1170
1171status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001172 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001173 status_t res = mEventQueue.postMessage(msg, reltime);
1174 if (res == NO_ERROR) {
1175 msg->wait();
1176 }
1177 return res;
1178}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001180void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001181 do {
1182 waitForEvent();
1183 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001184}
1185
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186void SurfaceFlinger::enableHardwareVsync() {
1187 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001190 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1191 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001193 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194}
1195
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001197 Mutex::Autolock _l(mHWVsyncLock);
1198
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199 if (makeAvailable) {
1200 mHWVsyncAvailable = true;
1201 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001202 // Hardware vsync is not currently available, so abort the resync
1203 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001204 return;
1205 }
1206
David Sodman105b7dc2017-11-04 20:28:14 -07001207 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209
1210 mPrimaryDispSync.reset();
1211 mPrimaryDispSync.setPeriod(period);
1212
1213 if (!mPrimaryHWVsyncEnabled) {
1214 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001215 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1216 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 mPrimaryHWVsyncEnabled = true;
1218 }
1219}
1220
Jesse Hall948fe0c2013-10-14 12:56:09 -07001221void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222 Mutex::Autolock _l(mHWVsyncLock);
1223 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001224 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1225 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 mPrimaryDispSync.endResync();
1227 mPrimaryHWVsyncEnabled = false;
1228 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001229 if (makeUnavailable) {
1230 mHWVsyncAvailable = false;
1231 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232}
1233
Tim Murray4a4e4a22016-04-19 16:29:23 +00001234void SurfaceFlinger::resyncWithRateLimit() {
1235 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001236
1237 // No explicit locking is needed here since EventThread holds a lock while calling this method
1238 static nsecs_t sLastResyncAttempted = 0;
1239 const nsecs_t now = systemTime();
1240 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001241 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001242 }
Dan Stoza57164302017-05-08 14:03:54 -07001243 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244}
1245
Steven Thomasb02664d2017-07-26 18:48:28 -07001246void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1247 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001248 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001249 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001250 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001251 return;
1252 }
1253
1254 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001255 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001256 return;
1257 }
1258
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 { // Scope for the lock
1262 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001263 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001264 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001266 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001267
1268 if (needsHwVsync) {
1269 enableHardwareVsync();
1270 } else {
1271 disableHardwareVsync(false);
1272 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001273}
1274
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001275void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001276 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1277 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278}
1279
Lloyd Pique715a2c12017-12-14 17:18:08 -08001280void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1281 HWC2::Connection connection) {
1282 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1283 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284
Lloyd Piqueba04e622017-12-14 17:11:26 -08001285 // Ignore events that do not have the right sequenceId.
1286 if (sequenceId != getBE().mComposerSequenceId) {
1287 return;
1288 }
1289
Steven Thomasb02664d2017-07-26 18:48:28 -07001290 // Only lock if we're not on the main thread. This function is normally
1291 // called on a hwbinder thread, but for the primary display it's called on
1292 // the main thread with the state lock already held, so don't attempt to
1293 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001294 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001295
Lloyd Pique715a2c12017-12-14 17:18:08 -08001296 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001297
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001298 if (std::this_thread::get_id() == mMainThreadId) {
1299 // Process all pending hot plug events immediately if we are on the main thread.
1300 processDisplayHotplugEventsLocked();
1301 }
1302
Lloyd Piqueba04e622017-12-14 17:11:26 -08001303 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Steven Thomasb02664d2017-07-26 18:48:28 -07001306void SurfaceFlinger::onRefreshReceived(int sequenceId,
1307 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001309 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001310 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001311 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001312 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001313}
1314
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 getHwComposer().setVsyncEnabled(disp,
1319 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001320}
1321
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001323void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 // Clear the drawing state so that the logic inside of
1326 // handleTransactionLocked will fire. It will determine the delta between
1327 // mCurrentState and mDrawingState and re-apply all changes when we make the
1328 // transition.
1329 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001330 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001331 mDisplays.clear();
1332}
1333
Steven Thomas050b2c82017-03-06 11:45:16 -08001334void SurfaceFlinger::updateVrFlinger() {
1335 if (!mVrFlinger)
1336 return;
1337 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001339 return;
1340 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
David Sodman105b7dc2017-11-04 20:28:14 -07001342 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 ALOGE("Vr flinger is only supported for remote hardware composer"
1344 " service connections. Ignoring request to transition to vr"
1345 " flinger.");
1346 mVrFlingerRequestsDisplay = false;
1347 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001348 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001351
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 int currentDisplayPowerMode = getDisplayDeviceLocked(
1353 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001360 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001361 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1362 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001363 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001364
David Sodman105b7dc2017-11-04 20:28:14 -07001365 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1366 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001367
1368 if (vrFlingerRequestsDisplay) {
1369 mVrFlinger->GrantDisplayOwnership();
1370 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001371 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001372 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001373
1374 mVisibleRegionsDirty = true;
1375 invalidateHwcGeometry();
1376
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001377 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1379 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1380 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001383 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 const nsecs_t period = activeConfig->getVsyncPeriod();
1385 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 // Use phase of 0 since phase is not known.
1388 // Use latency of 0, which will snap to the ideal latency.
1389 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001390
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391 android_atomic_or(1, &mRepaintEverything);
1392 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393}
1394
Mathias Agopian4fec8732012-06-29 14:12:52 -07001395void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001396 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001397 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001398 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001399 bool frameMissed = !mHadClientComposition &&
1400 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001401 (mPreviousPresentFence->getSignalTime() ==
1402 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001403 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001404 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001405 signalLayerUpdate();
1406 break;
1407 }
1408
Steven Thomas050b2c82017-03-06 11:45:16 -08001409 // Now that we're going to make it to the handleMessageTransaction()
1410 // call below it's safe to call updateVrFlinger(), which will
1411 // potentially trigger a display handoff.
1412 updateVrFlinger();
1413
Dan Stoza6b9454d2014-11-07 16:00:59 -08001414 bool refreshNeeded = handleMessageTransaction();
1415 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001416 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001417 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001418 // Signal a refresh if a transaction modified the window state,
1419 // a new buffer was latched, or if HWC has requested a full
1420 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421 signalRefresh();
1422 }
1423 break;
1424 }
1425 case MessageQueue::REFRESH: {
1426 handleMessageRefresh();
1427 break;
1428 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001429 }
1430}
1431
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001433 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001435 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001437 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001439}
1440
Dan Stoza6b9454d2014-11-07 16:00:59 -08001441bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001444}
1445
1446void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001448
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001449 mRefreshPending = false;
1450
Pablo Ceballos40845df2016-01-25 17:41:15 -08001451 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001452
Brian Andersond6927fb2016-07-23 23:37:30 -07001453 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001454 rebuildLayerStacks();
1455 setUpHWComposer();
1456 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001457 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001458 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001459 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001460
David Sodman105b7dc2017-11-04 20:28:14 -07001461 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001462
1463 mHadClientComposition = false;
1464 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1465 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1466 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001467 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001468 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001469
Dan Stoza9e56aa02015-11-02 13:00:03 -08001470 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473void SurfaceFlinger::doDebugFlashRegions()
1474{
1475 // is debugging enabled
1476 if (CC_LIKELY(!mDebugRegion))
1477 return;
1478
1479 const bool repaintEverything = mRepaintEverything;
1480 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1481 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001482 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483 // transform the dirty region into this screen's coordinate space
1484 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1485 if (!dirtyRegion.isEmpty()) {
1486 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001487 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001488
1489 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001491 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001492 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1493
Mathias Agopianda27af92012-09-13 18:17:13 -07001494 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495 }
1496 }
1497 }
1498
1499 postFramebuffer();
1500
1501 if (mDebugRegion > 1) {
1502 usleep(mDebugRegion * 1000);
1503 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001504
Dan Stoza9e56aa02015-11-02 13:00:03 -08001505 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001506 auto& displayDevice = mDisplays[displayId];
1507 if (!displayDevice->isDisplayOn()) {
1508 continue;
1509 }
1510
David Sodman105b7dc2017-11-04 20:28:14 -07001511 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1512 ALOGE_IF(result != NO_ERROR,
1513 "prepareFrame for display %zd failed:"
1514 " %d (%s)",
1515 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001516 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517}
1518
Adrian Roos1e1a1282017-11-01 19:05:31 +01001519void SurfaceFlinger::doTracing(const char* where) {
1520 ATRACE_CALL();
1521 ATRACE_NAME(where);
1522 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001523 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001524 }
1525}
1526
Brian Andersond6927fb2016-07-23 23:37:30 -07001527void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 ATRACE_CALL();
1530 ALOGV("preComposition");
1531
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001533 mDrawingState.traverseInZOrder([&](Layer* layer) {
1534 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535 needExtraInvalidate = true;
1536 }
Robert Carr2047fae2016-11-28 14:09:09 -08001537 });
1538
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539 if (needExtraInvalidate) {
1540 signalLayerUpdate();
1541 }
1542}
1543
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001544void SurfaceFlinger::updateCompositorTiming(
1545 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1546 std::shared_ptr<FenceTime>& presentFenceTime) {
1547 // Update queue of past composite+present times and determine the
1548 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001549 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001550 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001551 while (!getBE().mCompositePresentTimes.empty()) {
1552 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001553 // Cached values should have been updated before calling this method,
1554 // which helps avoid duplicate syscalls.
1555 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1556 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1557 break;
1558 }
1559 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001560 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561 }
1562
1563 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001564 while (getBE().mCompositePresentTimes.size() > 16) {
1565 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001566 }
1567
Brian Andersond0010582017-03-07 13:20:31 -08001568 setCompositorTimingSnapped(
1569 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1570}
1571
1572void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1573 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574 // Integer division and modulo round toward 0 not -inf, so we need to
1575 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001576 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001577 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1578 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1579
Brian Andersond0010582017-03-07 13:20:31 -08001580 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1581 if (idealLatency <= 0) {
1582 idealLatency = vsyncInterval;
1583 }
1584
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585 // Snap the latency to a value that removes scheduling jitter from the
1586 // composition and present times, which often have >1ms of jitter.
1587 // Reducing jitter is important if an app attempts to extrapolate
1588 // something (such as user input) to an accurate diasplay time.
1589 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1590 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001591 nsecs_t bias = vsyncInterval / 2;
1592 int64_t extraVsyncs =
1593 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1594 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1595 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001596
David Sodman99974d22017-11-28 12:04:33 -08001597 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1598 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1599 getBE().mCompositorTiming.interval = vsyncInterval;
1600 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601}
1602
1603void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001605 ATRACE_CALL();
1606 ALOGV("postComposition");
1607
Brian Anderson3546a3f2016-07-14 11:51:14 -07001608 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001609 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001610 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001611 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001612 }
1613
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001614 // |mStateLock| not needed as we are on the main thread
1615 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001616
David Sodman73beded2017-11-15 11:56:06 -08001617 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001618 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001619 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001620 glCompositionDoneFenceTime =
1621 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001622 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001623 } else {
1624 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1625 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001626
David Sodman73beded2017-11-15 11:56:06 -08001627 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001628 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001629 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001630 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001631
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1633 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1634
1635 // We use the refreshStartTime which might be sampled a little later than
1636 // when we started doing work for this frame, but that should be okay
1637 // since updateCompositorTiming has snapping logic.
1638 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001639 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001640 CompositorTiming compositorTiming;
1641 {
David Sodman99974d22017-11-28 12:04:33 -08001642 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1643 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001644 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645
Robert Carr2047fae2016-11-28 14:09:09 -08001646 mDrawingState.traverseInZOrder([&](Layer* layer) {
1647 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001648 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001649 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001650 recordBufferingStats(layer->getName().string(),
1651 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001652 }
Robert Carr2047fae2016-11-28 14:09:09 -08001653 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001654
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001655 if (presentFenceTime->isValid()) {
1656 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001657 enableHardwareVsync();
1658 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001659 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001660 }
1661 }
1662
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001663 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001664 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001665 enableHardwareVsync();
1666 }
1667 }
1668
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001669 if (mAnimCompositionPending) {
1670 mAnimCompositionPending = false;
1671
Brian Anderson4e606e32017-03-16 15:34:57 -07001672 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001674 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001675 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001676 // The HWC doesn't support present fences, so use the refresh
1677 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001679 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001680 mAnimFrameTracker.setActualPresentTime(presentTime);
1681 }
1682 mAnimFrameTracker.advanceFrame();
1683 }
Dan Stozab90cf072015-03-05 11:05:59 -08001684
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001685 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1686 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001687 return;
1688 }
1689
1690 nsecs_t currentTime = systemTime();
1691 if (mHasPoweredOff) {
1692 mHasPoweredOff = false;
1693 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001694 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001696 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1697 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001698 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001699 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001700 }
David Sodman4a36e932017-11-07 14:29:47 -08001701 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001702 }
David Sodman4a36e932017-11-07 14:29:47 -08001703 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001704}
1705
1706void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 ATRACE_CALL();
1708 ALOGV("rebuildLayerStacks");
1709
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001711 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001712 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001713 mVisibleRegionsDirty = false;
1714 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001715
Jeff Sharkey76488112017-02-27 14:15:18 -07001716 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1717 Region opaqueRegion;
1718 Region dirtyRegion;
1719 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001720 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001721 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1722 const Transform& tr(displayDevice->getTransform());
1723 const Rect bounds(displayDevice->getBounds());
1724 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001725 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001726
Jeff Sharkey76488112017-02-27 14:15:18 -07001727 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001728 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001729 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1730 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001731 Region drawRegion(tr.transform(
1732 layer->visibleNonTransparentRegion));
1733 drawRegion.andSelf(bounds);
1734 if (!drawRegion.isEmpty()) {
1735 layersSortedByZ.add(layer);
1736 } else {
1737 // Clear out the HWC layer if this layer was
1738 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001739 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001740 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001742 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001743 // WM changes displayDevice->layerStack upon sleep/awake.
1744 // Here we make sure we delete the HWC layers even if
1745 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001746 hwcLayerDestroyed = layer->destroyHwcLayer(
1747 displayDevice->getHwcDisplayId());
1748 }
1749
1750 // If a layer is not going to get a release fence because
1751 // it is invisible, but it is also going to release its
1752 // old buffer, add it to the list of layers needing
1753 // fences.
1754 if (hwcLayerDestroyed) {
1755 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1756 mLayersWithQueuedFrames.cend(), layer);
1757 if (found != mLayersWithQueuedFrames.cend()) {
1758 layersNeedingFences.add(layer);
1759 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001760 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001761 });
1762 }
1763 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001764 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 displayDevice->undefinedRegion.set(bounds);
1766 displayDevice->undefinedRegion.subtractSelf(
1767 tr.transform(opaqueRegion));
1768 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001770 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001772
Romain Guy0147a172017-06-01 13:53:56 -07001773mat4 SurfaceFlinger::computeSaturationMatrix() const {
1774 if (mSaturation == 1.0f) {
1775 return mat4();
1776 }
1777
1778 // Rec.709 luma coefficients
1779 float3 luminance{0.213f, 0.715f, 0.072f};
1780 luminance *= 1.0f - mSaturation;
1781 return mat4(
1782 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1783 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1784 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1785 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1786 );
1787}
1788
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001789// pickColorMode translates a given dataspace into the best available color mode.
1790// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001791ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001792 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001793 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001794 }
1795
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001796 switch (dataSpace) {
1797 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1798 // system expects.
1799 case HAL_DATASPACE_UNKNOWN:
1800 case HAL_DATASPACE_SRGB:
1801 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001802 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001803 break;
1804
1805 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001806 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001807 break;
1808
1809 default:
1810 // TODO (courtneygo): Do we want to assert an error here?
1811 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1812 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001813 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001814 break;
1815 }
1816}
1817
Romain Guy0147a172017-06-01 13:53:56 -07001818android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001819 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001820 // Only support sRGB and Display-P3 right now.
1821 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1822 return HAL_DATASPACE_DISPLAY_P3;
1823 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001824 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1825 return HAL_DATASPACE_DISPLAY_P3;
1826 }
1827 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1828 return HAL_DATASPACE_DISPLAY_P3;
1829 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001830 if (!hasHdr) {
1831 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1832 return HAL_DATASPACE_DISPLAY_P3;
1833 }
1834 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1835 return HAL_DATASPACE_DISPLAY_P3;
1836 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001837 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001838
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001839 return HAL_DATASPACE_V0_SRGB;
1840}
1841
Mathias Agopiancd60f992012-08-16 16:28:27 -07001842void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 ATRACE_CALL();
1844 ALOGV("setUpHWComposer");
1845
Jesse Hall028dc8f2013-08-20 16:35:32 -07001846 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001847 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1848 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1849 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1850
1851 // If nothing has changed (!dirty), don't recompose.
1852 // If something changed, but we don't currently have any visible layers,
1853 // and didn't when we last did a composition, then skip it this time.
1854 // The second rule does two things:
1855 // - When all layers are removed from a display, we'll emit one black
1856 // frame, then nothing more until we get new layers.
1857 // - When a display is created with a private layer stack, we won't
1858 // emit any black frames until a layer is added to the layer stack.
1859 bool mustRecompose = dirty && !(empty && wasEmpty);
1860
1861 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1862 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1863 mustRecompose ? "doing" : "skipping",
1864 dirty ? "+" : "-",
1865 empty ? "+" : "-",
1866 wasEmpty ? "+" : "-");
1867
Dan Stoza71433162014-02-04 16:22:36 -08001868 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001869
1870 if (mustRecompose) {
1871 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1872 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001873 }
1874
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 // build the h/w work list
1876 if (CC_UNLIKELY(mGeometryInvalid)) {
1877 mGeometryInvalid = false;
1878 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1879 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1880 const auto hwcId = displayDevice->getHwcDisplayId();
1881 if (hwcId >= 0) {
1882 const Vector<sp<Layer>>& currentLayers(
1883 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001884 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001885 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001887 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001890 }
1891 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001892
Robert Carrae060832016-11-28 10:51:00 -08001893 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001894 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001896 }
1897 }
1898 }
1899 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 }
Riley Andrews03414a12014-07-01 14:22:59 -07001901
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001902
Romain Guy0147a172017-06-01 13:53:56 -07001903 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 // Set the per-frame data
1906 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1907 auto& displayDevice = mDisplays[displayId];
1908 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001909
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 if (hwcId < 0) {
1911 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001912 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001913 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001914 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001915 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1916 "display %zd: %d", displayId, result);
1917 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001919 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1920 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001921 !displayDevice->getHdrSupport()) {
1922 layer->forceClientComposition(hwcId);
1923 }
1924
chaviwc9232ed2017-11-14 15:31:15 -08001925 if (layer->getForceClientComposition(hwcId)) {
1926 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1927 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1928 continue;
1929 }
1930
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 layer->setPerFrameData(displayDevice);
1932 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001933
1934 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001935 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001936 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1937
1938 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001939 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1940 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001941 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1942 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1943 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1944 }
1945 newColorMode = pickColorMode(newDataSpace);
1946
Thierry Strudel2924d012017-08-14 15:19:37 -07001947 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 }
1950
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001951 mPreviousColorMatrix = colorMatrix;
1952
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001954 auto& displayDevice = mDisplays[displayId];
1955 if (!displayDevice->isDisplayOn()) {
1956 continue;
1957 }
1958
David Sodman105b7dc2017-11-04 20:28:14 -07001959 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1961 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001962 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001963}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001964
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965void SurfaceFlinger::doComposition() {
1966 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 ALOGV("doComposition");
1968
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001969 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001970 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001971 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001972 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973 // transform the dirty region into this screen's coordinate space
1974 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001975
1976 // repaint the framebuffer (if needed)
1977 doDisplayComposition(hw, dirtyRegion);
1978
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001980 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001981 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001982 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001983 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001984}
1985
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986void SurfaceFlinger::postFramebuffer()
1987{
Mathias Agopian841cde52012-03-01 15:44:37 -08001988 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001990
Mathias Agopiana44b0412011-10-16 18:46:35 -07001991 const nsecs_t now = systemTime();
1992 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001993
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1995 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001996 if (!displayDevice->isDisplayOn()) {
1997 continue;
1998 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 const auto hwcId = displayDevice->getHwcDisplayId();
2000 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002001 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002002 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002003 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002004 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002006 // The layer buffer from the previous frame (if any) is released
2007 // by HWC only when the release fence from this frame (if any) is
2008 // signaled. Always get the release fence from HWC first.
2009 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002010 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002011
2012 // If the layer was client composited in the previous frame, we
2013 // need to merge with the previous client target acquire fence.
2014 // Since we do not track that, always merge with the current
2015 // client target acquire fence when it is available, even though
2016 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002018 releaseFence = Fence::merge("LayerRelease", releaseFence,
2019 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002020 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002021
Dan Stoza9e56aa02015-11-02 13:00:03 -08002022 layer->onLayerDisplayed(releaseFence);
2023 }
Chia-I Wu83806892017-11-16 10:50:20 -08002024
2025 // We've got a list of layers needing fences, that are disjoint with
2026 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2027 // supply them with the present fence.
2028 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002029 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002030 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2031 layer->onLayerDisplayed(presentFence);
2032 }
2033 }
2034
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002036 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002037 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002038 }
2039
Mathias Agopiana44b0412011-10-16 18:46:35 -07002040 mLastSwapBufferTime = systemTime() - now;
2041 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002042
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002043 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002044 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2045 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2046 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2047 logFrameStats();
2048 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050}
2051
Mathias Agopian87baae12012-07-31 12:38:26 -07002052void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002053{
Mathias Agopian841cde52012-03-01 15:44:37 -08002054 ATRACE_CALL();
2055
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002056 // here we keep a copy of the drawing state (that is the state that's
2057 // going to be overwritten by handleTransactionLocked()) outside of
2058 // mStateLock so that the side-effects of the State assignment
2059 // don't happen with mStateLock held (which can cause deadlocks).
2060 State drawingState(mDrawingState);
2061
Mathias Agopianca4d3602011-05-19 15:38:14 -07002062 Mutex::Autolock _l(mStateLock);
2063 const nsecs_t now = systemTime();
2064 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065
Mathias Agopianca4d3602011-05-19 15:38:14 -07002066 // Here we're guaranteed that some transaction flags are set
2067 // so we can call handleTransactionLocked() unconditionally.
2068 // We call getTransactionFlags(), which will also clear the flags,
2069 // with mStateLock held to guarantee that mCurrentState won't change
2070 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002071
Mathias Agopiane57f2922012-08-09 16:29:12 -07002072 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002073 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002074
Mathias Agopianca4d3602011-05-19 15:38:14 -07002075 mLastTransactionTime = systemTime() - now;
2076 mDebugInTransaction = 0;
2077 invalidateHwcGeometry();
2078 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002079}
2080
Lloyd Pique715a2c12017-12-14 17:18:08 -08002081DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2082 HWC2::Connection connection) const {
2083 // Figure out whether the event is for the primary display or an
2084 // external display by matching the Hwc display id against one for a
2085 // connected display. If we did not find a match, we then check what
2086 // displays are not already connected to determine the type. If we don't
2087 // have a connected primary display, we assume the new display is meant to
2088 // be the primary display, and then if we don't have an external display,
2089 // we assume it is that.
2090 const auto primaryDisplayId =
2091 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2092 const auto externalDisplayId =
2093 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2094 if (primaryDisplayId && primaryDisplayId == display) {
2095 return DisplayDevice::DISPLAY_PRIMARY;
2096 } else if (externalDisplayId && externalDisplayId == display) {
2097 return DisplayDevice::DISPLAY_EXTERNAL;
2098 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2099 return DisplayDevice::DISPLAY_PRIMARY;
2100 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2101 return DisplayDevice::DISPLAY_EXTERNAL;
2102 }
2103
2104 return DisplayDevice::DISPLAY_ID_INVALID;
2105}
2106
Lloyd Piqueba04e622017-12-14 17:11:26 -08002107void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2108 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002109 auto displayType = determineDisplayType(event.display, event.connection);
2110 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2111 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2112 continue;
2113 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002114
2115 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2116 ALOGE("External displays are not supported by the vr hardware composer.");
2117 continue;
2118 }
2119
Lloyd Pique715a2c12017-12-14 17:18:08 -08002120 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002121
2122 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002123 if (!mBuiltinDisplays[displayType].get()) {
2124 ALOGV("Creating built in display %d", displayType);
2125 mBuiltinDisplays[displayType] = new BBinder();
2126 // All non-virtual displays are currently considered secure.
2127 DisplayDeviceState info(displayType, true);
2128 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2129 "Built-in Screen" : "External Screen";
2130 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2131 mInterceptor.saveDisplayCreation(info);
2132 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002133 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002134 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002135
Lloyd Piquefcd86612017-12-14 17:15:36 -08002136 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2137 if (idx >= 0) {
2138 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2139 mInterceptor.saveDisplayDeletion(info.displayId);
2140 mCurrentState.displays.removeItemsAt(idx);
2141 }
2142 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002143 }
2144
2145 processDisplayChangesLocked();
2146 }
2147
2148 mPendingHotplugEvents.clear();
2149}
2150
Lloyd Pique347200f2017-12-14 17:00:15 -08002151void SurfaceFlinger::processDisplayChangesLocked() {
2152 // here we take advantage of Vector's copy-on-write semantics to
2153 // improve performance by skipping the transaction entirely when
2154 // know that the lists are identical
2155 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2156 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2157 if (!curr.isIdenticalTo(draw)) {
2158 mVisibleRegionsDirty = true;
2159 const size_t cc = curr.size();
2160 size_t dc = draw.size();
2161
2162 // find the displays that were removed
2163 // (ie: in drawing state but not in current state)
2164 // also handle displays that changed
2165 // (ie: displays that are in both lists)
2166 for (size_t i = 0; i < dc;) {
2167 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2168 if (j < 0) {
2169 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002170 // Call makeCurrent() on the primary display so we can
2171 // be sure that nothing associated with this display
2172 // is current.
2173 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2174 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2175 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2176 if (hw != nullptr) hw->disconnect(getHwComposer());
2177 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2178 mEventThread->onHotplugReceived(draw[i].type, false);
2179 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002180 } else {
2181 // this display is in both lists. see if something changed.
2182 const DisplayDeviceState& state(curr[j]);
2183 const wp<IBinder>& display(curr.keyAt(j));
2184 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2185 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2186 if (state_binder != draw_binder) {
2187 // changing the surface is like destroying and
2188 // recreating the DisplayDevice, so we just remove it
2189 // from the drawing state, so that it get re-added
2190 // below.
2191 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2192 if (hw != nullptr) hw->disconnect(getHwComposer());
2193 mDisplays.removeItem(display);
2194 mDrawingState.displays.removeItemsAt(i);
2195 dc--;
2196 // at this point we must loop to the next item
2197 continue;
2198 }
2199
2200 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2201 if (disp != nullptr) {
2202 if (state.layerStack != draw[i].layerStack) {
2203 disp->setLayerStack(state.layerStack);
2204 }
2205 if ((state.orientation != draw[i].orientation) ||
2206 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2207 disp->setProjection(state.orientation, state.viewport, state.frame);
2208 }
2209 if (state.width != draw[i].width || state.height != draw[i].height) {
2210 disp->setDisplaySize(state.width, state.height);
2211 }
2212 }
2213 }
2214 ++i;
2215 }
2216
2217 // find displays that were added
2218 // (ie: in current state but not in drawing state)
2219 for (size_t i = 0; i < cc; i++) {
2220 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2221 const DisplayDeviceState& state(curr[i]);
2222
2223 sp<DisplaySurface> dispSurface;
2224 sp<IGraphicBufferProducer> producer;
2225 sp<IGraphicBufferProducer> bqProducer;
2226 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002227 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002228
2229 int32_t hwcId = -1;
2230 if (state.isVirtualDisplay()) {
2231 // Virtual displays without a surface are dormant:
2232 // they have external state (layer stack, projection,
2233 // etc.) but no internal state (i.e. a DisplayDevice).
2234 if (state.surface != nullptr) {
2235 // Allow VR composer to use virtual displays.
2236 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2237 int width = 0;
2238 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2239 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2240 int height = 0;
2241 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2242 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2243 int intFormat = 0;
2244 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2245 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2246 auto format = static_cast<android_pixel_format_t>(intFormat);
2247
2248 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2249 }
2250
2251 // TODO: Plumb requested format back up to consumer
2252
2253 sp<VirtualDisplaySurface> vds =
2254 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2255 bqProducer, bqConsumer,
2256 state.displayName);
2257
2258 dispSurface = vds;
2259 producer = vds;
2260 }
2261 } else {
2262 ALOGE_IF(state.surface != nullptr,
2263 "adding a supported display, but rendering "
2264 "surface is provided (%p), ignoring it",
2265 state.surface.get());
2266
2267 hwcId = state.type;
2268 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2269 producer = bqProducer;
2270 }
2271
2272 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002273
Lloyd Pique347200f2017-12-14 17:00:15 -08002274 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002275 bool hasWideColorSupport = false;
2276 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002277 std::vector<ColorMode> modes =
Lloyd Piquefcd86612017-12-14 17:15:36 -08002278 getHwComposer().getColorModes(state.type);
Peiyong Lina52f0292018-03-14 17:26:31 -07002279 for (ColorMode colorMode : modes) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002280 switch (colorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002281 case ColorMode::DISPLAY_P3:
2282 case ColorMode::ADOBE_RGB:
2283 case ColorMode::DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002284 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002285 break;
2286 default:
2287 break;
2288 }
2289 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002290 }
2291
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002292 bool hasHdrSupport = false;
2293 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2294 getHwComposer().getHdrCapabilities(state.type);
2295 if (hdrCapabilities) {
2296 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2297 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2298 hasHdrSupport = iter != types.cend();
2299 }
2300
Lloyd Pique347200f2017-12-14 17:00:15 -08002301 sp<DisplayDevice> hw =
2302 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002303 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002304 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002305
Peiyong Lina52f0292018-03-14 17:26:31 -07002306 ColorMode defaultColorMode = ColorMode::NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002307 if (hasWideColorSupport) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002308 defaultColorMode = ColorMode::SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002309 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002310 setActiveColorModeInternal(hw, defaultColorMode);
2311 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002312 hw->setLayerStack(state.layerStack);
2313 hw->setProjection(state.orientation, state.viewport, state.frame);
2314 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002315
Lloyd Pique347200f2017-12-14 17:00:15 -08002316 mDisplays.add(display, hw);
2317 if (!state.isVirtualDisplay()) {
2318 mEventThread->onHotplugReceived(state.type, true);
2319 }
2320 }
2321 }
2322 }
2323 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002324
2325 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002326}
2327
Mathias Agopian87baae12012-07-31 12:38:26 -07002328void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002329{
Dan Stoza7dde5992015-05-22 09:51:44 -07002330 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002331 mCurrentState.traverseInZOrder([](Layer* layer) {
2332 layer->notifyAvailableFrames();
2333 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 /*
2336 * Traversal of the children
2337 * (perform the transaction for each of them if needed)
2338 */
2339
Mathias Agopian3559b072012-08-15 13:46:03 -07002340 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002341 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002343 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344
2345 const uint32_t flags = layer->doTransaction(0);
2346 if (flags & Layer::eVisibleRegion)
2347 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002348 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 }
2350
2351 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002352 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353 */
2354
Mathias Agopiane57f2922012-08-09 16:29:12 -07002355 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002356 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002357 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002358 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359
Mathias Agopian84300952012-11-21 16:02:13 -08002360 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2361 // The transform hint might have changed for some layers
2362 // (either because a display has changed, or because a layer
2363 // as changed).
2364 //
2365 // Walk through all the layers in currentLayers,
2366 // and update their transform hint.
2367 //
2368 // If a layer is visible only on a single display, then that
2369 // display is used to calculate the hint, otherwise we use the
2370 // default display.
2371 //
2372 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2373 // the hint is set before we acquire a buffer from the surface texture.
2374 //
2375 // NOTE: layer transactions have taken place already, so we use their
2376 // drawing state. However, SurfaceFlinger's own transaction has not
2377 // happened yet, so we must use the current state layer list
2378 // (soon to become the drawing state list).
2379 //
2380 sp<const DisplayDevice> disp;
2381 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002382 bool first = true;
2383 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002384 // NOTE: we rely on the fact that layers are sorted by
2385 // layerStack first (so we don't have to traverse the list
2386 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002387 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002388 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002389 currentlayerStack = layerStack;
2390 // figure out if this layerstack is mirrored
2391 // (more than one display) if so, pick the default display,
2392 // if not, pick the only display it's on.
2393 disp.clear();
2394 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2395 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002396 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002397 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002398 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002399 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002400 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002401 break;
2402 }
2403 }
2404 }
2405 }
Chet Haase91d25932013-04-11 15:24:55 -07002406
Robert Carr56a0b9a2017-12-04 16:06:13 -08002407 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002408 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002409 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2410 // redraw after transform hint changes. See bug 8508397.
2411
2412 // could be null when this layer is using a layerStack
2413 // that is not visible on any display. Also can occur at
2414 // screen off/on times.
2415 disp = getDefaultDisplayDeviceLocked();
2416 }
2417 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002418 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002419 if (disp != nullptr) {
2420 layer->updateTransformHint(disp);
2421 }
Robert Carr2047fae2016-11-28 14:09:09 -08002422
2423 first = false;
2424 });
Mathias Agopian84300952012-11-21 16:02:13 -08002425 }
2426
2427
Mathias Agopian3559b072012-08-15 13:46:03 -07002428 /*
2429 * Perform our own transaction if needed
2430 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002431
2432 if (mLayersAdded) {
2433 mLayersAdded = false;
2434 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002435 mVisibleRegionsDirty = true;
2436 }
2437
2438 // some layers might have been removed, so
2439 // we need to update the regions they're exposing.
2440 if (mLayersRemoved) {
2441 mLayersRemoved = false;
2442 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002443 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002444 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002445 // this layer is not visible anymore
2446 // TODO: we could traverse the tree from front to back and
2447 // compute the actual visible region
2448 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002449 Region visibleReg;
2450 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002451 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002452 }
Robert Carr2047fae2016-11-28 14:09:09 -08002453 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 }
2455
2456 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002457
2458 updateCursorAsync();
2459}
2460
2461void SurfaceFlinger::updateCursorAsync()
2462{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2464 auto& displayDevice = mDisplays[displayId];
2465 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002466 continue;
2467 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468
2469 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2470 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002471 }
2472 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002473}
2474
2475void SurfaceFlinger::commitTransaction()
2476{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002477 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002479 for (const auto& l : mLayersPendingRemoval) {
2480 recordBufferingStats(l->getName().string(),
2481 l->getOccupancyHistory(true));
2482 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002483 }
2484 mLayersPendingRemoval.clear();
2485 }
2486
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002487 // If this transaction is part of a window animation then the next frame
2488 // we composite should be considered an animation as well.
2489 mAnimCompositionPending = mAnimTransactionPending;
2490
Mathias Agopian4fec8732012-06-29 14:12:52 -07002491 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002492 mDrawingState.traverseInZOrder([](Layer* layer) {
2493 layer->commitChildList();
2494 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002495 mTransactionPending = false;
2496 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002497 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498}
2499
Chia-I Wuab0c3192017-08-01 11:29:00 -07002500void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002501 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502{
Mathias Agopian841cde52012-03-01 15:44:37 -08002503 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 Region aboveOpaqueLayers;
2507 Region aboveCoveredLayers;
2508 Region dirty;
2509
Mathias Agopian87baae12012-07-31 12:38:26 -07002510 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
Robert Carr2047fae2016-11-28 14:09:09 -08002512 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002514 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Jesse Hall01e29052013-02-19 16:13:35 -08002516 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002517 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002518 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002519
Mathias Agopianab028732010-03-16 16:41:46 -07002520 /*
2521 * opaqueRegion: area of a surface that is fully opaque.
2522 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002524
2525 /*
2526 * visibleRegion: area of a surface that is visible on screen
2527 * and not fully transparent. This is essentially the layer's
2528 * footprint minus the opaque regions above it.
2529 * Areas covered by a translucent surface are considered visible.
2530 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002532
2533 /*
2534 * coveredRegion: area of a surface that is covered by all
2535 * visible regions above it (which includes the translucent areas).
2536 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002538
Jesse Halla8026d22012-09-25 13:25:04 -07002539 /*
2540 * transparentRegion: area of a surface that is hinted to be completely
2541 * transparent. This is only used to tell when the layer has no visible
2542 * non-transparent regions and can be removed from the layer list. It
2543 * does not affect the visibleRegion of this layer or any layers
2544 * beneath it. The hint may not be correct if apps don't respect the
2545 * SurfaceView restrictions (which, sadly, some don't).
2546 */
2547 Region transparentRegion;
2548
Mathias Agopianab028732010-03-16 16:41:46 -07002549
2550 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002551 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002552 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002553 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002556 if (!visibleRegion.isEmpty()) {
2557 // Remove the transparent area from the visible region
2558 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002559 if (tr.preserveRects()) {
2560 // transform the transparent region
2561 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002562 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002563 // transformation too complex, can't do the
2564 // transparent region optimization.
2565 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002566 }
Mathias Agopianab028732010-03-16 16:41:46 -07002567 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568
Mathias Agopianab028732010-03-16 16:41:46 -07002569 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002570 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002571 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002572 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2573 // the opaque region is the layer's footprint
2574 opaqueRegion = visibleRegion;
2575 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 }
2577 }
2578
Robert Carre5f4f692018-01-12 13:12:28 -08002579 if (visibleRegion.isEmpty()) {
2580 layer->clearVisibilityRegions();
2581 return;
2582 }
2583
Mathias Agopianab028732010-03-16 16:41:46 -07002584 // Clip the covered region to the visible region
2585 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2586
2587 // Update aboveCoveredLayers for next (lower) layer
2588 aboveCoveredLayers.orSelf(visibleRegion);
2589
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 // subtract the opaque region covered by the layers above us
2591 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592
2593 // compute this layer's dirty region
2594 if (layer->contentDirty) {
2595 // we need to invalidate the whole region
2596 dirty = visibleRegion;
2597 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002598 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 layer->contentDirty = false;
2600 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002601 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002602 * the exposed region consists of two components:
2603 * 1) what's VISIBLE now and was COVERED before
2604 * 2) what's EXPOSED now less what was EXPOSED before
2605 *
2606 * note that (1) is conservative, we start with the whole
2607 * visible region but only keep what used to be covered by
2608 * something -- which mean it may have been exposed.
2609 *
2610 * (2) handles areas that were not covered by anything but got
2611 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002612 */
Mathias Agopianab028732010-03-16 16:41:46 -07002613 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002614 const Region oldVisibleRegion = layer->visibleRegion;
2615 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002616 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2617 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 }
2619 dirty.subtractSelf(aboveOpaqueLayers);
2620
2621 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002622 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623
Mathias Agopianab028732010-03-16 16:41:46 -07002624 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002626
Jesse Halla8026d22012-09-25 13:25:04 -07002627 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 layer->setVisibleRegion(visibleRegion);
2629 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002630 layer->setVisibleNonTransparentRegion(
2631 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002632 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633
Mathias Agopian87baae12012-07-31 12:38:26 -07002634 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635}
2636
Chia-I Wuab0c3192017-08-01 11:29:00 -07002637void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002638 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002639 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002640 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002641 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002642 }
2643 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002644}
2645
Dan Stoza6b9454d2014-11-07 16:00:59 -08002646bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002648 ALOGV("handlePageFlip");
2649
Brian Andersond6927fb2016-07-23 23:37:30 -07002650 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002653 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002654 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002655
2656 // Store the set of layers that need updates. This set must not change as
2657 // buffers are being latched, as this could result in a deadlock.
2658 // Example: Two producers share the same command stream and:
2659 // 1.) Layer 0 is latched
2660 // 2.) Layer 0 gets a new frame
2661 // 2.) Layer 1 gets a new frame
2662 // 3.) Layer 1 is latched.
2663 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2664 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002665 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002666 if (layer->hasQueuedFrame()) {
2667 frameQueued = true;
2668 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002669 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002670 } else {
2671 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002672 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002673 } else {
2674 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002675 }
Robert Carr2047fae2016-11-28 14:09:09 -08002676 });
2677
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002679 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002680 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002681 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002682 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002683 newDataLatched = true;
2684 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002685 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002686
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002687 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002688
2689 // If we will need to wake up at some time in the future to deal with a
2690 // queued frame that shouldn't be displayed during this vsync period, wake
2691 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002692 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002693 signalLayerUpdate();
2694 }
2695
2696 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002697 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698}
2699
Mathias Agopianad456f92011-01-13 17:53:01 -08002700void SurfaceFlinger::invalidateHwcGeometry()
2701{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002703}
2704
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002705
Fabien Sanglard830b8472016-11-30 16:35:58 -08002706void SurfaceFlinger::doDisplayComposition(
2707 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002708 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709{
Dan Stoza71433162014-02-04 16:22:36 -08002710 // We only need to actually compose the display if:
2711 // 1) It is being handled by hardware composer, which may need this to
2712 // keep its virtual display state machine in sync, or
2713 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002714 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002715 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002717 return;
2718 }
2719
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002721 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002722
2723 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002724 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
Chia-I Wub02087d2017-11-09 10:19:54 -08002727bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002728{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002730
Chia-I Wub02087d2017-11-09 10:19:54 -08002731 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002732 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002734
2735 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002736 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2737 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002738 if (applyColorMatrix) {
2739 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2740 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2741 }
2742
David Sodman105b7dc2017-11-04 20:28:14 -07002743 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 if (hasClientComposition) {
2745 ALOGV("hasClientComposition");
2746
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002747 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002748 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002749 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002750 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2751 }
2752 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2753
Chia-I Wu7f402902017-11-09 12:51:10 -08002754 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002755 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002757 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002758
2759 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002760 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002761 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2762 }
2763 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002764 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002765
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002766 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002767 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002769 // when using overlays, we assume a fully transparent framebuffer
2770 // NOTE: we could reduce how much we need to clear, for instance
2771 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002772 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002773 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002774 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002775 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002776 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002777 // we're left with the letterbox region
2778 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002780
2781 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002783
Mathias Agopianb9494d52012-04-18 02:28:45 -07002784 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002785 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002786 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002788 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002789 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002790
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002792 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002793 // scissor on the main display. It should never be needed
2794 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 const Rect& bounds(displayDevice->getBounds());
2796 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002797 if (scissor != bounds) {
2798 // scissor doesn't match the screen's dimensions, so we
2799 // need to clear everything outside of it and enable
2800 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002801
Mathias Agopianf45c5102012-10-24 16:29:17 -07002802 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002804 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002805 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002806 }
2807 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002808 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002809
Mathias Agopian85d751c2012-08-29 16:59:24 -07002810 /*
2811 * and then, render the layers targeted at the framebuffer
2812 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002813
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 ALOGV("Rendering client layers");
2815 const Transform& displayTransform = displayDevice->getTransform();
2816 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002817 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 bool firstLayer = true;
2819 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002820 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 displayTransform.transform(layer->visibleRegion)));
2822 ALOGV("Layer: %s", layer->getName().string());
2823 ALOGV(" Composition type: %s",
2824 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002825 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 switch (layer->getCompositionType(hwcId)) {
2827 case HWC2::Composition::Cursor:
2828 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002829 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002831 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002833 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002835 // never clear the very first layer since we're
2836 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002837 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002838 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002839 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002840 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002842 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002843 break;
2844 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002846 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 } else {
2849 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002850 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002851 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002852 }
2853 } else {
2854 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002856 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002857 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002858 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002859 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002860 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002861 }
2862 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002863
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002864 if (applyColorMatrix) {
2865 getRenderEngine().setupColorTransform(oldColorMatrix);
2866 }
2867
Mathias Agopianf45c5102012-10-24 16:29:17 -07002868 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002869 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002870 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871}
2872
Fabien Sanglard830b8472016-11-30 16:35:58 -08002873void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2874 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002875 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002876 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877}
2878
Dan Stoza7d89d062015-04-30 13:29:25 -07002879status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002880 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002881 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 const sp<Layer>& lbc,
2883 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002884{
Dan Stoza7d89d062015-04-30 13:29:25 -07002885 // add this layer to the current state list
2886 {
2887 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002889 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2890 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002891 return NO_MEMORY;
2892 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002893 if (parent == nullptr) {
2894 mCurrentState.layersSortedByZ.add(lbc);
2895 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002896 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002897 ALOGE("addClientLayer called with a removed parent");
2898 return NAME_NOT_FOUND;
2899 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002900 parent->addChild(lbc);
2901 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002902
Dan Stoza101d8dc2018-02-27 15:42:25 -08002903 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002904 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2905 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2906 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2907 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2908 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909 mLayersAdded = true;
2910 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002911 }
2912
Mathias Agopian96f08192010-06-02 23:28:45 -07002913 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002914 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002915
Dan Stoza7d89d062015-04-30 13:29:25 -07002916 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002917}
2918
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002919status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002920 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002921 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2922}
Robert Carr7f9b8992017-03-10 11:08:39 -08002923
chaviwca27f252018-02-06 16:46:39 -08002924status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2925 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002926 if (layer->isPendingRemoval()) {
2927 return NO_ERROR;
2928 }
2929
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002931 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002932 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002933 if (topLevelOnly) {
2934 return NO_ERROR;
2935 }
2936
Chia-I Wu98f1c102017-05-30 14:54:08 -07002937 sp<Layer> ancestor = p;
2938 while (ancestor->getParent() != nullptr) {
2939 ancestor = ancestor->getParent();
2940 }
2941 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2942 ALOGE("removeLayer called with a layer whose parent has been removed");
2943 return NAME_NOT_FOUND;
2944 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002945
2946 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002947 } else {
2948 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002949 }
2950
Robert Carr136e2f62017-02-08 17:54:29 -08002951 // As a matter of normal operation, the LayerCleaner will produce a second
2952 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2953 // so we will succeed in promoting it, but it's already been removed
2954 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2955 // otherwise something has gone wrong and we are leaking the layer.
2956 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002957 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2958 layer->getName().string(),
2959 (p != nullptr) ? p->getName().string() : "no-parent");
2960 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002961 } else if (index < 0) {
2962 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002963 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964
Chia-I Wuc6657022017-08-15 11:18:17 -07002965 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002966 mLayersPendingRemoval.add(layer);
2967 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002968 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002969 setTransactionFlags(eTransactionNeeded);
2970 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971}
2972
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002973uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002974 return android_atomic_release_load(&mTransactionFlags);
2975}
2976
Mathias Agopian3f844832013-08-07 21:24:32 -07002977uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2979}
2980
Mathias Agopian3f844832013-08-07 21:24:32 -07002981uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2983 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002984 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 }
2986 return old;
2987}
2988
chaviwca27f252018-02-06 16:46:39 -08002989bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
2990 for (const ComposerState& state : states) {
2991 // Here we need to check that the interface we're given is indeed
2992 // one of our own. A malicious client could give us a nullptr
2993 // IInterface, or one of its own or even one of our own but a
2994 // different type. All these situations would cause us to crash.
2995 if (state.client == nullptr) {
2996 return true;
2997 }
2998
2999 sp<IBinder> binder = IInterface::asBinder(state.client);
3000 if (binder == nullptr) {
3001 return true;
3002 }
3003
3004 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3005 return true;
3006 }
3007 }
3008 return false;
3009}
3010
Mathias Agopian8b33f032012-07-24 20:43:54 -07003011void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003012 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003013 const Vector<DisplayState>& displays,
3014 uint32_t flags)
3015{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003016 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003017 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003018 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003019
chaviwca27f252018-02-06 16:46:39 -08003020 if (containsAnyInvalidClientState(states)) {
3021 return;
3022 }
3023
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003024 if (flags & eAnimation) {
3025 // For window updates that are part of an animation we must wait for
3026 // previous animation "frames" to be handled.
3027 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003028 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003029 if (CC_UNLIKELY(err != NO_ERROR)) {
3030 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003031 // caller after a few seconds.
3032 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3033 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003034 mAnimTransactionPending = false;
3035 break;
3036 }
3037 }
3038 }
3039
chaviwca27f252018-02-06 16:46:39 -08003040 for (const DisplayState& display : displays) {
3041 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003042 }
3043
chaviwca27f252018-02-06 16:46:39 -08003044 for (const ComposerState& state : states) {
3045 transactionFlags |= setClientStateLocked(state);
3046 }
3047
3048 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3049 // as destroyed should only occur after setting all other states. This is to allow for a
3050 // child re-parent to happen before marking its original parent as destroyed (which would
3051 // then mark the child as destroyed).
3052 for (const ComposerState& state : states) {
3053 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003054 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003055
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003056 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3057 // anyway. This can be used as a flush mechanism for previous async transactions.
3058 // Empty animation transaction can be used to simulate back-pressure, so also force a
3059 // transaction for empty animation transactions.
3060 if (transactionFlags == 0 &&
3061 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003062 transactionFlags = eTransactionNeeded;
3063 }
3064
Mathias Agopian386aa982011-11-07 21:58:03 -08003065 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003066 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003067 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003068 }
Irvel468051e2016-06-13 16:44:44 -07003069
Mathias Agopian386aa982011-11-07 21:58:03 -08003070 // this triggers the transaction
3071 setTransactionFlags(transactionFlags);
3072
3073 // if this is a synchronous transaction, wait for it to take effect
3074 // before returning.
3075 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003076 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003077 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003078 if (flags & eAnimation) {
3079 mAnimTransactionPending = true;
3080 }
3081 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003082 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3083 if (CC_UNLIKELY(err != NO_ERROR)) {
3084 // just in case something goes wrong in SF, return to the
3085 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003086 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3087 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003088 break;
3089 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 }
3092}
3093
Mathias Agopiane57f2922012-08-09 16:29:12 -07003094uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3095{
Jesse Hall9a143922012-10-04 16:29:19 -07003096 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3097 if (dpyIdx < 0)
3098 return 0;
3099
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003101 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003102 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003103 const uint32_t what = s.what;
3104 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003105 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003106 disp.surface = s.surface;
3107 flags |= eDisplayTransactionNeeded;
3108 }
3109 }
3110 if (what & DisplayState::eLayerStackChanged) {
3111 if (disp.layerStack != s.layerStack) {
3112 disp.layerStack = s.layerStack;
3113 flags |= eDisplayTransactionNeeded;
3114 }
3115 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003116 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003117 if (disp.orientation != s.orientation) {
3118 disp.orientation = s.orientation;
3119 flags |= eDisplayTransactionNeeded;
3120 }
3121 if (disp.frame != s.frame) {
3122 disp.frame = s.frame;
3123 flags |= eDisplayTransactionNeeded;
3124 }
3125 if (disp.viewport != s.viewport) {
3126 disp.viewport = s.viewport;
3127 flags |= eDisplayTransactionNeeded;
3128 }
3129 }
Michael Lentine47e45402014-07-18 15:34:25 -07003130 if (what & DisplayState::eDisplaySizeChanged) {
3131 if (disp.width != s.width) {
3132 disp.width = s.width;
3133 flags |= eDisplayTransactionNeeded;
3134 }
3135 if (disp.height != s.height) {
3136 disp.height = s.height;
3137 flags |= eDisplayTransactionNeeded;
3138 }
3139 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003140 }
3141 return flags;
3142}
3143
chaviwca27f252018-02-06 16:46:39 -08003144uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3145 const layer_state_t& s = composerState.state;
3146 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3147
Mathias Agopian13127d82013-03-05 17:47:11 -08003148 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003149 if (layer == nullptr) {
3150 return 0;
3151 }
3152
3153 if (layer->isPendingRemoval()) {
3154 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3155 return 0;
3156 }
3157
3158 uint32_t flags = 0;
3159
3160 const uint32_t what = s.what;
3161 bool geometryAppliesWithResize =
3162 what & layer_state_t::eGeometryAppliesWithResize;
3163 if (what & layer_state_t::ePositionChanged) {
3164 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3165 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003166 }
chaviw8b3871a2017-11-01 17:41:01 -07003167 }
3168 if (what & layer_state_t::eLayerChanged) {
3169 // NOTE: index needs to be calculated before we update the state
3170 const auto& p = layer->getParent();
3171 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003172 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003173 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003174 mCurrentState.layersSortedByZ.removeAt(idx);
3175 mCurrentState.layersSortedByZ.add(layer);
3176 // we need traversal (state changed)
3177 // AND transaction (list changed)
3178 flags |= eTransactionNeeded|eTraversalNeeded;
3179 }
chaviw8b3871a2017-11-01 17:41:01 -07003180 } else {
3181 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003182 flags |= eTransactionNeeded|eTraversalNeeded;
3183 }
3184 }
chaviw8b3871a2017-11-01 17:41:01 -07003185 }
3186 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003187 // NOTE: index needs to be calculated before we update the state
3188 const auto& p = layer->getParent();
3189 if (p == nullptr) {
3190 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3191 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3192 mCurrentState.layersSortedByZ.removeAt(idx);
3193 mCurrentState.layersSortedByZ.add(layer);
3194 // we need traversal (state changed)
3195 // AND transaction (list changed)
3196 flags |= eTransactionNeeded|eTraversalNeeded;
3197 }
3198 } else {
3199 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3200 flags |= eTransactionNeeded|eTraversalNeeded;
3201 }
chaviw8b3871a2017-11-01 17:41:01 -07003202 }
3203 }
3204 if (what & layer_state_t::eSizeChanged) {
3205 if (layer->setSize(s.w, s.h)) {
3206 flags |= eTraversalNeeded;
3207 }
3208 }
3209 if (what & layer_state_t::eAlphaChanged) {
3210 if (layer->setAlpha(s.alpha))
3211 flags |= eTraversalNeeded;
3212 }
3213 if (what & layer_state_t::eColorChanged) {
3214 if (layer->setColor(s.color))
3215 flags |= eTraversalNeeded;
3216 }
3217 if (what & layer_state_t::eMatrixChanged) {
3218 if (layer->setMatrix(s.matrix))
3219 flags |= eTraversalNeeded;
3220 }
3221 if (what & layer_state_t::eTransparentRegionChanged) {
3222 if (layer->setTransparentRegionHint(s.transparentRegion))
3223 flags |= eTraversalNeeded;
3224 }
3225 if (what & layer_state_t::eFlagsChanged) {
3226 if (layer->setFlags(s.flags, s.mask))
3227 flags |= eTraversalNeeded;
3228 }
3229 if (what & layer_state_t::eCropChanged) {
3230 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3231 flags |= eTraversalNeeded;
3232 }
3233 if (what & layer_state_t::eFinalCropChanged) {
3234 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3235 flags |= eTraversalNeeded;
3236 }
3237 if (what & layer_state_t::eLayerStackChanged) {
3238 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3239 // We only allow setting layer stacks for top level layers,
3240 // everything else inherits layer stack from its parent.
3241 if (layer->hasParent()) {
3242 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3243 layer->getName().string());
3244 } else if (idx < 0) {
3245 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3246 "that also does not appear in the top level layer list. Something"
3247 " has gone wrong.", layer->getName().string());
3248 } else if (layer->setLayerStack(s.layerStack)) {
3249 mCurrentState.layersSortedByZ.removeAt(idx);
3250 mCurrentState.layersSortedByZ.add(layer);
3251 // we need traversal (state changed)
3252 // AND transaction (list changed)
3253 flags |= eTransactionNeeded|eTraversalNeeded;
3254 }
3255 }
3256 if (what & layer_state_t::eDeferTransaction) {
3257 if (s.barrierHandle != nullptr) {
3258 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3259 } else if (s.barrierGbp != nullptr) {
3260 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3261 if (authenticateSurfaceTextureLocked(gbp)) {
3262 const auto& otherLayer =
3263 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3264 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3265 } else {
3266 ALOGE("Attempt to defer transaction to to an"
3267 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003268 }
3269 }
chaviw8b3871a2017-11-01 17:41:01 -07003270 // We don't trigger a traversal here because if no other state is
3271 // changed, we don't want this to cause any more work
3272 }
3273 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003274 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003275 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003276 if (!hadParent) {
3277 mCurrentState.layersSortedByZ.remove(layer);
3278 }
chaviw8b3871a2017-11-01 17:41:01 -07003279 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 }
3282 if (what & layer_state_t::eReparentChildren) {
3283 if (layer->reparentChildren(s.reparentHandle)) {
3284 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003285 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286 }
chaviw8b3871a2017-11-01 17:41:01 -07003287 if (what & layer_state_t::eDetachChildren) {
3288 layer->detachChildren();
3289 }
3290 if (what & layer_state_t::eOverrideScalingModeChanged) {
3291 layer->setOverrideScalingMode(s.overrideScalingMode);
3292 // We don't trigger a traversal here because if no other state is
3293 // changed, we don't want this to cause any more work
3294 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295 return flags;
3296}
3297
chaviwca27f252018-02-06 16:46:39 -08003298void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3299 const layer_state_t& state = composerState.state;
3300 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3301
3302 sp<Layer> layer(client->getLayerUser(state.surface));
3303 if (layer == nullptr) {
3304 return;
3305 }
3306
3307 if (layer->isPendingRemoval()) {
3308 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3309 return;
3310 }
3311
3312 if (state.what & layer_state_t::eDestroySurface) {
3313 removeLayerLocked(mStateLock, layer);
3314 }
3315}
3316
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003317status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003318 const String8& name,
3319 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003320 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003321 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3322 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003324 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003325 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003326 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003327 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003328 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003329
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003330 status_t result = NO_ERROR;
3331
3332 sp<Layer> layer;
3333
Cody Northropbc755282017-03-31 12:00:08 -06003334 String8 uniqueName = getUniqueLayerName(name);
3335
Mathias Agopian3165cc22012-08-08 19:42:09 -07003336 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3337 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003338 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003339 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003340 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342 break;
chaviw13fdc492017-06-27 12:40:18 -07003343 case ISurfaceComposerClient::eFXSurfaceColor:
3344 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003345 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003346 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003347 break;
3348 default:
3349 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350 break;
3351 }
3352
Dan Stoza7d89d062015-04-30 13:29:25 -07003353 if (result != NO_ERROR) {
3354 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003356
Chia-I Wuab0c3192017-08-01 11:29:00 -07003357 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3358 // TODO b/64227542
3359 if (windowType == 441731) {
3360 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3361 layer->setPrimaryDisplayOnly();
3362 }
3363
Albert Chaulk479c60c2017-01-27 14:21:34 -05003364 layer->setInfo(windowType, ownerUid);
3365
Robert Carr1f0a16a2016-10-24 16:27:39 -07003366 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003367 if (result != NO_ERROR) {
3368 return result;
3369 }
Irvelffc9efc2016-07-27 15:16:37 -07003370 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003371
3372 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003373 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003374}
3375
Cody Northropbc755282017-03-31 12:00:08 -06003376String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3377{
3378 bool matchFound = true;
3379 uint32_t dupeCounter = 0;
3380
3381 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3382 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3383
3384 // Loop over layers until we're sure there is no matching name
3385 while (matchFound) {
3386 matchFound = false;
3387 mDrawingState.traverseInZOrder([&](Layer* layer) {
3388 if (layer->getName() == uniqueName) {
3389 matchFound = true;
3390 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3391 }
3392 });
3393 }
3394
3395 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3396
3397 return uniqueName;
3398}
3399
David Sodman0c69cad2017-08-21 12:12:51 -07003400status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003401 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3402 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403{
3404 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003405 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003406 case PIXEL_FORMAT_TRANSPARENT:
3407 case PIXEL_FORMAT_TRANSLUCENT:
3408 format = PIXEL_FORMAT_RGBA_8888;
3409 break;
3410 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003411 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003412 break;
3413 }
3414
David Sodman0c69cad2017-08-21 12:12:51 -07003415 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3416 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003417 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003418 *handle = layer->getHandle();
3419 *gbp = layer->getProducer();
3420 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003421 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003422
David Sodman0c69cad2017-08-21 12:12:51 -07003423 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003424 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003425}
3426
chaviw13fdc492017-06-27 12:40:18 -07003427status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003428 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003429 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003430{
chaviw13fdc492017-06-27 12:40:18 -07003431 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003432 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003433 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003434}
3435
Mathias Agopianac9fa422013-02-11 16:40:36 -08003436status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437{
Robert Carr9524cb32017-02-13 11:32:32 -08003438 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003439 status_t err = NO_ERROR;
3440 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003441 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003442 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003443 err = removeLayer(l);
3444 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3445 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003446 }
3447 return err;
3448}
3449
Mathias Agopian13127d82013-03-05 17:47:11 -08003450status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003451{
Mathias Agopian67106042013-03-14 19:18:13 -07003452 // called by ~LayerCleaner() when all references to the IBinder (handle)
3453 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003454 sp<Layer> l = layer.promote();
3455 if (l == nullptr) {
3456 // The layer has already been removed, carry on
3457 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003458 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003459 // If we have a parent, then we can continue to live as long as it does.
3460 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461}
3462
Mathias Agopianb60314a2012-04-10 22:09:54 -07003463// ---------------------------------------------------------------------------
3464
Andy McFadden13a082e2012-08-24 10:16:42 -07003465void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003466 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003467 Vector<ComposerState> state;
3468 Vector<DisplayState> displays;
3469 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003470 d.what = DisplayState::eDisplayProjectionChanged |
3471 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003472 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003473 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003474 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003475 d.frame.makeInvalid();
3476 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003477 d.width = 0;
3478 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003479 displays.add(d);
3480 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003481 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3482 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003483
David Sodman105b7dc2017-11-04 20:28:14 -07003484 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003485 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003486 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003487
Brian Andersond0010582017-03-07 13:20:31 -08003488 // Use phase of 0 since phase is not known.
3489 // Use latency of 0, which will snap to the ideal latency.
3490 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003491}
3492
3493void SurfaceFlinger::initializeDisplays() {
3494 class MessageScreenInitialized : public MessageBase {
3495 SurfaceFlinger* flinger;
3496 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003497 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003498 virtual bool handler() {
3499 flinger->onInitializeDisplays();
3500 return true;
3501 }
3502 };
3503 sp<MessageBase> msg = new MessageScreenInitialized(this);
3504 postMessageAsync(msg); // we may be called from main thread, use async message
3505}
3506
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003507void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003508 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003509 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3510 this);
3511 int32_t type = hw->getDisplayType();
3512 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003513
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003514 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003515 return;
3516 }
3517
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003518 hw->setPowerMode(mode);
3519 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3520 ALOGW("Trying to set power mode for virtual display");
3521 return;
3522 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003523
Irvelffc9efc2016-07-27 15:16:37 -07003524 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003525 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003526 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3527 if (idx < 0) {
3528 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3529 return;
3530 }
3531 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3532 }
3533
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003534 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003535 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003536 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003537 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3538 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003539 // FIXME: eventthread only knows about the main display right now
3540 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003541 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003544 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003545 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003546 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003547
3548 struct sched_param param = {0};
3549 param.sched_priority = 1;
3550 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3551 ALOGW("Couldn't set SCHED_FIFO on display on");
3552 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003553 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003554 // Turn off the display
3555 struct sched_param param = {0};
3556 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3557 ALOGW("Couldn't set SCHED_OTHER on display off");
3558 }
3559
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003560 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3561 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003562 disableHardwareVsync(true); // also cancels any in-progress resync
3563
Mathias Agopiancde87a32012-09-13 14:09:01 -07003564 // FIXME: eventthread only knows about the main display right now
3565 mEventThread->onScreenReleased();
3566 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003567
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003568 getHwComposer().setPowerMode(type, mode);
3569 mVisibleRegionsDirty = true;
3570 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003571 } else if (mode == HWC_POWER_MODE_DOZE ||
3572 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003573 // Update display while dozing
3574 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003575 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3576 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003577 // FIXME: eventthread only knows about the main display right now
3578 mEventThread->onScreenAcquired();
3579 resyncToHardwareVsync(true);
3580 }
3581 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3582 // Leave display going to doze
3583 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3584 disableHardwareVsync(true); // also cancels any in-progress resync
3585 // FIXME: eventthread only knows about the main display right now
3586 mEventThread->onScreenReleased();
3587 }
3588 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003589 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003590 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003591 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003592 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003593}
3594
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003595void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3596 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003597 SurfaceFlinger& mFlinger;
3598 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003599 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003600 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003601 MessageSetPowerMode(SurfaceFlinger& flinger,
3602 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3603 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003604 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003605 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003606 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003607 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003608 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003609 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003610 ALOGW("Attempt to set power mode = %d for virtual display",
3611 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003612 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003613 mFlinger.setPowerModeInternal(
3614 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003615 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003616 return true;
3617 }
3618 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003619 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003620 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003621}
3622
3623// ---------------------------------------------------------------------------
3624
Lloyd Pique755e3192018-01-31 16:46:15 -08003625status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3626 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003628
Mathias Agopianbd115332013-04-18 16:41:04 -07003629 IPCThreadState* ipc = IPCThreadState::self();
3630 const int pid = ipc->getCallingPid();
3631 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003632
Mathias Agopianbd115332013-04-18 16:41:04 -07003633 if ((uid != AID_SHELL) &&
3634 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003635 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003636 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003638 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003639 // (this would indicate SF is stuck, but we want to be able to
3640 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003641 status_t err = mStateLock.timedLock(s2ns(1));
3642 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003643 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003644 result.appendFormat(
3645 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3646 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003647 }
3648
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003649 bool dumpAll = true;
3650 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003651 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003652
3653 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003654 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003655 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3656 dumpAll = false;
3657 }
3658
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003659 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003660 if ((index < numArgs) &&
3661 (args[index] == String16("--list"))) {
3662 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003663 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003664 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003665 }
3666
3667 if ((index < numArgs) &&
3668 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003669 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003670 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003671 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003673
3674 if ((index < numArgs) &&
3675 (args[index] == String16("--latency-clear"))) {
3676 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003677 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003678 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003679 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003680
3681 if ((index < numArgs) &&
3682 (args[index] == String16("--dispsync"))) {
3683 index++;
3684 mPrimaryDispSync.dump(result);
3685 dumpAll = false;
3686 }
Dan Stozab90cf072015-03-05 11:05:59 -08003687
3688 if ((index < numArgs) &&
3689 (args[index] == String16("--static-screen"))) {
3690 index++;
3691 dumpStaticScreenStats(result);
3692 dumpAll = false;
3693 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003694
3695 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003696 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003697 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003698 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003699 dumpAll = false;
3700 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003701
3702 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3703 index++;
3704 dumpWideColorInfo(result);
3705 dumpAll = false;
3706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003708
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003709 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003710 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003711 }
3712
Mathias Agopian9795c422009-08-26 16:36:26 -07003713 if (locked) {
3714 mStateLock.unlock();
3715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 }
3717 write(fd, result.string(), result.size());
3718 return NO_ERROR;
3719}
3720
Dan Stozac7014012014-02-14 15:03:43 -08003721void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3722 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003723{
Robert Carr2047fae2016-11-28 14:09:09 -08003724 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003725 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003726 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003727}
3728
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003729void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003730 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731{
3732 String8 name;
3733 if (index < args.size()) {
3734 name = String8(args[index]);
3735 index++;
3736 }
3737
David Sodman105b7dc2017-11-04 20:28:14 -07003738 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003739 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003740 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003741
3742 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003743 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003744 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003745 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003746 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003747 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003748 }
Robert Carr2047fae2016-11-28 14:09:09 -08003749 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003750 }
3751}
3752
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003753void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003754 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003755{
3756 String8 name;
3757 if (index < args.size()) {
3758 name = String8(args[index]);
3759 index++;
3760 }
3761
Robert Carr2047fae2016-11-28 14:09:09 -08003762 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003763 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003764 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003765 }
Robert Carr2047fae2016-11-28 14:09:09 -08003766 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003767
Svetoslavd85084b2014-03-20 10:28:31 -07003768 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003769}
3770
Jamie Gennis6547ff42013-07-16 20:12:42 -07003771// This should only be called from the main thread. Otherwise it would need
3772// the lock and should use mCurrentState rather than mDrawingState.
3773void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003774 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003775 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003776 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003777
3778 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3779}
3780
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003781void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003782{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003783 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003784
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003785 if (isLayerTripleBufferingDisabled())
3786 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003787
3788 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003789 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003790 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003791 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003792 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3793 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003794 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003795}
3796
Dan Stozab90cf072015-03-05 11:05:59 -08003797void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3798{
3799 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003800 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3801 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003802 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003803 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003804 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3805 b + 1, bucketTimeSec, percent);
3806 }
David Sodman4a36e932017-11-07 14:29:47 -08003807 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003808 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003809 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003810 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003811 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003812}
3813
Dan Stozae77c7662016-05-13 11:37:28 -07003814void SurfaceFlinger::recordBufferingStats(const char* layerName,
3815 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003816 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3817 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003818 for (const auto& segment : history) {
3819 if (!segment.usedThirdBuffer) {
3820 stats.twoBufferTime += segment.totalTime;
3821 }
3822 if (segment.occupancyAverage < 1.0f) {
3823 stats.doubleBufferedTime += segment.totalTime;
3824 } else if (segment.occupancyAverage < 2.0f) {
3825 stats.tripleBufferedTime += segment.totalTime;
3826 }
3827 ++stats.numSegments;
3828 stats.totalTime += segment.totalTime;
3829 }
3830}
3831
Brian Andersond6927fb2016-07-23 23:37:30 -07003832void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3833 result.appendFormat("Layer frame timestamps:\n");
3834
3835 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3836 const size_t count = currentLayers.size();
3837 for (size_t i=0 ; i<count ; i++) {
3838 currentLayers[i]->dumpFrameEvents(result);
3839 }
3840}
3841
Dan Stozae77c7662016-05-13 11:37:28 -07003842void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3843 result.append("Buffering stats:\n");
3844 result.append(" [Layer name] <Active time> <Two buffer> "
3845 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003846 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003847 typedef std::tuple<std::string, float, float, float> BufferTuple;
3848 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003849 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003850 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003851 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003852 if (stats.numSegments == 0) {
3853 continue;
3854 }
3855 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3856 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3857 stats.totalTime;
3858 float doubleBufferRatio = static_cast<float>(
3859 stats.doubleBufferedTime) / stats.totalTime;
3860 float tripleBufferRatio = static_cast<float>(
3861 stats.tripleBufferedTime) / stats.totalTime;
3862 sorted.insert({activeTime, {name, twoBufferRatio,
3863 doubleBufferRatio, tripleBufferRatio}});
3864 }
3865 for (const auto& sortedPair : sorted) {
3866 float activeTime = sortedPair.first;
3867 const BufferTuple& values = sortedPair.second;
3868 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3869 std::get<0>(values).c_str(), activeTime,
3870 std::get<1>(values), std::get<2>(values),
3871 std::get<3>(values));
3872 }
3873 result.append("\n");
3874}
3875
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003876void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3877 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003878 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003879
3880 // TODO: print out if wide-color mode is active or not
3881
3882 for (size_t d = 0; d < mDisplays.size(); d++) {
3883 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3884 int32_t hwcId = displayDevice->getHwcDisplayId();
3885 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3886 continue;
3887 }
3888
3889 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003890 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003891 for (auto&& mode : modes) {
3892 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3893 }
3894
Peiyong Lina52f0292018-03-14 17:26:31 -07003895 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003896 result.appendFormat(" Current color mode: %s (%d)\n",
3897 decodeColorMode(currentMode).c_str(), currentMode);
3898 }
3899 result.append("\n");
3900}
3901
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003902LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003903 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003904 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3905 const State& state = useDrawing ? mDrawingState : mCurrentState;
3906 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003907 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003908 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003909 });
3910
3911 return layersProto;
3912}
3913
Mathias Agopian74d211a2013-04-22 16:55:35 +02003914void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3915 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003916{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003917 bool colorize = false;
3918 if (index < args.size()
3919 && (args[index] == String16("--color"))) {
3920 colorize = true;
3921 index++;
3922 }
3923
3924 Colorizer colorizer(colorize);
3925
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926 // figure out if we're stuck somewhere
3927 const nsecs_t now = systemTime();
3928 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3929 const nsecs_t inTransaction(mDebugInTransaction);
3930 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3931 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3932
3933 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003934 * Dump library configuration.
3935 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003936
3937 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003938 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003939 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003940 appendSfConfigString(result);
3941 appendUiConfigString(result);
3942 appendGuiConfigString(result);
3943 result.append("\n");
3944
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003945 result.append("\nWide-Color information:\n");
3946 dumpWideColorInfo(result);
3947
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003948 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003949 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003950 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003951 result.append(SyncFeatures::getInstance().toString());
3952 result.append("\n");
3953
David Sodman105b7dc2017-11-04 20:28:14 -07003954 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003955
Andy McFadden41d67d72014-04-25 16:58:34 -07003956 colorizer.bold(result);
3957 result.append("DispSync configuration: ");
3958 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003959 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003960 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003961 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003962 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003963 result.append("\n");
3964
Dan Stozab90cf072015-03-05 11:05:59 -08003965 // Dump static screen stats
3966 result.append("\n");
3967 dumpStaticScreenStats(result);
3968 result.append("\n");
3969
Dan Stozae77c7662016-05-13 11:37:28 -07003970 dumpBufferingStats(result);
3971
Andy McFadden4803b742012-09-24 19:07:20 -07003972 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973 * Dump the visible layer list
3974 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003975 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003976 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07003977 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
3978 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003979 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003980
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003981 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003982 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07003983 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003984
3985 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003986 * Dump Display state
3987 */
3988
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003989 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003990 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003991 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003992 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3993 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003994 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003995 }
3996
3997 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003998 * Dump SurfaceFlinger global state
3999 */
4000
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004001 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004002 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004003 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004004
Mathias Agopian888c8222012-08-04 21:10:38 -07004005 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004006 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004007
David Sodmanbc815282017-11-05 18:57:52 -08004008 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004009
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004010 if (hw) {
4011 hw->undefinedRegion.dump(result, "undefinedRegion");
4012 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4013 hw->getOrientation(), hw->isDisplayOn());
4014 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004015 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004016 " last eglSwapBuffers() time: %f us\n"
4017 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004018 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004019 " refresh-rate : %f fps\n"
4020 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004021 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004022 " gpu_to_cpu_unsupported : %d\n"
4023 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004024 mLastSwapBufferTime/1000.0,
4025 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004026 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004027 1e9 / activeConfig->getVsyncPeriod(),
4028 activeConfig->getDpiX(),
4029 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004030 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004031
Mathias Agopian74d211a2013-04-22 16:55:35 +02004032 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004033 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004034
Mathias Agopian74d211a2013-04-22 16:55:35 +02004035 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004036 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037
4038 /*
4039 * VSYNC state
4040 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004041 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004042 result.append("\n");
4043
4044 /*
4045 * HWC layer minidump
4046 */
4047 for (size_t d = 0; d < mDisplays.size(); d++) {
4048 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4049 int32_t hwcId = displayDevice->getHwcDisplayId();
4050 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4051 continue;
4052 }
4053
4054 result.appendFormat("Display %d HWC layers:\n", hwcId);
4055 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004056 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004057 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004058 });
Dan Stozae22aec72016-08-01 13:20:59 -07004059 result.append("\n");
4060 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004061
4062 /*
4063 * Dump HWComposer state
4064 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004065 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004066 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004067 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004068 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004069 result.appendFormat(" h/w composer %s\n",
4070 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004071 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004072
4073 /*
4074 * Dump gralloc state
4075 */
4076 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4077 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004078
4079 /*
4080 * Dump VrFlinger state if in use.
4081 */
4082 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4083 result.append("VrFlinger state:\n");
4084 result.append(mVrFlinger->Dump().c_str());
4085 result.append("\n");
4086 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004087}
4088
Mathias Agopian13127d82013-03-05 17:47:11 -08004089const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004090SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004091 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004092 wp<IBinder> dpy;
4093 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4094 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4095 dpy = mDisplays.keyAt(i);
4096 break;
4097 }
4098 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004099 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004100 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4101 // Just use the primary display so we have something to return
4102 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4103 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004104 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004105}
4106
Keun young Park63f165f2012-08-31 10:53:36 -07004107bool SurfaceFlinger::startDdmConnection()
4108{
4109 void* libddmconnection_dso =
4110 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4111 if (!libddmconnection_dso) {
4112 return false;
4113 }
4114 void (*DdmConnection_start)(const char* name);
4115 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004116 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004117 if (!DdmConnection_start) {
4118 dlclose(libddmconnection_dso);
4119 return false;
4120 }
4121 (*DdmConnection_start)(getServiceName());
4122 return true;
4123}
4124
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004125status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 switch (code) {
4127 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004128 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004129 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004130 case CLEAR_ANIMATION_FRAME_STATS:
4131 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004132 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004133 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004134 case ENABLE_VSYNC_INJECTIONS:
4135 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 {
4137 // codes that require permission check
4138 IPCThreadState* ipc = IPCThreadState::self();
4139 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004140 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004141 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004142 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004143 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004144 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004145 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004146 break;
4147 }
Robert Carr1db73f62016-12-21 12:58:51 -08004148 /*
4149 * Calling setTransactionState is safe, because you need to have been
4150 * granted a reference to Client* and Handle* to do anything with it.
4151 *
4152 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4153 */
4154 case SET_TRANSACTION_STATE:
4155 case CREATE_SCOPED_CONNECTION:
4156 {
4157 return OK;
4158 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004159 case CAPTURE_SCREEN:
4160 {
4161 // codes that require permission check
4162 IPCThreadState* ipc = IPCThreadState::self();
4163 const int pid = ipc->getCallingPid();
4164 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004165 if ((uid != AID_GRAPHICS) &&
4166 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004167 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004168 return PERMISSION_DENIED;
4169 }
4170 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004171 }
chaviwa76b2712017-09-20 12:02:26 -07004172 case CAPTURE_LAYERS: {
4173 IPCThreadState* ipc = IPCThreadState::self();
4174 const int pid = ipc->getCallingPid();
4175 const int uid = ipc->getCallingUid();
4176 if ((uid != AID_GRAPHICS) &&
4177 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4178 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4179 return PERMISSION_DENIED;
4180 }
4181 break;
4182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004184 return OK;
4185}
4186
4187status_t SurfaceFlinger::onTransact(
4188 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4189{
4190 status_t credentialCheck = CheckTransactCodeCredentials(code);
4191 if (credentialCheck != OK) {
4192 return credentialCheck;
4193 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4196 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004197 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004198 IPCThreadState* ipc = IPCThreadState::self();
4199 const int uid = ipc->getCallingUid();
4200 if (CC_UNLIKELY(uid != AID_SYSTEM
4201 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004202 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004203 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004204 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205 return PERMISSION_DENIED;
4206 }
4207 int n;
4208 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004209 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004210 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004211 return NO_ERROR;
4212 case 1002: // SHOW_UPDATES
4213 n = data.readInt32();
4214 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004215 invalidateHwcGeometry();
4216 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004217 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004218 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004219 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004220 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004221 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004222 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004223 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004224 setTransactionFlags(
4225 eTransactionNeeded|
4226 eDisplayTransactionNeeded|
4227 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004228 return NO_ERROR;
4229 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004230 case 1006:{ // send empty update
4231 signalRefresh();
4232 return NO_ERROR;
4233 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004234 case 1008: // toggle use of hw composer
4235 n = data.readInt32();
4236 mDebugDisableHWC = n ? 1 : 0;
4237 invalidateHwcGeometry();
4238 repaintEverything();
4239 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004240 case 1009: // toggle use of transform hint
4241 n = data.readInt32();
4242 mDebugDisableTransformHint = n ? 1 : 0;
4243 invalidateHwcGeometry();
4244 repaintEverything();
4245 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004247 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004248 reply->writeInt32(0);
4249 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004250 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004251 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004252 return NO_ERROR;
4253 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004254 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004255 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004256 return NO_ERROR;
4257 }
4258 case 1014: {
4259 // daltonize
4260 n = data.readInt32();
4261 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004262 case 1:
4263 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4264 break;
4265 case 2:
4266 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4267 break;
4268 case 3:
4269 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4270 break;
4271 default:
4272 mDaltonizer.setType(ColorBlindnessType::None);
4273 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004274 }
4275 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004276 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004277 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004278 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004279 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004280 invalidateHwcGeometry();
4281 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004282 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004284 case 1015: {
4285 // apply a color matrix
4286 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004287 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004288 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004289 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004290 for (size_t j = 0; j < 4; j++) {
4291 mColorMatrix[i][j] = data.readFloat();
4292 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004293 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004294 } else {
4295 mColorMatrix = mat4();
4296 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004297
4298 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4299 // the division by w in the fragment shader
4300 float4 lastRow(transpose(mColorMatrix)[3]);
4301 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4302 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4303 }
4304
Alan Viverette9c5a3332013-09-12 20:04:35 -07004305 invalidateHwcGeometry();
4306 repaintEverything();
4307 return NO_ERROR;
4308 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004309 // This is an experimental interface
4310 // Needs to be shifted to proper binder interface when we productize
4311 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004312 n = data.readInt32();
4313 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004314 return NO_ERROR;
4315 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004316 case 1017: {
4317 n = data.readInt32();
4318 mForceFullDamage = static_cast<bool>(n);
4319 return NO_ERROR;
4320 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004321 case 1018: { // Modify Choreographer's phase offset
4322 n = data.readInt32();
4323 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4324 return NO_ERROR;
4325 }
4326 case 1019: { // Modify SurfaceFlinger's phase offset
4327 n = data.readInt32();
4328 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4329 return NO_ERROR;
4330 }
Irvel468051e2016-06-13 16:44:44 -07004331 case 1020: { // Layer updates interceptor
4332 n = data.readInt32();
4333 if (n) {
4334 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004335 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004336 }
4337 else{
4338 ALOGV("Interceptor disabled");
4339 mInterceptor.disable();
4340 }
4341 return NO_ERROR;
4342 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004343 case 1021: { // Disable HWC virtual displays
4344 n = data.readInt32();
4345 mUseHwcVirtualDisplays = !n;
4346 return NO_ERROR;
4347 }
Romain Guy0147a172017-06-01 13:53:56 -07004348 case 1022: { // Set saturation boost
4349 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4350
4351 invalidateHwcGeometry();
4352 repaintEverything();
4353 return NO_ERROR;
4354 }
Romain Guy54f154a2017-10-24 21:40:32 +01004355 case 1023: { // Set native mode
4356 mForceNativeColorMode = data.readInt32() == 1;
4357
4358 invalidateHwcGeometry();
4359 repaintEverything();
4360 return NO_ERROR;
4361 }
4362 case 1024: { // Is wide color gamut rendering/color management supported?
4363 reply->writeBool(hasWideColorDisplay);
4364 return NO_ERROR;
4365 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004366 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004367 n = data.readInt32();
4368 if (n) {
4369 ALOGV("LayerTracing enabled");
4370 mTracing.enable();
4371 doTracing("tracing.enable");
4372 reply->writeInt32(NO_ERROR);
4373 } else {
4374 ALOGV("LayerTracing disabled");
4375 status_t err = mTracing.disable();
4376 reply->writeInt32(err);
4377 }
4378 return NO_ERROR;
4379 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004380 case 1026: { // Get layer tracing status
4381 reply->writeBool(mTracing.isEnabled());
4382 return NO_ERROR;
4383 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004384 }
4385 }
4386 return err;
4387}
4388
Steven Thomas6d8110b2017-08-31 18:24:21 -07004389void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004390 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004391 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004392}
4393
Steven Thomas6d8110b2017-08-31 18:24:21 -07004394void SurfaceFlinger::repaintEverything() {
4395 ConditionalLock _l(mStateLock,
4396 std::this_thread::get_id() != mMainThreadId);
4397 repaintEverythingLocked();
4398}
4399
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004400// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4401class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004402public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004403 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4404 ~WindowDisconnector() {
4405 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004406 }
4407
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004408private:
4409 ANativeWindow* mWindow;
4410 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004411};
4412
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004413status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4414 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4415 int32_t minLayerZ, int32_t maxLayerZ,
4416 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004417 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004418 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004419
chaviwa76b2712017-09-20 12:02:26 -07004420 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4421
4422 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004423 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4424
chaviwa76b2712017-09-20 12:02:26 -07004425 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4426
4427 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4428 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004429 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004430}
4431
4432status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004433 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004434 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004435 ATRACE_CALL();
4436
4437 class LayerRenderArea : public RenderArea {
4438 public:
Robert Carr578038f2018-03-09 12:25:24 -08004439 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4440 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4441 : RenderArea(reqHeight, reqWidth),
4442 mLayer(layer),
4443 mCrop(crop),
4444 mFlinger(flinger),
4445 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004446 Rect getBounds() const override {
4447 const Layer::State& layerState(mLayer->getDrawingState());
4448 return Rect(layerState.active.w, layerState.active.h);
4449 }
4450 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4451 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4452 bool isSecure() const override { return false; }
4453 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004454 const Transform& getTransform() const { return mTransform; }
4455
4456 class ReparentForDrawing {
4457 public:
4458 const sp<Layer>& oldParent;
4459 const sp<Layer>& newParent;
4460
4461 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4462 : oldParent(oldParent), newParent(newParent) {
4463 oldParent->reparentChildrenForDrawing(newParent);
4464 }
4465 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4466 };
4467
4468 void render(std::function<void()> drawLayers) override {
4469 if (!mChildrenOnly) {
4470 mTransform = mLayer->getTransform().inverse();
4471 drawLayers();
4472 } else {
4473 Rect bounds = getBounds();
4474 screenshotParentLayer =
4475 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4476 bounds.getWidth(), bounds.getHeight(), 0);
4477
4478 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4479 drawLayers();
4480 }
4481 }
chaviwa76b2712017-09-20 12:02:26 -07004482
chaviw7206d492017-11-10 16:16:12 -08004483 Rect getSourceCrop() const override {
4484 if (mCrop.isEmpty()) {
4485 return getBounds();
4486 } else {
4487 return mCrop;
4488 }
4489 }
chaviwa76b2712017-09-20 12:02:26 -07004490 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004491 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004492
4493 private:
chaviw7206d492017-11-10 16:16:12 -08004494 const sp<Layer> mLayer;
4495 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004496
4497 // In the "childrenOnly" case we reparent the children to a screenshot
4498 // layer which has no properties set and which does not draw.
4499 sp<ContainerLayer> screenshotParentLayer;
4500 Transform mTransform;
4501
4502 SurfaceFlinger* mFlinger;
4503 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004504 };
4505
4506 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4507 auto parent = layerHandle->owner.promote();
4508
chaviw7206d492017-11-10 16:16:12 -08004509 if (parent == nullptr || parent->isPendingRemoval()) {
4510 ALOGE("captureLayers called with a removed parent");
4511 return NAME_NOT_FOUND;
4512 }
4513
Robert Carr578038f2018-03-09 12:25:24 -08004514 const int uid = IPCThreadState::self()->getCallingUid();
4515 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4516 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4517 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4518 return PERMISSION_DENIED;
4519 }
4520
chaviw7206d492017-11-10 16:16:12 -08004521 Rect crop(sourceCrop);
4522 if (sourceCrop.width() <= 0) {
4523 crop.left = 0;
4524 crop.right = parent->getCurrentState().active.w;
4525 }
4526
4527 if (sourceCrop.height() <= 0) {
4528 crop.top = 0;
4529 crop.bottom = parent->getCurrentState().active.h;
4530 }
4531
4532 int32_t reqWidth = crop.width() * frameScale;
4533 int32_t reqHeight = crop.height() * frameScale;
4534
Robert Carr578038f2018-03-09 12:25:24 -08004535 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004536
Robert Carr578038f2018-03-09 12:25:24 -08004537 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004538 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4539 if (!layer->isVisible()) {
4540 return;
Robert Carr578038f2018-03-09 12:25:24 -08004541 } else if (childrenOnly && layer == parent.get()) {
4542 return;
chaviwa76b2712017-09-20 12:02:26 -07004543 }
4544 visitor(layer);
4545 });
4546 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004547 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004548}
4549
4550status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4551 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004552 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004553 bool useIdentityTransform) {
4554 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004555
chaviwa76b2712017-09-20 12:02:26 -07004556 renderArea.updateDimensions();
4557
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004558 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4559 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4560 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4561 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004562
4563 // This mutex protects syncFd and captureResult for communication of the return values from the
4564 // main thread back to this Binder thread
4565 std::mutex captureMutex;
4566 std::condition_variable captureCondition;
4567 std::unique_lock<std::mutex> captureLock(captureMutex);
4568 int syncFd = -1;
4569 std::optional<status_t> captureResult;
4570
Robert Carr03480e22018-01-04 16:02:06 -08004571 const int uid = IPCThreadState::self()->getCallingUid();
4572 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4573
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004574 sp<LambdaMessage> message = new LambdaMessage([&]() {
4575 // If there is a refresh pending, bug out early and tell the binder thread to try again
4576 // after the refresh.
4577 if (mRefreshPending) {
4578 ATRACE_NAME("Skipping screenshot for now");
4579 std::unique_lock<std::mutex> captureLock(captureMutex);
4580 captureResult = std::make_optional<status_t>(EAGAIN);
4581 captureCondition.notify_one();
4582 return;
4583 }
4584
4585 status_t result = NO_ERROR;
4586 int fd = -1;
4587 {
4588 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004589 renderArea.render([&]() {
4590 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4591 useIdentityTransform, forSystem, &fd);
4592 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004593 }
4594
4595 {
4596 std::unique_lock<std::mutex> captureLock(captureMutex);
4597 syncFd = fd;
4598 captureResult = std::make_optional<status_t>(result);
4599 captureCondition.notify_one();
4600 }
4601 });
4602
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004603 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004604 if (result == NO_ERROR) {
4605 captureCondition.wait(captureLock, [&]() { return captureResult; });
4606 while (*captureResult == EAGAIN) {
4607 captureResult.reset();
4608 result = postMessageAsync(message);
4609 if (result != NO_ERROR) {
4610 return result;
4611 }
4612 captureCondition.wait(captureLock, [&]() { return captureResult; });
4613 }
4614 result = *captureResult;
4615 }
4616
4617 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004618 sync_wait(syncFd, -1);
4619 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004620 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004621
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004622 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004623}
4624
chaviwa76b2712017-09-20 12:02:26 -07004625void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4626 TraverseLayersFunction traverseLayers, bool yswap,
4627 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004628 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004629
Lloyd Pique144e1162017-12-20 16:44:52 -08004630 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004631
4632 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004633 const auto raWidth = renderArea.getWidth();
4634 const auto raHeight = renderArea.getHeight();
4635
4636 const auto reqWidth = renderArea.getReqWidth();
4637 const auto reqHeight = renderArea.getReqHeight();
4638 Rect sourceCrop = renderArea.getSourceCrop();
4639
4640 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4641 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004642
Dan Stozac1879002014-05-22 15:59:05 -07004643 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004644 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004645 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004646 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004647 }
4648
4649 // ensure that sourceCrop is inside screen
4650 if (sourceCrop.left < 0) {
4651 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4652 }
chaviwa76b2712017-09-20 12:02:26 -07004653 if (sourceCrop.right > raWidth) {
4654 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004655 }
4656 if (sourceCrop.top < 0) {
4657 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4658 }
chaviwa76b2712017-09-20 12:02:26 -07004659 if (sourceCrop.bottom > raHeight) {
4660 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004661 }
4662
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004663 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004664 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004665 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004666 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4667 }
4668 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004669
Mathias Agopian180f10d2013-04-10 22:55:41 -07004670 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004671 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004672
4673 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004674 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4675 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004676 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004677
4678 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004679 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004680
chaviwa76b2712017-09-20 12:02:26 -07004681 traverseLayers([&](Layer* layer) {
4682 if (filtering) layer->setFiltering(true);
4683 layer->draw(renderArea, useIdentityTransform);
4684 if (filtering) layer->setFiltering(false);
4685 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004686}
4687
chaviwa76b2712017-09-20 12:02:26 -07004688status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4689 TraverseLayersFunction traverseLayers,
4690 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004691 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004692 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004693 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004694 ATRACE_CALL();
4695
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004696 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004697
4698 traverseLayers([&](Layer* layer) {
4699 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4700 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004701
Robert Carr03480e22018-01-04 16:02:06 -08004702 // We allow the system server to take screenshots of secure layers for
4703 // use in situations like the Screen-rotation animation and place
4704 // the impetus on WindowManager to not persist them.
4705 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004706 ALOGW("FB is protected: PERMISSION_DENIED");
4707 return PERMISSION_DENIED;
4708 }
4709
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004710 // this binds the given EGLImage as a framebuffer for the
4711 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004712 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004713 if (bufferBond.getStatus() != NO_ERROR) {
4714 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004715 return INVALID_OPERATION;
4716 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004717
Dan Stozaabcda352017-06-01 14:37:39 -07004718 // this will in fact render into our dequeued buffer
4719 // via an FBO, which means we didn't have to create
4720 // an EGLSurface and therefore we're not
4721 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004722 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004723
Dan Stozaabcda352017-06-01 14:37:39 -07004724 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004725 getRenderEngine().finish();
4726 *outSyncFd = -1;
4727
chaviwa76b2712017-09-20 12:02:26 -07004728 const auto reqWidth = renderArea.getReqWidth();
4729 const auto reqHeight = renderArea.getReqHeight();
4730
Dan Stozaabcda352017-06-01 14:37:39 -07004731 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4732 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004733 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004734 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004735 } else {
4736 base::unique_fd syncFd = getRenderEngine().flush();
4737 if (syncFd < 0) {
4738 getRenderEngine().finish();
4739 }
4740 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004741 }
4742
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004743 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004744}
4745
Mathias Agopiand5556842013-09-19 17:08:37 -07004746void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004747 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004748 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004749 for (size_t y = 0; y < h; y++) {
4750 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4751 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004752 if (p[x] != 0xFF000000) return;
4753 }
4754 }
chaviwa76b2712017-09-20 12:02:26 -07004755 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004756
Robert Carr2047fae2016-11-28 14:09:09 -08004757 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004758 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004759 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004760 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4761 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4762 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4763 static_cast<float>(state.color.a));
4764 i++;
4765 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004766 }
4767}
4768
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004769// ---------------------------------------------------------------------------
4770
Dan Stoza412903f2017-04-27 13:42:17 -07004771void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4772 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004773}
4774
Dan Stoza412903f2017-04-27 13:42:17 -07004775void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4776 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004777}
4778
chaviwa76b2712017-09-20 12:02:26 -07004779void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4780 int32_t maxLayerZ,
4781 const LayerVector::Visitor& visitor) {
4782 // We loop through the first level of layers without traversing,
4783 // as we need to interpret min/max layer Z in the top level Z space.
4784 for (const auto& layer : mDrawingState.layersSortedByZ) {
4785 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4786 continue;
4787 }
4788 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004789 // relative layers are traversed in Layer::traverseInZOrder
4790 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004791 continue;
4792 }
4793 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004794 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4795 return;
4796 }
chaviwa76b2712017-09-20 12:02:26 -07004797 if (!layer->isVisible()) {
4798 return;
4799 }
4800 visitor(layer);
4801 });
4802 }
4803}
4804
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004805}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004806
4807
4808#if defined(__gl_h_)
4809#error "don't include gl/gl.h in this file"
4810#endif
4811
4812#if defined(__gl2_h_)
4813#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004814#endif