blob: 7ae5b219a1292edda8279d049697f362978dcfc5 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
David Sodmanbc815282017-11-05 18:57:52 -0800157SurfaceFlingerBE::SurfaceFlingerBE()
158 : mHwcServiceName(getHwcServiceName()),
159 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800160 mFrameBuckets(),
161 mTotalTime(0),
162 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800163 mComposerSequenceId(0) {
164}
165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166SurfaceFlinger::SurfaceFlinger()
Lloyd Pique12eb4232018-01-17 11:54:43 -0800167 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700169 mTransactionPending(false),
170 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700172 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700173 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800175 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800177 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800178 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700181 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700182 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700183 mDebugInSwapBuffers(0),
184 mLastSwapBufferTime(0),
185 mDebugInTransaction(0),
186 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700187 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700188 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800189 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700191 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700192 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700193 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800194 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800195 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700196 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800197 mMainThreadId(std::this_thread::get_id()),
198 mCreateBufferQueue(&BufferQueue::createBufferQueue) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800200
201 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
203
204 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
206
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800207 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
David Sodman99974d22017-11-28 12:04:33 -0800229 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285}
286
Dan Stozac7014012014-02-14 15:03:43 -0800287void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800288{
289 // the window manager died on us. prepare its eulogy.
290
Andy McFadden13a082e2012-08-24 10:16:42 -0700291 // restore initial conditions (default device unblank, etc)
292 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800293
294 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700295 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296}
297
Robert Carr1db73f62016-12-21 12:58:51 -0800298static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700299 status_t err = client->initCheck();
300 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800301 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800302 }
Robert Carr1db73f62016-12-21 12:58:51 -0800303 return nullptr;
304}
305
306sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
307 return initClient(new Client(this));
308}
309
310sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
311 const sp<IGraphicBufferProducer>& gbp) {
312 if (authenticateSurfaceTexture(gbp) == false) {
313 return nullptr;
314 }
315 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
316 if (layer == nullptr) {
317 return nullptr;
318 }
319
320 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700323sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
324 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700325{
326 class DisplayToken : public BBinder {
327 sp<SurfaceFlinger> flinger;
328 virtual ~DisplayToken() {
329 // no more references, this display must be terminated
330 Mutex::Autolock _l(flinger->mStateLock);
331 flinger->mCurrentState.displays.removeItem(this);
332 flinger->setTransactionFlags(eDisplayTransactionNeeded);
333 }
334 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700335 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 : flinger(flinger) {
337 }
338 };
339
340 sp<BBinder> token = new DisplayToken(this);
341
342 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700343 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700344 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700346 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700347 return token;
348}
349
Jesse Hall6c913be2013-08-08 12:15:49 -0700350void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
351 Mutex::Autolock _l(mStateLock);
352
353 ssize_t idx = mCurrentState.displays.indexOfKey(display);
354 if (idx < 0) {
355 ALOGW("destroyDisplay: invalid display token");
356 return;
357 }
358
359 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
360 if (!info.isVirtualDisplay()) {
361 ALOGE("destroyDisplay called for non-virtual display");
362 return;
363 }
Irvelffc9efc2016-07-27 15:16:37 -0700364 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700365 mCurrentState.displays.removeItemsAt(idx);
366 setTransactionFlags(eDisplayTransactionNeeded);
367}
368
Mathias Agopiane57f2922012-08-09 16:29:12 -0700369sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700370 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700371 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800372 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700373 }
Jesse Hall692c7232012-11-08 15:41:56 -0800374 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700375}
376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377void SurfaceFlinger::bootFinished()
378{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700379 if (mStartPropertySetThread->join() != NO_ERROR) {
380 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 const nsecs_t now = systemTime();
383 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000384 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700385
386 // wait patiently for the window manager death
387 const String16 name("window");
388 sp<IBinder> window(defaultServiceManager()->getService(name));
389 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700391 }
392
Steven Thomas050b2c82017-03-06 11:45:16 -0800393 if (mVrFlinger) {
394 mVrFlinger->OnBootFinished();
395 }
396
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700397 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 // formerly we would just kill the process, but we now ask it to exit so it
399 // can choose where to stop the animation.
400 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700401
402 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
403 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
404 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700405
Thierry Strudel2924d012017-08-14 15:19:37 -0700406 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700407 readPersistentProperties();
408 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700409 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410}
411
Mathias Agopian3f844832013-08-07 21:24:32 -0700412void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700413 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800414 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700415 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700416 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800417 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
418 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700419 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 return true;
422 }
423 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425}
426
Lloyd Piquee83f9312018-02-01 12:53:17 -0800427class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* name) :
431 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
435 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 mDispSync(dispSync),
437 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mVsyncMutex(),
439 mPhaseOffset(phaseOffset),
440 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700441
Lloyd Piquee83f9312018-02-01 12:53:17 -0800442 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443
Lloyd Piquee83f9312018-02-01 12:53:17 -0800444 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 static_cast<DispSync::Callback*>(this));
449 if (err != NO_ERROR) {
450 ALOGE("error registering vsync callback: %s (%d)",
451 strerror(-err), err);
452 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700453 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 } else {
455 status_t err = mDispSync->removeEventListener(
456 static_cast<DispSync::Callback*>(this));
457 if (err != NO_ERROR) {
458 ALOGE("error unregistering vsync callback: %s (%d)",
459 strerror(-err), err);
460 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700461 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 }
465
Lloyd Piquee83f9312018-02-01 12:53:17 -0800466 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 mCallback = callback;
469 }
470
Lloyd Piquee83f9312018-02-01 12:53:17 -0800471 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 Mutex::Autolock lock(mVsyncMutex);
473
474 // Normalize phaseOffset to [0, period)
475 auto period = mDispSync->getPeriod();
476 phaseOffset %= period;
477 if (phaseOffset < 0) {
478 // If we're here, then phaseOffset is in (-period, 0). After this
479 // operation, it will be in (0, period)
480 phaseOffset += period;
481 }
482 mPhaseOffset = phaseOffset;
483
484 // If we're not enabled, we don't need to mess with the listeners
485 if (!mEnabled) {
486 return;
487 }
488
489 // Remove the listener with the old offset
490 status_t err = mDispSync->removeEventListener(
491 static_cast<DispSync::Callback*>(this));
492 if (err != NO_ERROR) {
493 ALOGE("error unregistering vsync callback: %s (%d)",
494 strerror(-err), err);
495 }
496
497 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499 static_cast<DispSync::Callback*>(this));
500 if (err != NO_ERROR) {
501 ALOGE("error registering vsync callback: %s (%d)",
502 strerror(-err), err);
503 }
504 }
505
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506private:
507 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700510 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 callback = mCallback;
512
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 if (mTraceVsync) {
514 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700515 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700516 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 }
518
Peiyong Lin566a3b42018-01-09 18:22:43 -0800519 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 callback->onVSyncEvent(when);
521 }
522 }
523
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 const char* const mName;
525
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 int mValue;
527
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 const String8 mVsyncOnLabel;
530 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533
534 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800535 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536
537 Mutex mVsyncMutex; // Protects the following
538 nsecs_t mPhaseOffset;
539 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540};
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700543public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800544 InjectVSyncSource() = default;
545 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700546
Lloyd Piquee83f9312018-02-01 12:53:17 -0800547 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700548 std::lock_guard<std::mutex> lock(mCallbackMutex);
549 mCallback = callback;
550 }
551
Lloyd Piquee83f9312018-02-01 12:53:17 -0800552 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700553 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700554 if (mCallback) {
555 mCallback->onVSyncEvent(when);
556 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setVSyncEnabled(bool) override {}
560 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700561
562private:
563 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800564 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700565};
566
Wei Wangf9b05ee2017-07-19 20:59:39 -0700567// Do not call property_set on main thread which will be blocked by init
568// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700570 ALOGI( "SurfaceFlinger's main thread ready to run. "
571 "Initializing graphics H/W...");
572
Thierry Strudel2924d012017-08-14 15:19:37 -0700573 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900574
Steven Thomasb02664d2017-07-26 18:48:28 -0700575 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800578 mEventThreadSource =
579 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
580 true, "app");
581 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
582 "appEventThread");
583 mSfEventThreadSource =
584 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
585 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
586 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
587 "sfEventThread");
Lloyd Piquee83f9312018-02-01 12:53:17 -0800588 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800591 getBE().mRenderEngine =
592 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
593 hasWideColorDisplay
594 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
595 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800596 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700597
598 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
599 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800600 getBE().mHwc.reset(
601 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700602 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800603 // Process any initial hotplug and resulting display changes.
604 processDisplayHotplugEventsLocked();
605 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
606 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800607
Lloyd Piquefcd86612017-12-14 17:15:36 -0800608 // make the default display GLContext current so that we can create textures
609 // when creating Layers (which may happens before we render something)
610 getDefaultDisplayDeviceLocked()->makeCurrent();
611
Steven Thomas050b2c82017-03-06 11:45:16 -0800612 if (useVrFlinger) {
613 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700614 // This callback is called from the vr flinger dispatch thread. We
615 // need to call signalTransaction(), which requires holding
616 // mStateLock when we're not on the main thread. Acquiring
617 // mStateLock from the vr flinger dispatch thread might trigger a
618 // deadlock in surface flinger (see b/66916578), so post a message
619 // to be handled on the main thread instead.
620 sp<LambdaMessage> message = new LambdaMessage([=]() {
621 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
622 mVrFlingerRequestsDisplay = requestDisplay;
623 signalTransaction();
624 });
625 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 };
David Sodman105b7dc2017-11-04 20:28:14 -0700627 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
628 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800629 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 if (!mVrFlinger) {
631 ALOGE("Failed to start vrflinger");
632 }
633 }
634
Lloyd Pique755e3192018-01-31 16:46:15 -0800635 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
636 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
637 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700638
Mathias Agopian92a979a2012-08-02 18:32:23 -0700639 // initialize our drawing state
640 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700641
Andy McFadden13a082e2012-08-24 10:16:42 -0700642 // set initial conditions (e.g. unblank default device)
643 initializeDisplays();
644
David Sodmanbc815282017-11-05 18:57:52 -0800645 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700646
Wei Wangf9b05ee2017-07-19 20:59:39 -0700647 // Inform native graphics APIs whether the present timestamp is supported:
648 if (getHwComposer().hasCapability(
649 HWC2::Capability::PresentFenceIsNotReliable)) {
650 mStartPropertySetThread = new StartPropertySetThread(false);
651 } else {
652 mStartPropertySetThread = new StartPropertySetThread(true);
653 }
654
655 if (mStartPropertySetThread->Start() != NO_ERROR) {
656 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800658
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700660}
661
Romain Guy11d63f42017-07-20 12:47:14 -0700662void SurfaceFlinger::readPersistentProperties() {
663 char value[PROPERTY_VALUE_MAX];
664
665 property_get("persist.sys.sf.color_saturation", value, "1.0");
666 mSaturation = atof(value);
667 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100668
669 property_get("persist.sys.sf.native_mode", value, "0");
670 mForceNativeColorMode = atoi(value) == 1;
671 if (mForceNativeColorMode) {
672 ALOGV("Forcing native color mode");
673 }
Romain Guy11d63f42017-07-20 12:47:14 -0700674}
675
Mathias Agopiana67e4182012-06-19 17:26:12 -0700676void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800677 // Start boot animation service by setting a property mailbox
678 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 if (mStartPropertySetThread->join() != NO_ERROR) {
682 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800683 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700684}
685
Mathias Agopian875d8e12013-06-07 15:35:48 -0700686size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800687 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700688}
689
Mathias Agopian875d8e12013-06-07 15:35:48 -0700690size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800691 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700692}
693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800694// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800695
Jamie Gennis582270d2011-08-17 18:19:00 -0700696bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800697 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800698 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800699 return authenticateSurfaceTextureLocked(bufferProducer);
700}
701
702bool SurfaceFlinger::authenticateSurfaceTextureLocked(
703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800704 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800705 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800706}
707
Brian Anderson6b376712017-04-04 10:51:39 -0700708status_t SurfaceFlinger::getSupportedFrameTimestamps(
709 std::vector<FrameEvent>* outSupported) const {
710 *outSupported = {
711 FrameEvent::REQUESTED_PRESENT,
712 FrameEvent::ACQUIRE,
713 FrameEvent::LATCH,
714 FrameEvent::FIRST_REFRESH_START,
715 FrameEvent::LAST_REFRESH_START,
716 FrameEvent::GPU_COMPOSITION_DONE,
717 FrameEvent::DEQUEUE_READY,
718 FrameEvent::RELEASE,
719 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700720 ConditionalLock _l(mStateLock,
721 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700722 if (!getHwComposer().hasCapability(
723 HWC2::Capability::PresentFenceIsNotReliable)) {
724 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
725 }
726 return NO_ERROR;
727}
728
Dan Stoza7f7da322014-05-02 15:26:25 -0700729status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
730 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800731 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700732 return BAD_VALUE;
733 }
734
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500735 if (!display.get())
736 return NAME_NOT_FOUND;
737
Jesse Hall692c7232012-11-08 15:41:56 -0800738 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700739 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800740 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700741 type = i;
742 break;
743 }
744 }
745
746 if (type < 0) {
747 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700748 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700749
Mathias Agopian8b736f12012-08-13 17:54:26 -0700750 // TODO: Not sure if display density should handled by SF any longer
751 class Density {
752 static int getDensityFromProperty(char const* propName) {
753 char property[PROPERTY_VALUE_MAX];
754 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800755 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 density = atoi(property);
757 }
758 return density;
759 }
760 public:
761 static int getEmuDensity() {
762 return getDensityFromProperty("qemu.sf.lcd_density"); }
763 static int getBuildDensity() {
764 return getDensityFromProperty("ro.sf.lcd_density"); }
765 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700766
Dan Stoza7f7da322014-05-02 15:26:25 -0700767 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700768
Steven Thomas6d8110b2017-08-31 18:24:21 -0700769 ConditionalLock _l(mStateLock,
770 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800771 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700772 DisplayInfo info = DisplayInfo();
773
Dan Stoza9e56aa02015-11-02 13:00:03 -0800774 float xdpi = hwConfig->getDpiX();
775 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700776
777 if (type == DisplayDevice::DISPLAY_PRIMARY) {
778 // The density of the device is provided by a build property
779 float density = Density::getBuildDensity() / 160.0f;
780 if (density == 0) {
781 // the build doesn't provide a density -- this is wrong!
782 // use xdpi instead
783 ALOGE("ro.sf.lcd_density must be defined as a build property");
784 density = xdpi / 160.0f;
785 }
786 if (Density::getEmuDensity()) {
787 // if "qemu.sf.lcd_density" is specified, it overrides everything
788 xdpi = ydpi = density = Density::getEmuDensity();
789 density /= 160.0f;
790 }
791 info.density = density;
792
793 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700794 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800795 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 } else {
797 // TODO: where should this value come from?
798 static const int TV_DENSITY = 213;
799 info.density = TV_DENSITY / 160.0f;
800 info.orientation = 0;
801 }
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 info.w = hwConfig->getWidth();
804 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 info.xdpi = xdpi;
806 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900808 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809
Andy McFadden91b2ca82014-06-13 14:04:23 -0700810 // This is how far in advance a buffer must be queued for
811 // presentation at a given time. If you want a buffer to appear
812 // on the screen at time N, you must submit the buffer before
813 // (N - presentationDeadline).
814 //
815 // Normally it's one full refresh period (to give SF a chance to
816 // latch the buffer), but this can be reduced by configuring a
817 // DispSync offset. Any additional delays introduced by the hardware
818 // composer or panel must be accounted for here.
819 //
820 // We add an additional 1ms to allow for processing time and
821 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800823 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700824
825 // All non-virtual displays are currently considered secure.
826 info.secure = true;
827
Michael Wright28f24d02016-07-12 13:30:53 -0700828 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 }
830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 return NO_ERROR;
832}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700833
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800834status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700835 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800836 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700837 return BAD_VALUE;
838 }
839
840 // FIXME for now we always return stats for the primary display
841 memset(stats, 0, sizeof(*stats));
842 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
843 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
844 return NO_ERROR;
845}
846
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700847int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800848 if (display == nullptr) {
849 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800850 return BAD_VALUE;
851 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700852
853 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800854 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700855 return device->getActiveConfig();
856 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700857
Dan Stoza24a42e92015-03-09 10:04:11 -0700858 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700859}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700860
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700861void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
862 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
863 this);
864 int32_t type = hw->getDisplayType();
865 int currentMode = hw->getActiveConfig();
866
867 if (mode == currentMode) {
868 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
869 return;
870 }
871
872 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
873 ALOGW("Trying to set config for virtual display");
874 return;
875 }
876
877 hw->setActiveConfig(mode);
878 getHwComposer().setActiveConfig(type, mode);
879}
880
881status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
882 class MessageSetActiveConfig: public MessageBase {
883 SurfaceFlinger& mFlinger;
884 sp<IBinder> mDisplay;
885 int mMode;
886 public:
887 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
888 int mode) :
889 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
890 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700891 Vector<DisplayInfo> configs;
892 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700893 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700894 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700895 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700896 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700897 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700898 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800899 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700900 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700902 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
903 ALOGW("Attempt to set active config = %d for virtual display",
904 mMode);
905 } else {
906 mFlinger.setActiveConfigInternal(hw, mMode);
907 }
908 return true;
909 }
910 };
911 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
912 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700913 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700914}
Michael Wright28f24d02016-07-12 13:30:53 -0700915status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700916 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700917 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
918 return BAD_VALUE;
919 }
920
921 if (!display.get()) {
922 return NAME_NOT_FOUND;
923 }
924
925 int32_t type = NAME_NOT_FOUND;
926 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
927 if (display == mBuiltinDisplays[i]) {
928 type = i;
929 break;
930 }
931 }
932
933 if (type < 0) {
934 return type;
935 }
936
Peiyong Lina52f0292018-03-14 17:26:31 -0700937 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700938 {
939 ConditionalLock _l(mStateLock,
940 std::this_thread::get_id() != mMainThreadId);
941 modes = getHwComposer().getColorModes(type);
942 }
Michael Wright28f24d02016-07-12 13:30:53 -0700943 outColorModes->clear();
944 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
945
946 return NO_ERROR;
947}
948
Peiyong Lina52f0292018-03-14 17:26:31 -0700949ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700950 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if (device != nullptr) {
952 return device->getActiveColorMode();
953 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700954 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700955}
956
957void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700958 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700959 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700960 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700961
962 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700963 return;
964 }
965
966 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
967 ALOGW("Trying to set config for virtual display");
968 return;
969 }
970
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600971 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
972 hw->getDisplayType());
973
Michael Wright28f24d02016-07-12 13:30:53 -0700974 hw->setActiveColorMode(mode);
975 getHwComposer().setActiveColorMode(type, mode);
976}
977
978
979status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 class MessageSetActiveColorMode: public MessageBase {
982 SurfaceFlinger& mFlinger;
983 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -0700984 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -0700985 public:
986 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -0700988 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
989 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -0700991 mFlinger.getDisplayColorModes(mDisplay, &modes);
992 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600994 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
995 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700996 return true;
997 }
998 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
999 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001000 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1001 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001002 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGW("Attempt to set active color mode %s %d for virtual display",
1004 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001005 } else {
1006 mFlinger.setActiveColorModeInternal(hw, mMode);
1007 }
1008 return true;
1009 }
1010 };
1011 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1012 postMessageSync(msg);
1013 return NO_ERROR;
1014}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001015
Svetoslavd85084b2014-03-20 10:28:31 -07001016status_t SurfaceFlinger::clearAnimationFrameStats() {
1017 Mutex::Autolock _l(mStateLock);
1018 mAnimFrameTracker.clearStats();
1019 return NO_ERROR;
1020}
1021
1022status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.getStats(outStats);
1025 return NO_ERROR;
1026}
1027
Dan Stozac4f471e2016-03-24 09:31:08 -07001028status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1029 HdrCapabilities* outCapabilities) const {
1030 Mutex::Autolock _l(mStateLock);
1031
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001032 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001033 if (displayDevice == nullptr) {
1034 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1035 return BAD_VALUE;
1036 }
1037
1038 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001039 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001040 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001041 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1042 // insert HDR10 as we will force client composition for HDR10
1043 // layers
1044 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1045 types.push_back(HAL_HDR_HDR10);
1046
1047 *outCapabilities = HdrCapabilities(types,
1048 capabilities->getDesiredMaxLuminance(),
1049 capabilities->getDesiredMaxAverageLuminance(),
1050 capabilities->getDesiredMinLuminance());
1051 } else {
1052 *outCapabilities = std::move(*capabilities);
1053 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001054 } else {
1055 return BAD_VALUE;
1056 }
1057
1058 return NO_ERROR;
1059}
1060
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001062 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1063 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001064
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 if (mInjectVSyncs == enable) {
1066 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068
1069 if (enable) {
1070 ALOGV("VSync Injections enabled");
1071 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001072 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001073 mInjectorEventThread =
1074 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1075 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001077 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078 } else {
1079 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001080 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 }
1082
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001083 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 });
1085 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001086 return NO_ERROR;
1087}
1088
1089status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001090 Mutex::Autolock _l(mStateLock);
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 if (!mInjectVSyncs) {
1093 ALOGE("VSync Injections not enabled");
1094 return BAD_VALUE;
1095 }
1096 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1097 ALOGV("Injecting VSync inside SurfaceFlinger");
1098 mVSyncInjector->onInjectSyncEvent(when);
1099 }
1100 return NO_ERROR;
1101}
1102
Lloyd Pique755e3192018-01-31 16:46:15 -08001103status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1104 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001105 IPCThreadState* ipc = IPCThreadState::self();
1106 const int pid = ipc->getCallingPid();
1107 const int uid = ipc->getCallingUid();
1108 if ((uid != AID_SHELL) &&
1109 !PermissionCache::checkPermission(sDump, pid, uid)) {
1110 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1111 return PERMISSION_DENIED;
1112 }
1113
1114 // Try to acquire a lock for 1s, fail gracefully
1115 const status_t err = mStateLock.timedLock(s2ns(1));
1116 const bool locked = (err == NO_ERROR);
1117 if (!locked) {
1118 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1119 return TIMED_OUT;
1120 }
1121
1122 outLayers->clear();
1123 mCurrentState.traverseInZOrder([&](Layer* layer) {
1124 outLayers->push_back(layer->getLayerDebugInfo());
1125 });
1126
1127 mStateLock.unlock();
1128 return NO_ERROR;
1129}
1130
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001131// ----------------------------------------------------------------------------
1132
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001133sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1134 ISurfaceComposer::VsyncSource vsyncSource) {
1135 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1136 return mSFEventThread->createEventConnection();
1137 } else {
1138 return mEventThread->createEventConnection();
1139 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001140}
1141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143
1144void SurfaceFlinger::waitForEvent() {
1145 mEventQueue.waitMessage();
1146}
1147
1148void SurfaceFlinger::signalTransaction() {
1149 mEventQueue.invalidate();
1150}
1151
1152void SurfaceFlinger::signalLayerUpdate() {
1153 mEventQueue.invalidate();
1154}
1155
1156void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001157 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158 mEventQueue.refresh();
1159}
1160
1161status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001162 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 return mEventQueue.postMessage(msg, reltime);
1164}
1165
1166status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001167 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001168 status_t res = mEventQueue.postMessage(msg, reltime);
1169 if (res == NO_ERROR) {
1170 msg->wait();
1171 }
1172 return res;
1173}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001175void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001176 do {
1177 waitForEvent();
1178 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179}
1180
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181void SurfaceFlinger::enableHardwareVsync() {
1182 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001183 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001185 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1186 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001188 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189}
1190
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 Mutex::Autolock _l(mHWVsyncLock);
1193
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 if (makeAvailable) {
1195 mHWVsyncAvailable = true;
1196 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001197 // Hardware vsync is not currently available, so abort the resync
1198 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199 return;
1200 }
1201
David Sodman105b7dc2017-11-04 20:28:14 -07001202 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204
1205 mPrimaryDispSync.reset();
1206 mPrimaryDispSync.setPeriod(period);
1207
1208 if (!mPrimaryHWVsyncEnabled) {
1209 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1211 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryHWVsyncEnabled = true;
1213 }
1214}
1215
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 Mutex::Autolock _l(mHWVsyncLock);
1218 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1220 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryDispSync.endResync();
1222 mPrimaryHWVsyncEnabled = false;
1223 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 if (makeUnavailable) {
1225 mHWVsyncAvailable = false;
1226 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227}
1228
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229void SurfaceFlinger::resyncWithRateLimit() {
1230 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001231
1232 // No explicit locking is needed here since EventThread holds a lock while calling this method
1233 static nsecs_t sLastResyncAttempted = 0;
1234 const nsecs_t now = systemTime();
1235 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237 }
Dan Stoza57164302017-05-08 14:03:54 -07001238 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239}
1240
Steven Thomasb02664d2017-07-26 18:48:28 -07001241void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1242 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001243 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001245 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 return;
1247 }
1248
1249 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001250 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 return;
1252 }
1253
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 { // Scope for the lock
1257 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001258 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001261 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001262
1263 if (needsHwVsync) {
1264 enableHardwareVsync();
1265 } else {
1266 disableHardwareVsync(false);
1267 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001268}
1269
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001270void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001271 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1272 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001273}
1274
Lloyd Pique715a2c12017-12-14 17:18:08 -08001275void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1276 HWC2::Connection connection) {
1277 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1278 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001279
Lloyd Piqueba04e622017-12-14 17:11:26 -08001280 // Ignore events that do not have the right sequenceId.
1281 if (sequenceId != getBE().mComposerSequenceId) {
1282 return;
1283 }
1284
Steven Thomasb02664d2017-07-26 18:48:28 -07001285 // Only lock if we're not on the main thread. This function is normally
1286 // called on a hwbinder thread, but for the primary display it's called on
1287 // the main thread with the state lock already held, so don't attempt to
1288 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001289 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001290
Lloyd Pique715a2c12017-12-14 17:18:08 -08001291 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001292
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001293 if (std::this_thread::get_id() == mMainThreadId) {
1294 // Process all pending hot plug events immediately if we are on the main thread.
1295 processDisplayHotplugEventsLocked();
1296 }
1297
Lloyd Piqueba04e622017-12-14 17:11:26 -08001298 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001299}
1300
Steven Thomasb02664d2017-07-26 18:48:28 -07001301void SurfaceFlinger::onRefreshReceived(int sequenceId,
1302 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001303 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001304 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001305 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001306 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001307 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001308}
1309
Dan Stoza9e56aa02015-11-02 13:00:03 -08001310void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001312 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 getHwComposer().setVsyncEnabled(disp,
1314 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001315}
1316
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001318void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001319 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320 // Clear the drawing state so that the logic inside of
1321 // handleTransactionLocked will fire. It will determine the delta between
1322 // mCurrentState and mDrawingState and re-apply all changes when we make the
1323 // transition.
1324 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001325 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326 mDisplays.clear();
1327}
1328
Steven Thomas050b2c82017-03-06 11:45:16 -08001329void SurfaceFlinger::updateVrFlinger() {
1330 if (!mVrFlinger)
1331 return;
1332 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001333 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001334 return;
1335 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336
David Sodman105b7dc2017-11-04 20:28:14 -07001337 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 ALOGE("Vr flinger is only supported for remote hardware composer"
1339 " service connections. Ignoring request to transition to vr"
1340 " flinger.");
1341 mVrFlingerRequestsDisplay = false;
1342 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001343 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 int currentDisplayPowerMode = getDisplayDeviceLocked(
1348 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349
Steven Thomasb02664d2017-07-26 18:48:28 -07001350 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001355 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001356 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1357 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001358 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359
David Sodman105b7dc2017-11-04 20:28:14 -07001360 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1361 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001362
1363 if (vrFlingerRequestsDisplay) {
1364 mVrFlinger->GrantDisplayOwnership();
1365 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368
1369 mVisibleRegionsDirty = true;
1370 invalidateHwcGeometry();
1371
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001372 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1374 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1375 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001376
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001378 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 const nsecs_t period = activeConfig->getVsyncPeriod();
1380 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 // Use phase of 0 since phase is not known.
1383 // Use latency of 0, which will snap to the ideal latency.
1384 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 android_atomic_or(1, &mRepaintEverything);
1387 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388}
1389
Mathias Agopian4fec8732012-06-29 14:12:52 -07001390void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001391 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001392 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001393 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001394 bool frameMissed = !mHadClientComposition &&
1395 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396 (mPreviousPresentFence->getSignalTime() ==
1397 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001398 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001399 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001400 signalLayerUpdate();
1401 break;
1402 }
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404 // Now that we're going to make it to the handleMessageTransaction()
1405 // call below it's safe to call updateVrFlinger(), which will
1406 // potentially trigger a display handoff.
1407 updateVrFlinger();
1408
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 bool refreshNeeded = handleMessageTransaction();
1410 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001411 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001413 // Signal a refresh if a transaction modified the window state,
1414 // a new buffer was latched, or if HWC has requested a full
1415 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 signalRefresh();
1417 }
1418 break;
1419 }
1420 case MessageQueue::REFRESH: {
1421 handleMessageRefresh();
1422 break;
1423 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424 }
1425}
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001428 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001430 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001431 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434}
1435
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001439}
1440
1441void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001443
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001444 mRefreshPending = false;
1445
Pablo Ceballos40845df2016-01-25 17:41:15 -08001446 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001447
Brian Andersond6927fb2016-07-23 23:37:30 -07001448 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001449 rebuildLayerStacks();
1450 setUpHWComposer();
1451 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001452 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001453 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001454 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001455 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001456
David Sodman105b7dc2017-11-04 20:28:14 -07001457 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001458
1459 mHadClientComposition = false;
1460 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1461 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1462 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001463 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001464 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001465
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469void SurfaceFlinger::doDebugFlashRegions()
1470{
1471 // is debugging enabled
1472 if (CC_LIKELY(!mDebugRegion))
1473 return;
1474
1475 const bool repaintEverything = mRepaintEverything;
1476 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1477 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001478 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 // transform the dirty region into this screen's coordinate space
1480 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1481 if (!dirtyRegion.isEmpty()) {
1482 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001483 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484
1485 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001486 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001487 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001488 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1489
Mathias Agopianda27af92012-09-13 18:17:13 -07001490 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 }
1492 }
1493 }
1494
1495 postFramebuffer();
1496
1497 if (mDebugRegion > 1) {
1498 usleep(mDebugRegion * 1000);
1499 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001500
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001502 auto& displayDevice = mDisplays[displayId];
1503 if (!displayDevice->isDisplayOn()) {
1504 continue;
1505 }
1506
David Sodman105b7dc2017-11-04 20:28:14 -07001507 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1508 ALOGE_IF(result != NO_ERROR,
1509 "prepareFrame for display %zd failed:"
1510 " %d (%s)",
1511 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001512 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513}
1514
Adrian Roos1e1a1282017-11-01 19:05:31 +01001515void SurfaceFlinger::doTracing(const char* where) {
1516 ATRACE_CALL();
1517 ATRACE_NAME(where);
1518 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001519 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001520 }
1521}
1522
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001523void SurfaceFlinger::logLayerStats() {
1524 ATRACE_CALL();
1525 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1526 int32_t hwcId = -1;
1527 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1528 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1529 if (displayDevice->isPrimary()) {
1530 hwcId = displayDevice->getHwcDisplayId();
1531 break;
1532 }
1533 }
1534 if (hwcId < 0) {
1535 ALOGE("LayerStats: Hmmm, no primary display?");
1536 return;
1537 }
1538 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1539 }
1540}
1541
Brian Andersond6927fb2016-07-23 23:37:30 -07001542void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 ATRACE_CALL();
1545 ALOGV("preComposition");
1546
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001548 mDrawingState.traverseInZOrder([&](Layer* layer) {
1549 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550 needExtraInvalidate = true;
1551 }
Robert Carr2047fae2016-11-28 14:09:09 -08001552 });
1553
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554 if (needExtraInvalidate) {
1555 signalLayerUpdate();
1556 }
1557}
1558
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559void SurfaceFlinger::updateCompositorTiming(
1560 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1561 std::shared_ptr<FenceTime>& presentFenceTime) {
1562 // Update queue of past composite+present times and determine the
1563 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001564 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001566 while (!getBE().mCompositePresentTimes.empty()) {
1567 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568 // Cached values should have been updated before calling this method,
1569 // which helps avoid duplicate syscalls.
1570 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1571 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1572 break;
1573 }
1574 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001575 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001576 }
1577
1578 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001579 while (getBE().mCompositePresentTimes.size() > 16) {
1580 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581 }
1582
Brian Andersond0010582017-03-07 13:20:31 -08001583 setCompositorTimingSnapped(
1584 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1585}
1586
1587void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1588 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589 // Integer division and modulo round toward 0 not -inf, so we need to
1590 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001591 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1593 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1594
Brian Andersond0010582017-03-07 13:20:31 -08001595 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1596 if (idealLatency <= 0) {
1597 idealLatency = vsyncInterval;
1598 }
1599
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600 // Snap the latency to a value that removes scheduling jitter from the
1601 // composition and present times, which often have >1ms of jitter.
1602 // Reducing jitter is important if an app attempts to extrapolate
1603 // something (such as user input) to an accurate diasplay time.
1604 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1605 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001606 nsecs_t bias = vsyncInterval / 2;
1607 int64_t extraVsyncs =
1608 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1609 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1610 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611
David Sodman99974d22017-11-28 12:04:33 -08001612 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1613 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1614 getBE().mCompositorTiming.interval = vsyncInterval;
1615 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616}
1617
1618void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001620 ATRACE_CALL();
1621 ALOGV("postComposition");
1622
Brian Anderson3546a3f2016-07-14 11:51:14 -07001623 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001624 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001625 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001626 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001627 }
1628
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001629 // |mStateLock| not needed as we are on the main thread
1630 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001631
David Sodman73beded2017-11-15 11:56:06 -08001632 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001633 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001634 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001635 glCompositionDoneFenceTime =
1636 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001637 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001638 } else {
1639 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1640 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001641
David Sodman73beded2017-11-15 11:56:06 -08001642 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001643 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001644 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001645 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001646
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1648 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1649
1650 // We use the refreshStartTime which might be sampled a little later than
1651 // when we started doing work for this frame, but that should be okay
1652 // since updateCompositorTiming has snapping logic.
1653 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001654 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001655 CompositorTiming compositorTiming;
1656 {
David Sodman99974d22017-11-28 12:04:33 -08001657 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1658 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001659 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660
Robert Carr2047fae2016-11-28 14:09:09 -08001661 mDrawingState.traverseInZOrder([&](Layer* layer) {
1662 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001663 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001664 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001665 recordBufferingStats(layer->getName().string(),
1666 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001667 }
Robert Carr2047fae2016-11-28 14:09:09 -08001668 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001669
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001670 if (presentFenceTime->isValid()) {
1671 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001672 enableHardwareVsync();
1673 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001674 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001675 }
1676 }
1677
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001678 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001679 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001680 enableHardwareVsync();
1681 }
1682 }
1683
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001684 if (mAnimCompositionPending) {
1685 mAnimCompositionPending = false;
1686
Brian Anderson4e606e32017-03-16 15:34:57 -07001687 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001688 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001689 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001690 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001691 // The HWC doesn't support present fences, so use the refresh
1692 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001693 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001694 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001695 mAnimFrameTracker.setActualPresentTime(presentTime);
1696 }
1697 mAnimFrameTracker.advanceFrame();
1698 }
Dan Stozab90cf072015-03-05 11:05:59 -08001699
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001700 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1701 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001702 return;
1703 }
1704
1705 nsecs_t currentTime = systemTime();
1706 if (mHasPoweredOff) {
1707 mHasPoweredOff = false;
1708 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001709 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001711 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1712 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001713 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001714 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001715 }
David Sodman4a36e932017-11-07 14:29:47 -08001716 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001717 }
David Sodman4a36e932017-11-07 14:29:47 -08001718 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719}
1720
1721void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001722 ATRACE_CALL();
1723 ALOGV("rebuildLayerStacks");
1724
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001726 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001727 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001728 mVisibleRegionsDirty = false;
1729 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001730
Jeff Sharkey76488112017-02-27 14:15:18 -07001731 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1732 Region opaqueRegion;
1733 Region dirtyRegion;
1734 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001735 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001736 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1737 const Transform& tr(displayDevice->getTransform());
1738 const Rect bounds(displayDevice->getBounds());
1739 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001740 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001741
Jeff Sharkey76488112017-02-27 14:15:18 -07001742 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001743 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001744 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1745 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001746 Region drawRegion(tr.transform(
1747 layer->visibleNonTransparentRegion));
1748 drawRegion.andSelf(bounds);
1749 if (!drawRegion.isEmpty()) {
1750 layersSortedByZ.add(layer);
1751 } else {
1752 // Clear out the HWC layer if this layer was
1753 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001754 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001755 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001756 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001757 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001758 // WM changes displayDevice->layerStack upon sleep/awake.
1759 // Here we make sure we delete the HWC layers even if
1760 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001761 hwcLayerDestroyed = layer->destroyHwcLayer(
1762 displayDevice->getHwcDisplayId());
1763 }
1764
1765 // If a layer is not going to get a release fence because
1766 // it is invisible, but it is also going to release its
1767 // old buffer, add it to the list of layers needing
1768 // fences.
1769 if (hwcLayerDestroyed) {
1770 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1771 mLayersWithQueuedFrames.cend(), layer);
1772 if (found != mLayersWithQueuedFrames.cend()) {
1773 layersNeedingFences.add(layer);
1774 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001775 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 });
1777 }
1778 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001779 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 displayDevice->undefinedRegion.set(bounds);
1781 displayDevice->undefinedRegion.subtractSelf(
1782 tr.transform(opaqueRegion));
1783 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001784 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001785 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001786}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001787
Romain Guy0147a172017-06-01 13:53:56 -07001788mat4 SurfaceFlinger::computeSaturationMatrix() const {
1789 if (mSaturation == 1.0f) {
1790 return mat4();
1791 }
1792
1793 // Rec.709 luma coefficients
1794 float3 luminance{0.213f, 0.715f, 0.072f};
1795 luminance *= 1.0f - mSaturation;
1796 return mat4(
1797 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1798 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1799 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1800 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1801 );
1802}
1803
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001804// pickColorMode translates a given dataspace into the best available color mode.
1805// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001806ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001807 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001808 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001809 }
1810
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001811 switch (dataSpace) {
1812 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1813 // system expects.
1814 case HAL_DATASPACE_UNKNOWN:
1815 case HAL_DATASPACE_SRGB:
1816 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001817 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001818 break;
1819
1820 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001821 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001822 break;
1823
1824 default:
1825 // TODO (courtneygo): Do we want to assert an error here?
1826 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1827 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001828 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001829 break;
1830 }
1831}
1832
Romain Guy0147a172017-06-01 13:53:56 -07001833android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001834 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001835 // Only support sRGB and Display-P3 right now.
1836 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1837 return HAL_DATASPACE_DISPLAY_P3;
1838 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001839 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1840 return HAL_DATASPACE_DISPLAY_P3;
1841 }
1842 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1843 return HAL_DATASPACE_DISPLAY_P3;
1844 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001845 if (!hasHdr) {
1846 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1847 return HAL_DATASPACE_DISPLAY_P3;
1848 }
1849 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1850 return HAL_DATASPACE_DISPLAY_P3;
1851 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001852 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001853
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001854 return HAL_DATASPACE_V0_SRGB;
1855}
1856
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 ATRACE_CALL();
1859 ALOGV("setUpHWComposer");
1860
Jesse Hall028dc8f2013-08-20 16:35:32 -07001861 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001862 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1863 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1864 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1865
1866 // If nothing has changed (!dirty), don't recompose.
1867 // If something changed, but we don't currently have any visible layers,
1868 // and didn't when we last did a composition, then skip it this time.
1869 // The second rule does two things:
1870 // - When all layers are removed from a display, we'll emit one black
1871 // frame, then nothing more until we get new layers.
1872 // - When a display is created with a private layer stack, we won't
1873 // emit any black frames until a layer is added to the layer stack.
1874 bool mustRecompose = dirty && !(empty && wasEmpty);
1875
1876 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1877 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1878 mustRecompose ? "doing" : "skipping",
1879 dirty ? "+" : "-",
1880 empty ? "+" : "-",
1881 wasEmpty ? "+" : "-");
1882
Dan Stoza71433162014-02-04 16:22:36 -08001883 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001884
1885 if (mustRecompose) {
1886 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1887 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001888 }
1889
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 // build the h/w work list
1891 if (CC_UNLIKELY(mGeometryInvalid)) {
1892 mGeometryInvalid = false;
1893 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1894 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1895 const auto hwcId = displayDevice->getHwcDisplayId();
1896 if (hwcId >= 0) {
1897 const Vector<sp<Layer>>& currentLayers(
1898 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001899 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001900 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001902 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001904 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001905 }
1906 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001907
Robert Carrae060832016-11-28 10:51:00 -08001908 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001909 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001911 }
1912 }
1913 }
1914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 }
Riley Andrews03414a12014-07-01 14:22:59 -07001916
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001917
Romain Guy0147a172017-06-01 13:53:56 -07001918 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001919
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 // Set the per-frame data
1921 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1922 auto& displayDevice = mDisplays[displayId];
1923 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001924
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 if (hwcId < 0) {
1926 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001927 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001928 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001929 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001930 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1931 "display %zd: %d", displayId, result);
1932 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001934 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1935 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001936 !displayDevice->getHdrSupport()) {
1937 layer->forceClientComposition(hwcId);
1938 }
1939
chaviwc9232ed2017-11-14 15:31:15 -08001940 if (layer->getForceClientComposition(hwcId)) {
1941 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1942 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1943 continue;
1944 }
1945
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 layer->setPerFrameData(displayDevice);
1947 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001948
1949 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001950 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001951 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1952
1953 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001954 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1955 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001956 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1957 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1958 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1959 }
1960 newColorMode = pickColorMode(newDataSpace);
1961
Thierry Strudel2924d012017-08-14 15:19:37 -07001962 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001963 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 }
1965
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001966 mPreviousColorMatrix = colorMatrix;
1967
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001969 auto& displayDevice = mDisplays[displayId];
1970 if (!displayDevice->isDisplayOn()) {
1971 continue;
1972 }
1973
David Sodman105b7dc2017-11-04 20:28:14 -07001974 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1976 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001977 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001979
Mathias Agopiancd60f992012-08-16 16:28:27 -07001980void SurfaceFlinger::doComposition() {
1981 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 ALOGV("doComposition");
1983
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001984 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001985 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001986 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001987 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988 // transform the dirty region into this screen's coordinate space
1989 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001990
1991 // repaint the framebuffer (if needed)
1992 doDisplayComposition(hw, dirtyRegion);
1993
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001995 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001996 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001997 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001998 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001999}
2000
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001void SurfaceFlinger::postFramebuffer()
2002{
Mathias Agopian841cde52012-03-01 15:44:37 -08002003 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002005
Mathias Agopiana44b0412011-10-16 18:46:35 -07002006 const nsecs_t now = systemTime();
2007 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002008
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2010 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002011 if (!displayDevice->isDisplayOn()) {
2012 continue;
2013 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 const auto hwcId = displayDevice->getHwcDisplayId();
2015 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002016 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002017 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002018 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002019 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002021 // The layer buffer from the previous frame (if any) is released
2022 // by HWC only when the release fence from this frame (if any) is
2023 // signaled. Always get the release fence from HWC first.
2024 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002025 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002026
2027 // If the layer was client composited in the previous frame, we
2028 // need to merge with the previous client target acquire fence.
2029 // Since we do not track that, always merge with the current
2030 // client target acquire fence when it is available, even though
2031 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002033 releaseFence = Fence::merge("LayerRelease", releaseFence,
2034 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002035 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002036
David Sodmanb8af7922017-12-21 15:17:55 -08002037 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 }
Chia-I Wu83806892017-11-16 10:50:20 -08002039
2040 // We've got a list of layers needing fences, that are disjoint with
2041 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2042 // supply them with the present fence.
2043 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002044 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002045 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002046 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002047 }
2048 }
2049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002051 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002052 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002053 }
2054
Mathias Agopiana44b0412011-10-16 18:46:35 -07002055 mLastSwapBufferTime = systemTime() - now;
2056 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002057
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002058 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002059 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2060 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2061 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2062 logFrameStats();
2063 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002064 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065}
2066
Mathias Agopian87baae12012-07-31 12:38:26 -07002067void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002068{
Mathias Agopian841cde52012-03-01 15:44:37 -08002069 ATRACE_CALL();
2070
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002071 // here we keep a copy of the drawing state (that is the state that's
2072 // going to be overwritten by handleTransactionLocked()) outside of
2073 // mStateLock so that the side-effects of the State assignment
2074 // don't happen with mStateLock held (which can cause deadlocks).
2075 State drawingState(mDrawingState);
2076
Mathias Agopianca4d3602011-05-19 15:38:14 -07002077 Mutex::Autolock _l(mStateLock);
2078 const nsecs_t now = systemTime();
2079 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002080
Mathias Agopianca4d3602011-05-19 15:38:14 -07002081 // Here we're guaranteed that some transaction flags are set
2082 // so we can call handleTransactionLocked() unconditionally.
2083 // We call getTransactionFlags(), which will also clear the flags,
2084 // with mStateLock held to guarantee that mCurrentState won't change
2085 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002086
Mathias Agopiane57f2922012-08-09 16:29:12 -07002087 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002088 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002089
Mathias Agopianca4d3602011-05-19 15:38:14 -07002090 mLastTransactionTime = systemTime() - now;
2091 mDebugInTransaction = 0;
2092 invalidateHwcGeometry();
2093 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002094}
2095
Lloyd Pique715a2c12017-12-14 17:18:08 -08002096DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2097 HWC2::Connection connection) const {
2098 // Figure out whether the event is for the primary display or an
2099 // external display by matching the Hwc display id against one for a
2100 // connected display. If we did not find a match, we then check what
2101 // displays are not already connected to determine the type. If we don't
2102 // have a connected primary display, we assume the new display is meant to
2103 // be the primary display, and then if we don't have an external display,
2104 // we assume it is that.
2105 const auto primaryDisplayId =
2106 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2107 const auto externalDisplayId =
2108 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2109 if (primaryDisplayId && primaryDisplayId == display) {
2110 return DisplayDevice::DISPLAY_PRIMARY;
2111 } else if (externalDisplayId && externalDisplayId == display) {
2112 return DisplayDevice::DISPLAY_EXTERNAL;
2113 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2114 return DisplayDevice::DISPLAY_PRIMARY;
2115 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2116 return DisplayDevice::DISPLAY_EXTERNAL;
2117 }
2118
2119 return DisplayDevice::DISPLAY_ID_INVALID;
2120}
2121
Lloyd Piqueba04e622017-12-14 17:11:26 -08002122void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2123 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002124 auto displayType = determineDisplayType(event.display, event.connection);
2125 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2126 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2127 continue;
2128 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002129
2130 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2131 ALOGE("External displays are not supported by the vr hardware composer.");
2132 continue;
2133 }
2134
Lloyd Pique715a2c12017-12-14 17:18:08 -08002135 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002136
2137 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002138 ALOGV("Creating built in display %d", displayType);
2139 ALOGW_IF(mBuiltinDisplays[displayType],
2140 "Overwriting display token for display type %d", displayType);
2141 mBuiltinDisplays[displayType] = new BBinder();
2142 // All non-virtual displays are currently considered secure.
2143 DisplayDeviceState info(displayType, true);
2144 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2145 "Built-in Screen" : "External Screen";
2146 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2147 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002148 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002149 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002150
Lloyd Piquefcd86612017-12-14 17:15:36 -08002151 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2152 if (idx >= 0) {
2153 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2154 mInterceptor.saveDisplayDeletion(info.displayId);
2155 mCurrentState.displays.removeItemsAt(idx);
2156 }
2157 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002158 }
2159
2160 processDisplayChangesLocked();
2161 }
2162
2163 mPendingHotplugEvents.clear();
2164}
2165
Lloyd Pique347200f2017-12-14 17:00:15 -08002166void SurfaceFlinger::processDisplayChangesLocked() {
2167 // here we take advantage of Vector's copy-on-write semantics to
2168 // improve performance by skipping the transaction entirely when
2169 // know that the lists are identical
2170 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2171 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2172 if (!curr.isIdenticalTo(draw)) {
2173 mVisibleRegionsDirty = true;
2174 const size_t cc = curr.size();
2175 size_t dc = draw.size();
2176
2177 // find the displays that were removed
2178 // (ie: in drawing state but not in current state)
2179 // also handle displays that changed
2180 // (ie: displays that are in both lists)
2181 for (size_t i = 0; i < dc;) {
2182 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2183 if (j < 0) {
2184 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002185 // Call makeCurrent() on the primary display so we can
2186 // be sure that nothing associated with this display
2187 // is current.
2188 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2189 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2190 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2191 if (hw != nullptr) hw->disconnect(getHwComposer());
2192 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2193 mEventThread->onHotplugReceived(draw[i].type, false);
2194 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002195 } else {
2196 // this display is in both lists. see if something changed.
2197 const DisplayDeviceState& state(curr[j]);
2198 const wp<IBinder>& display(curr.keyAt(j));
2199 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2200 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2201 if (state_binder != draw_binder) {
2202 // changing the surface is like destroying and
2203 // recreating the DisplayDevice, so we just remove it
2204 // from the drawing state, so that it get re-added
2205 // below.
2206 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2207 if (hw != nullptr) hw->disconnect(getHwComposer());
2208 mDisplays.removeItem(display);
2209 mDrawingState.displays.removeItemsAt(i);
2210 dc--;
2211 // at this point we must loop to the next item
2212 continue;
2213 }
2214
2215 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2216 if (disp != nullptr) {
2217 if (state.layerStack != draw[i].layerStack) {
2218 disp->setLayerStack(state.layerStack);
2219 }
2220 if ((state.orientation != draw[i].orientation) ||
2221 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2222 disp->setProjection(state.orientation, state.viewport, state.frame);
2223 }
2224 if (state.width != draw[i].width || state.height != draw[i].height) {
2225 disp->setDisplaySize(state.width, state.height);
2226 }
2227 }
2228 }
2229 ++i;
2230 }
2231
2232 // find displays that were added
2233 // (ie: in current state but not in drawing state)
2234 for (size_t i = 0; i < cc; i++) {
2235 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2236 const DisplayDeviceState& state(curr[i]);
2237
2238 sp<DisplaySurface> dispSurface;
2239 sp<IGraphicBufferProducer> producer;
2240 sp<IGraphicBufferProducer> bqProducer;
2241 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002242 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002243
2244 int32_t hwcId = -1;
2245 if (state.isVirtualDisplay()) {
2246 // Virtual displays without a surface are dormant:
2247 // they have external state (layer stack, projection,
2248 // etc.) but no internal state (i.e. a DisplayDevice).
2249 if (state.surface != nullptr) {
2250 // Allow VR composer to use virtual displays.
2251 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2252 int width = 0;
2253 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2254 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2255 int height = 0;
2256 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2257 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2258 int intFormat = 0;
2259 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2260 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2261 auto format = static_cast<android_pixel_format_t>(intFormat);
2262
2263 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2264 }
2265
2266 // TODO: Plumb requested format back up to consumer
2267
2268 sp<VirtualDisplaySurface> vds =
2269 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2270 bqProducer, bqConsumer,
2271 state.displayName);
2272
2273 dispSurface = vds;
2274 producer = vds;
2275 }
2276 } else {
2277 ALOGE_IF(state.surface != nullptr,
2278 "adding a supported display, but rendering "
2279 "surface is provided (%p), ignoring it",
2280 state.surface.get());
2281
2282 hwcId = state.type;
2283 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2284 producer = bqProducer;
2285 }
2286
2287 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002288
Lloyd Pique347200f2017-12-14 17:00:15 -08002289 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002290 bool hasWideColorSupport = false;
2291 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002292 std::vector<ColorMode> modes =
Lloyd Piquefcd86612017-12-14 17:15:36 -08002293 getHwComposer().getColorModes(state.type);
Peiyong Lina52f0292018-03-14 17:26:31 -07002294 for (ColorMode colorMode : modes) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002295 switch (colorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002296 case ColorMode::DISPLAY_P3:
2297 case ColorMode::ADOBE_RGB:
2298 case ColorMode::DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002299 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002300 break;
2301 default:
2302 break;
2303 }
2304 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002305 }
2306
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002307 bool hasHdrSupport = false;
2308 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2309 getHwComposer().getHdrCapabilities(state.type);
2310 if (hdrCapabilities) {
2311 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2312 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2313 hasHdrSupport = iter != types.cend();
2314 }
2315
Lloyd Pique347200f2017-12-14 17:00:15 -08002316 sp<DisplayDevice> hw =
2317 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002318 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002319 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002320
Peiyong Lina52f0292018-03-14 17:26:31 -07002321 ColorMode defaultColorMode = ColorMode::NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002322 if (hasWideColorSupport) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002323 defaultColorMode = ColorMode::SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002324 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002325 setActiveColorModeInternal(hw, defaultColorMode);
2326 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002327 hw->setLayerStack(state.layerStack);
2328 hw->setProjection(state.orientation, state.viewport, state.frame);
2329 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002330
Lloyd Pique347200f2017-12-14 17:00:15 -08002331 mDisplays.add(display, hw);
2332 if (!state.isVirtualDisplay()) {
2333 mEventThread->onHotplugReceived(state.type, true);
2334 }
2335 }
2336 }
2337 }
2338 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339
2340 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002341}
2342
Mathias Agopian87baae12012-07-31 12:38:26 -07002343void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002344{
Dan Stoza7dde5992015-05-22 09:51:44 -07002345 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002346 mCurrentState.traverseInZOrder([](Layer* layer) {
2347 layer->notifyAvailableFrames();
2348 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350 /*
2351 * Traversal of the children
2352 * (perform the transaction for each of them if needed)
2353 */
2354
Mathias Agopian3559b072012-08-15 13:46:03 -07002355 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002356 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002358 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359
2360 const uint32_t flags = layer->doTransaction(0);
2361 if (flags & Layer::eVisibleRegion)
2362 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002363 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 }
2365
2366 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002367 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002368 */
2369
Mathias Agopiane57f2922012-08-09 16:29:12 -07002370 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002371 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002372 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002373 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374
Mathias Agopian84300952012-11-21 16:02:13 -08002375 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2376 // The transform hint might have changed for some layers
2377 // (either because a display has changed, or because a layer
2378 // as changed).
2379 //
2380 // Walk through all the layers in currentLayers,
2381 // and update their transform hint.
2382 //
2383 // If a layer is visible only on a single display, then that
2384 // display is used to calculate the hint, otherwise we use the
2385 // default display.
2386 //
2387 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2388 // the hint is set before we acquire a buffer from the surface texture.
2389 //
2390 // NOTE: layer transactions have taken place already, so we use their
2391 // drawing state. However, SurfaceFlinger's own transaction has not
2392 // happened yet, so we must use the current state layer list
2393 // (soon to become the drawing state list).
2394 //
2395 sp<const DisplayDevice> disp;
2396 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002397 bool first = true;
2398 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002399 // NOTE: we rely on the fact that layers are sorted by
2400 // layerStack first (so we don't have to traverse the list
2401 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002402 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002403 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002404 currentlayerStack = layerStack;
2405 // figure out if this layerstack is mirrored
2406 // (more than one display) if so, pick the default display,
2407 // if not, pick the only display it's on.
2408 disp.clear();
2409 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2410 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002411 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002412 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002413 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002414 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002415 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002416 break;
2417 }
2418 }
2419 }
2420 }
Chet Haase91d25932013-04-11 15:24:55 -07002421
Robert Carr56a0b9a2017-12-04 16:06:13 -08002422 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002423 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002424 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2425 // redraw after transform hint changes. See bug 8508397.
2426
2427 // could be null when this layer is using a layerStack
2428 // that is not visible on any display. Also can occur at
2429 // screen off/on times.
2430 disp = getDefaultDisplayDeviceLocked();
2431 }
2432 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002433 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002434 if (disp != nullptr) {
2435 layer->updateTransformHint(disp);
2436 }
Robert Carr2047fae2016-11-28 14:09:09 -08002437
2438 first = false;
2439 });
Mathias Agopian84300952012-11-21 16:02:13 -08002440 }
2441
2442
Mathias Agopian3559b072012-08-15 13:46:03 -07002443 /*
2444 * Perform our own transaction if needed
2445 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002446
2447 if (mLayersAdded) {
2448 mLayersAdded = false;
2449 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002450 mVisibleRegionsDirty = true;
2451 }
2452
2453 // some layers might have been removed, so
2454 // we need to update the regions they're exposing.
2455 if (mLayersRemoved) {
2456 mLayersRemoved = false;
2457 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002458 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002459 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002460 // this layer is not visible anymore
2461 // TODO: we could traverse the tree from front to back and
2462 // compute the actual visible region
2463 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002464 Region visibleReg;
2465 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002466 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002467 }
Robert Carr2047fae2016-11-28 14:09:09 -08002468 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469 }
2470
2471 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002472
2473 updateCursorAsync();
2474}
2475
2476void SurfaceFlinger::updateCursorAsync()
2477{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2479 auto& displayDevice = mDisplays[displayId];
2480 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002481 continue;
2482 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483
2484 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2485 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002486 }
2487 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002488}
2489
2490void SurfaceFlinger::commitTransaction()
2491{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002492 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002493 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494 for (const auto& l : mLayersPendingRemoval) {
2495 recordBufferingStats(l->getName().string(),
2496 l->getOccupancyHistory(true));
2497 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002498 }
2499 mLayersPendingRemoval.clear();
2500 }
2501
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002502 // If this transaction is part of a window animation then the next frame
2503 // we composite should be considered an animation as well.
2504 mAnimCompositionPending = mAnimTransactionPending;
2505
Mathias Agopian4fec8732012-06-29 14:12:52 -07002506 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002507 mDrawingState.traverseInZOrder([](Layer* layer) {
2508 layer->commitChildList();
2509 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002510 mTransactionPending = false;
2511 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002512 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513}
2514
Chia-I Wuab0c3192017-08-01 11:29:00 -07002515void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002516 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517{
Mathias Agopian841cde52012-03-01 15:44:37 -08002518 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002520
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521 Region aboveOpaqueLayers;
2522 Region aboveCoveredLayers;
2523 Region dirty;
2524
Mathias Agopian87baae12012-07-31 12:38:26 -07002525 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
Robert Carr2047fae2016-11-28 14:09:09 -08002527 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002529 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530
Jesse Hall01e29052013-02-19 16:13:35 -08002531 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002532 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002533 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002534
Mathias Agopianab028732010-03-16 16:41:46 -07002535 /*
2536 * opaqueRegion: area of a surface that is fully opaque.
2537 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002539
2540 /*
2541 * visibleRegion: area of a surface that is visible on screen
2542 * and not fully transparent. This is essentially the layer's
2543 * footprint minus the opaque regions above it.
2544 * Areas covered by a translucent surface are considered visible.
2545 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002547
2548 /*
2549 * coveredRegion: area of a surface that is covered by all
2550 * visible regions above it (which includes the translucent areas).
2551 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002553
Jesse Halla8026d22012-09-25 13:25:04 -07002554 /*
2555 * transparentRegion: area of a surface that is hinted to be completely
2556 * transparent. This is only used to tell when the layer has no visible
2557 * non-transparent regions and can be removed from the layer list. It
2558 * does not affect the visibleRegion of this layer or any layers
2559 * beneath it. The hint may not be correct if apps don't respect the
2560 * SurfaceView restrictions (which, sadly, some don't).
2561 */
2562 Region transparentRegion;
2563
Mathias Agopianab028732010-03-16 16:41:46 -07002564
2565 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002566 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002567 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002568 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002570 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002571 if (!visibleRegion.isEmpty()) {
2572 // Remove the transparent area from the visible region
2573 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002574 if (tr.preserveRects()) {
2575 // transform the transparent region
2576 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002578 // transformation too complex, can't do the
2579 // transparent region optimization.
2580 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002581 }
Mathias Agopianab028732010-03-16 16:41:46 -07002582 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
Mathias Agopianab028732010-03-16 16:41:46 -07002584 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002586 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002587 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2588 // the opaque region is the layer's footprint
2589 opaqueRegion = visibleRegion;
2590 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 }
2592 }
2593
Robert Carre5f4f692018-01-12 13:12:28 -08002594 if (visibleRegion.isEmpty()) {
2595 layer->clearVisibilityRegions();
2596 return;
2597 }
2598
Mathias Agopianab028732010-03-16 16:41:46 -07002599 // Clip the covered region to the visible region
2600 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2601
2602 // Update aboveCoveredLayers for next (lower) layer
2603 aboveCoveredLayers.orSelf(visibleRegion);
2604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 // subtract the opaque region covered by the layers above us
2606 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607
2608 // compute this layer's dirty region
2609 if (layer->contentDirty) {
2610 // we need to invalidate the whole region
2611 dirty = visibleRegion;
2612 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002613 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 layer->contentDirty = false;
2615 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002616 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002617 * the exposed region consists of two components:
2618 * 1) what's VISIBLE now and was COVERED before
2619 * 2) what's EXPOSED now less what was EXPOSED before
2620 *
2621 * note that (1) is conservative, we start with the whole
2622 * visible region but only keep what used to be covered by
2623 * something -- which mean it may have been exposed.
2624 *
2625 * (2) handles areas that were not covered by anything but got
2626 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002627 */
Mathias Agopianab028732010-03-16 16:41:46 -07002628 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002629 const Region oldVisibleRegion = layer->visibleRegion;
2630 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002631 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2632 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 }
2634 dirty.subtractSelf(aboveOpaqueLayers);
2635
2636 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002637 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638
Mathias Agopianab028732010-03-16 16:41:46 -07002639 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002641
Jesse Halla8026d22012-09-25 13:25:04 -07002642 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 layer->setVisibleRegion(visibleRegion);
2644 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002645 layer->setVisibleNonTransparentRegion(
2646 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002647 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648
Mathias Agopian87baae12012-07-31 12:38:26 -07002649 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650}
2651
Chia-I Wuab0c3192017-08-01 11:29:00 -07002652void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002653 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002654 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002655 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002656 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002657 }
2658 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002659}
2660
Dan Stoza6b9454d2014-11-07 16:00:59 -08002661bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 ALOGV("handlePageFlip");
2664
Brian Andersond6927fb2016-07-23 23:37:30 -07002665 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666
Mathias Agopian4fec8732012-06-29 14:12:52 -07002667 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002668 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002669 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002670
2671 // Store the set of layers that need updates. This set must not change as
2672 // buffers are being latched, as this could result in a deadlock.
2673 // Example: Two producers share the same command stream and:
2674 // 1.) Layer 0 is latched
2675 // 2.) Layer 0 gets a new frame
2676 // 2.) Layer 1 gets a new frame
2677 // 3.) Layer 1 is latched.
2678 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2679 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002680 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002681 if (layer->hasQueuedFrame()) {
2682 frameQueued = true;
2683 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002684 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002685 } else {
2686 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002687 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002688 } else {
2689 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002690 }
Robert Carr2047fae2016-11-28 14:09:09 -08002691 });
2692
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002694 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002695 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002696 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002697 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002698 newDataLatched = true;
2699 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002701
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002702 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002703
2704 // If we will need to wake up at some time in the future to deal with a
2705 // queued frame that shouldn't be displayed during this vsync period, wake
2706 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002707 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002708 signalLayerUpdate();
2709 }
2710
2711 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002712 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713}
2714
Mathias Agopianad456f92011-01-13 17:53:01 -08002715void SurfaceFlinger::invalidateHwcGeometry()
2716{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002718}
2719
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002720
Fabien Sanglard830b8472016-11-30 16:35:58 -08002721void SurfaceFlinger::doDisplayComposition(
2722 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002723 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724{
Dan Stoza71433162014-02-04 16:22:36 -08002725 // We only need to actually compose the display if:
2726 // 1) It is being handled by hardware composer, which may need this to
2727 // keep its virtual display state machine in sync, or
2728 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002729 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002730 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002732 return;
2733 }
2734
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002736 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002737
2738 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002739 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740}
2741
Chia-I Wub02087d2017-11-09 10:19:54 -08002742bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002743{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002745
Chia-I Wub02087d2017-11-09 10:19:54 -08002746 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002747 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002749
2750 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002751 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2752 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002753 if (applyColorMatrix) {
2754 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2755 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2756 }
2757
David Sodman105b7dc2017-11-04 20:28:14 -07002758 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 if (hasClientComposition) {
2760 ALOGV("hasClientComposition");
2761
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002762 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002763 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002764 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002765 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2766 }
2767 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2768
Chia-I Wu7f402902017-11-09 12:51:10 -08002769 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002770 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002772 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002773
2774 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002775 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002776 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2777 }
2778 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002779 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002780
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002781 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002782 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002784 // when using overlays, we assume a fully transparent framebuffer
2785 // NOTE: we could reduce how much we need to clear, for instance
2786 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002787 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002788 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002789 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002790 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002791 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002792 // we're left with the letterbox region
2793 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002795
2796 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002798
Mathias Agopianb9494d52012-04-18 02:28:45 -07002799 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002800 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002801 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002803 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002804 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002805
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002807 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002808 // scissor on the main display. It should never be needed
2809 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 const Rect& bounds(displayDevice->getBounds());
2811 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002812 if (scissor != bounds) {
2813 // scissor doesn't match the screen's dimensions, so we
2814 // need to clear everything outside of it and enable
2815 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002816
Mathias Agopianf45c5102012-10-24 16:29:17 -07002817 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002819 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002820 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002821 }
2822 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002823 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002824
Mathias Agopian85d751c2012-08-29 16:59:24 -07002825 /*
2826 * and then, render the layers targeted at the framebuffer
2827 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002828
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 ALOGV("Rendering client layers");
2830 const Transform& displayTransform = displayDevice->getTransform();
2831 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002832 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 bool firstLayer = true;
2834 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002835 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002836 displayTransform.transform(layer->visibleRegion)));
2837 ALOGV("Layer: %s", layer->getName().string());
2838 ALOGV(" Composition type: %s",
2839 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002840 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 switch (layer->getCompositionType(hwcId)) {
2842 case HWC2::Composition::Cursor:
2843 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002844 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002846 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002848 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002850 // never clear the very first layer since we're
2851 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002852 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002853 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002854 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002855 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002857 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002858 break;
2859 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002860 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002861 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002862 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002863 } else {
2864 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002865 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002867 }
2868 } else {
2869 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002871 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002872 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002873 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002874 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002875 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002876 }
2877 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002878
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002879 if (applyColorMatrix) {
2880 getRenderEngine().setupColorTransform(oldColorMatrix);
2881 }
2882
Mathias Agopianf45c5102012-10-24 16:29:17 -07002883 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002884 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002885 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886}
2887
Fabien Sanglard830b8472016-11-30 16:35:58 -08002888void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2889 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002890 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002891 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Dan Stoza7d89d062015-04-30 13:29:25 -07002894status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002895 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002896 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002897 const sp<Layer>& lbc,
2898 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002899{
Dan Stoza7d89d062015-04-30 13:29:25 -07002900 // add this layer to the current state list
2901 {
2902 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002904 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2905 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002906 return NO_MEMORY;
2907 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002908 if (parent == nullptr) {
2909 mCurrentState.layersSortedByZ.add(lbc);
2910 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002911 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002912 ALOGE("addClientLayer called with a removed parent");
2913 return NAME_NOT_FOUND;
2914 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002915 parent->addChild(lbc);
2916 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002917
Dan Stoza101d8dc2018-02-27 15:42:25 -08002918 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2919 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() > MAX_LAYERS,
2920 "Suspected IGBP leak");
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 mLayersAdded = true;
2922 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002923 }
2924
Mathias Agopian96f08192010-06-02 23:28:45 -07002925 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002926 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002927
Dan Stoza7d89d062015-04-30 13:29:25 -07002928 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002929}
2930
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002931status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002932 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002933 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2934}
Robert Carr7f9b8992017-03-10 11:08:39 -08002935
chaviwca27f252018-02-06 16:46:39 -08002936status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2937 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002938 if (layer->isPendingRemoval()) {
2939 return NO_ERROR;
2940 }
2941
Robert Carr1f0a16a2016-10-24 16:27:39 -07002942 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002943 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002944 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002945 if (topLevelOnly) {
2946 return NO_ERROR;
2947 }
2948
Chia-I Wu98f1c102017-05-30 14:54:08 -07002949 sp<Layer> ancestor = p;
2950 while (ancestor->getParent() != nullptr) {
2951 ancestor = ancestor->getParent();
2952 }
2953 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2954 ALOGE("removeLayer called with a layer whose parent has been removed");
2955 return NAME_NOT_FOUND;
2956 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002957
2958 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002959 } else {
2960 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002961 }
2962
Robert Carr136e2f62017-02-08 17:54:29 -08002963 // As a matter of normal operation, the LayerCleaner will produce a second
2964 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2965 // so we will succeed in promoting it, but it's already been removed
2966 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2967 // otherwise something has gone wrong and we are leaking the layer.
2968 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002969 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2970 layer->getName().string(),
2971 (p != nullptr) ? p->getName().string() : "no-parent");
2972 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002973 } else if (index < 0) {
2974 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002975 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976
Chia-I Wuc6657022017-08-15 11:18:17 -07002977 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 mLayersPendingRemoval.add(layer);
2979 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002980 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002981 setTransactionFlags(eTransactionNeeded);
2982 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983}
2984
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002985uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002986 return android_atomic_release_load(&mTransactionFlags);
2987}
2988
Mathias Agopian3f844832013-08-07 21:24:32 -07002989uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2991}
2992
Mathias Agopian3f844832013-08-07 21:24:32 -07002993uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2995 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002996 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997 }
2998 return old;
2999}
3000
chaviwca27f252018-02-06 16:46:39 -08003001bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3002 for (const ComposerState& state : states) {
3003 // Here we need to check that the interface we're given is indeed
3004 // one of our own. A malicious client could give us a nullptr
3005 // IInterface, or one of its own or even one of our own but a
3006 // different type. All these situations would cause us to crash.
3007 if (state.client == nullptr) {
3008 return true;
3009 }
3010
3011 sp<IBinder> binder = IInterface::asBinder(state.client);
3012 if (binder == nullptr) {
3013 return true;
3014 }
3015
3016 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3017 return true;
3018 }
3019 }
3020 return false;
3021}
3022
Mathias Agopian8b33f032012-07-24 20:43:54 -07003023void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003024 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003025 const Vector<DisplayState>& displays,
3026 uint32_t flags)
3027{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003028 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003029 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003030 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003031
chaviwca27f252018-02-06 16:46:39 -08003032 if (containsAnyInvalidClientState(states)) {
3033 return;
3034 }
3035
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003036 if (flags & eAnimation) {
3037 // For window updates that are part of an animation we must wait for
3038 // previous animation "frames" to be handled.
3039 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003040 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003041 if (CC_UNLIKELY(err != NO_ERROR)) {
3042 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003043 // caller after a few seconds.
3044 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3045 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003046 mAnimTransactionPending = false;
3047 break;
3048 }
3049 }
3050 }
3051
chaviwca27f252018-02-06 16:46:39 -08003052 for (const DisplayState& display : displays) {
3053 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003054 }
3055
chaviwca27f252018-02-06 16:46:39 -08003056 for (const ComposerState& state : states) {
3057 transactionFlags |= setClientStateLocked(state);
3058 }
3059
3060 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3061 // as destroyed should only occur after setting all other states. This is to allow for a
3062 // child re-parent to happen before marking its original parent as destroyed (which would
3063 // then mark the child as destroyed).
3064 for (const ComposerState& state : states) {
3065 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003066 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003067
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003068 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3069 // anyway. This can be used as a flush mechanism for previous async transactions.
3070 // Empty animation transaction can be used to simulate back-pressure, so also force a
3071 // transaction for empty animation transactions.
3072 if (transactionFlags == 0 &&
3073 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003074 transactionFlags = eTransactionNeeded;
3075 }
3076
Mathias Agopian386aa982011-11-07 21:58:03 -08003077 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003078 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003079 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003080 }
Irvel468051e2016-06-13 16:44:44 -07003081
Mathias Agopian386aa982011-11-07 21:58:03 -08003082 // this triggers the transaction
3083 setTransactionFlags(transactionFlags);
3084
3085 // if this is a synchronous transaction, wait for it to take effect
3086 // before returning.
3087 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003088 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003089 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003090 if (flags & eAnimation) {
3091 mAnimTransactionPending = true;
3092 }
3093 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003094 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3095 if (CC_UNLIKELY(err != NO_ERROR)) {
3096 // just in case something goes wrong in SF, return to the
3097 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003098 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3099 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003100 break;
3101 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103 }
3104}
3105
Mathias Agopiane57f2922012-08-09 16:29:12 -07003106uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3107{
Jesse Hall9a143922012-10-04 16:29:19 -07003108 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3109 if (dpyIdx < 0)
3110 return 0;
3111
Mathias Agopiane57f2922012-08-09 16:29:12 -07003112 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003113 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003114 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003115 const uint32_t what = s.what;
3116 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003117 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003118 disp.surface = s.surface;
3119 flags |= eDisplayTransactionNeeded;
3120 }
3121 }
3122 if (what & DisplayState::eLayerStackChanged) {
3123 if (disp.layerStack != s.layerStack) {
3124 disp.layerStack = s.layerStack;
3125 flags |= eDisplayTransactionNeeded;
3126 }
3127 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003128 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003129 if (disp.orientation != s.orientation) {
3130 disp.orientation = s.orientation;
3131 flags |= eDisplayTransactionNeeded;
3132 }
3133 if (disp.frame != s.frame) {
3134 disp.frame = s.frame;
3135 flags |= eDisplayTransactionNeeded;
3136 }
3137 if (disp.viewport != s.viewport) {
3138 disp.viewport = s.viewport;
3139 flags |= eDisplayTransactionNeeded;
3140 }
3141 }
Michael Lentine47e45402014-07-18 15:34:25 -07003142 if (what & DisplayState::eDisplaySizeChanged) {
3143 if (disp.width != s.width) {
3144 disp.width = s.width;
3145 flags |= eDisplayTransactionNeeded;
3146 }
3147 if (disp.height != s.height) {
3148 disp.height = s.height;
3149 flags |= eDisplayTransactionNeeded;
3150 }
3151 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003152 }
3153 return flags;
3154}
3155
chaviwca27f252018-02-06 16:46:39 -08003156uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3157 const layer_state_t& s = composerState.state;
3158 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3159
Mathias Agopian13127d82013-03-05 17:47:11 -08003160 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003161 if (layer == nullptr) {
3162 return 0;
3163 }
3164
3165 if (layer->isPendingRemoval()) {
3166 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3167 return 0;
3168 }
3169
3170 uint32_t flags = 0;
3171
3172 const uint32_t what = s.what;
3173 bool geometryAppliesWithResize =
3174 what & layer_state_t::eGeometryAppliesWithResize;
3175 if (what & layer_state_t::ePositionChanged) {
3176 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3177 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003178 }
chaviw8b3871a2017-11-01 17:41:01 -07003179 }
3180 if (what & layer_state_t::eLayerChanged) {
3181 // NOTE: index needs to be calculated before we update the state
3182 const auto& p = layer->getParent();
3183 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003184 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003185 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003186 mCurrentState.layersSortedByZ.removeAt(idx);
3187 mCurrentState.layersSortedByZ.add(layer);
3188 // we need traversal (state changed)
3189 // AND transaction (list changed)
3190 flags |= eTransactionNeeded|eTraversalNeeded;
3191 }
chaviw8b3871a2017-11-01 17:41:01 -07003192 } else {
3193 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003194 flags |= eTransactionNeeded|eTraversalNeeded;
3195 }
3196 }
chaviw8b3871a2017-11-01 17:41:01 -07003197 }
3198 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003199 // NOTE: index needs to be calculated before we update the state
3200 const auto& p = layer->getParent();
3201 if (p == nullptr) {
3202 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3203 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3204 mCurrentState.layersSortedByZ.removeAt(idx);
3205 mCurrentState.layersSortedByZ.add(layer);
3206 // we need traversal (state changed)
3207 // AND transaction (list changed)
3208 flags |= eTransactionNeeded|eTraversalNeeded;
3209 }
3210 } else {
3211 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3212 flags |= eTransactionNeeded|eTraversalNeeded;
3213 }
chaviw8b3871a2017-11-01 17:41:01 -07003214 }
3215 }
3216 if (what & layer_state_t::eSizeChanged) {
3217 if (layer->setSize(s.w, s.h)) {
3218 flags |= eTraversalNeeded;
3219 }
3220 }
3221 if (what & layer_state_t::eAlphaChanged) {
3222 if (layer->setAlpha(s.alpha))
3223 flags |= eTraversalNeeded;
3224 }
3225 if (what & layer_state_t::eColorChanged) {
3226 if (layer->setColor(s.color))
3227 flags |= eTraversalNeeded;
3228 }
3229 if (what & layer_state_t::eMatrixChanged) {
3230 if (layer->setMatrix(s.matrix))
3231 flags |= eTraversalNeeded;
3232 }
3233 if (what & layer_state_t::eTransparentRegionChanged) {
3234 if (layer->setTransparentRegionHint(s.transparentRegion))
3235 flags |= eTraversalNeeded;
3236 }
3237 if (what & layer_state_t::eFlagsChanged) {
3238 if (layer->setFlags(s.flags, s.mask))
3239 flags |= eTraversalNeeded;
3240 }
3241 if (what & layer_state_t::eCropChanged) {
3242 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3243 flags |= eTraversalNeeded;
3244 }
3245 if (what & layer_state_t::eFinalCropChanged) {
3246 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3247 flags |= eTraversalNeeded;
3248 }
3249 if (what & layer_state_t::eLayerStackChanged) {
3250 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3251 // We only allow setting layer stacks for top level layers,
3252 // everything else inherits layer stack from its parent.
3253 if (layer->hasParent()) {
3254 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3255 layer->getName().string());
3256 } else if (idx < 0) {
3257 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3258 "that also does not appear in the top level layer list. Something"
3259 " has gone wrong.", layer->getName().string());
3260 } else if (layer->setLayerStack(s.layerStack)) {
3261 mCurrentState.layersSortedByZ.removeAt(idx);
3262 mCurrentState.layersSortedByZ.add(layer);
3263 // we need traversal (state changed)
3264 // AND transaction (list changed)
3265 flags |= eTransactionNeeded|eTraversalNeeded;
3266 }
3267 }
3268 if (what & layer_state_t::eDeferTransaction) {
3269 if (s.barrierHandle != nullptr) {
3270 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3271 } else if (s.barrierGbp != nullptr) {
3272 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3273 if (authenticateSurfaceTextureLocked(gbp)) {
3274 const auto& otherLayer =
3275 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3276 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3277 } else {
3278 ALOGE("Attempt to defer transaction to to an"
3279 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003280 }
3281 }
chaviw8b3871a2017-11-01 17:41:01 -07003282 // We don't trigger a traversal here because if no other state is
3283 // changed, we don't want this to cause any more work
3284 }
3285 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003286 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003287 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003288 if (!hadParent) {
3289 mCurrentState.layersSortedByZ.remove(layer);
3290 }
chaviw8b3871a2017-11-01 17:41:01 -07003291 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003292 }
chaviw8b3871a2017-11-01 17:41:01 -07003293 }
3294 if (what & layer_state_t::eReparentChildren) {
3295 if (layer->reparentChildren(s.reparentHandle)) {
3296 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003297 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 }
chaviw8b3871a2017-11-01 17:41:01 -07003299 if (what & layer_state_t::eDetachChildren) {
3300 layer->detachChildren();
3301 }
3302 if (what & layer_state_t::eOverrideScalingModeChanged) {
3303 layer->setOverrideScalingMode(s.overrideScalingMode);
3304 // We don't trigger a traversal here because if no other state is
3305 // changed, we don't want this to cause any more work
3306 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003307 return flags;
3308}
3309
chaviwca27f252018-02-06 16:46:39 -08003310void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3311 const layer_state_t& state = composerState.state;
3312 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3313
3314 sp<Layer> layer(client->getLayerUser(state.surface));
3315 if (layer == nullptr) {
3316 return;
3317 }
3318
3319 if (layer->isPendingRemoval()) {
3320 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3321 return;
3322 }
3323
3324 if (state.what & layer_state_t::eDestroySurface) {
3325 removeLayerLocked(mStateLock, layer);
3326 }
3327}
3328
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003329status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003330 const String8& name,
3331 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003332 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003333 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3334 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003336 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003337 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003338 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003339 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003340 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003341
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003342 status_t result = NO_ERROR;
3343
3344 sp<Layer> layer;
3345
Cody Northropbc755282017-03-31 12:00:08 -06003346 String8 uniqueName = getUniqueLayerName(name);
3347
Mathias Agopian3165cc22012-08-08 19:42:09 -07003348 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3349 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003350 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003351 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003352 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354 break;
chaviw13fdc492017-06-27 12:40:18 -07003355 case ISurfaceComposerClient::eFXSurfaceColor:
3356 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003357 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003358 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003359 break;
3360 default:
3361 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362 break;
3363 }
3364
Dan Stoza7d89d062015-04-30 13:29:25 -07003365 if (result != NO_ERROR) {
3366 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003368
Chia-I Wuab0c3192017-08-01 11:29:00 -07003369 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3370 // TODO b/64227542
3371 if (windowType == 441731) {
3372 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3373 layer->setPrimaryDisplayOnly();
3374 }
3375
Albert Chaulk479c60c2017-01-27 14:21:34 -05003376 layer->setInfo(windowType, ownerUid);
3377
Robert Carr1f0a16a2016-10-24 16:27:39 -07003378 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003379 if (result != NO_ERROR) {
3380 return result;
3381 }
Irvelffc9efc2016-07-27 15:16:37 -07003382 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003383
3384 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003385 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003386}
3387
Cody Northropbc755282017-03-31 12:00:08 -06003388String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3389{
3390 bool matchFound = true;
3391 uint32_t dupeCounter = 0;
3392
3393 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3394 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3395
3396 // Loop over layers until we're sure there is no matching name
3397 while (matchFound) {
3398 matchFound = false;
3399 mDrawingState.traverseInZOrder([&](Layer* layer) {
3400 if (layer->getName() == uniqueName) {
3401 matchFound = true;
3402 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3403 }
3404 });
3405 }
3406
3407 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3408
3409 return uniqueName;
3410}
3411
David Sodman0c69cad2017-08-21 12:12:51 -07003412status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003413 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3414 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003415{
3416 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003417 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003418 case PIXEL_FORMAT_TRANSPARENT:
3419 case PIXEL_FORMAT_TRANSLUCENT:
3420 format = PIXEL_FORMAT_RGBA_8888;
3421 break;
3422 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003423 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424 break;
3425 }
3426
David Sodman0c69cad2017-08-21 12:12:51 -07003427 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3428 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003429 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003430 *handle = layer->getHandle();
3431 *gbp = layer->getProducer();
3432 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003433 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003434
David Sodman0c69cad2017-08-21 12:12:51 -07003435 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003436 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437}
3438
chaviw13fdc492017-06-27 12:40:18 -07003439status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003440 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003441 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442{
chaviw13fdc492017-06-27 12:40:18 -07003443 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003444 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003445 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003446}
3447
Mathias Agopianac9fa422013-02-11 16:40:36 -08003448status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449{
Robert Carr9524cb32017-02-13 11:32:32 -08003450 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003451 status_t err = NO_ERROR;
3452 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003453 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003454 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003455 err = removeLayer(l);
3456 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3457 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003458 }
3459 return err;
3460}
3461
Mathias Agopian13127d82013-03-05 17:47:11 -08003462status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003463{
Mathias Agopian67106042013-03-14 19:18:13 -07003464 // called by ~LayerCleaner() when all references to the IBinder (handle)
3465 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003466 sp<Layer> l = layer.promote();
3467 if (l == nullptr) {
3468 // The layer has already been removed, carry on
3469 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003470 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003471 // If we have a parent, then we can continue to live as long as it does.
3472 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003473}
3474
Mathias Agopianb60314a2012-04-10 22:09:54 -07003475// ---------------------------------------------------------------------------
3476
Andy McFadden13a082e2012-08-24 10:16:42 -07003477void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003478 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003479 Vector<ComposerState> state;
3480 Vector<DisplayState> displays;
3481 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003482 d.what = DisplayState::eDisplayProjectionChanged |
3483 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003484 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003485 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003486 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003487 d.frame.makeInvalid();
3488 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003489 d.width = 0;
3490 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003491 displays.add(d);
3492 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003493 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3494 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003495
David Sodman105b7dc2017-11-04 20:28:14 -07003496 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003497 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003498 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003499
Brian Andersond0010582017-03-07 13:20:31 -08003500 // Use phase of 0 since phase is not known.
3501 // Use latency of 0, which will snap to the ideal latency.
3502 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003503}
3504
3505void SurfaceFlinger::initializeDisplays() {
3506 class MessageScreenInitialized : public MessageBase {
3507 SurfaceFlinger* flinger;
3508 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003509 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003510 virtual bool handler() {
3511 flinger->onInitializeDisplays();
3512 return true;
3513 }
3514 };
3515 sp<MessageBase> msg = new MessageScreenInitialized(this);
3516 postMessageAsync(msg); // we may be called from main thread, use async message
3517}
3518
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003519void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003520 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003521 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3522 this);
3523 int32_t type = hw->getDisplayType();
3524 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003525
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003526 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003527 return;
3528 }
3529
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 hw->setPowerMode(mode);
3531 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3532 ALOGW("Trying to set power mode for virtual display");
3533 return;
3534 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003535
Irvelffc9efc2016-07-27 15:16:37 -07003536 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003537 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003538 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3539 if (idx < 0) {
3540 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3541 return;
3542 }
3543 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3544 }
3545
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003547 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003548 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003549 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3550 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003551 // FIXME: eventthread only knows about the main display right now
3552 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003553 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003556 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003557 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003558 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003559
3560 struct sched_param param = {0};
3561 param.sched_priority = 1;
3562 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3563 ALOGW("Couldn't set SCHED_FIFO on display on");
3564 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003565 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003566 // Turn off the display
3567 struct sched_param param = {0};
3568 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3569 ALOGW("Couldn't set SCHED_OTHER on display off");
3570 }
3571
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003572 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3573 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003574 disableHardwareVsync(true); // also cancels any in-progress resync
3575
Mathias Agopiancde87a32012-09-13 14:09:01 -07003576 // FIXME: eventthread only knows about the main display right now
3577 mEventThread->onScreenReleased();
3578 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003579
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003580 getHwComposer().setPowerMode(type, mode);
3581 mVisibleRegionsDirty = true;
3582 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003583 } else if (mode == HWC_POWER_MODE_DOZE ||
3584 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003585 // Update display while dozing
3586 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003587 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3588 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003589 // FIXME: eventthread only knows about the main display right now
3590 mEventThread->onScreenAcquired();
3591 resyncToHardwareVsync(true);
3592 }
3593 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3594 // Leave display going to doze
3595 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3596 disableHardwareVsync(true); // also cancels any in-progress resync
3597 // FIXME: eventthread only knows about the main display right now
3598 mEventThread->onScreenReleased();
3599 }
3600 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003601 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003602 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003603 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003604 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003605}
3606
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003607void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3608 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003609 SurfaceFlinger& mFlinger;
3610 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003611 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003612 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003613 MessageSetPowerMode(SurfaceFlinger& flinger,
3614 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3615 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003616 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003617 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003618 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003619 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003620 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003621 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003622 ALOGW("Attempt to set power mode = %d for virtual display",
3623 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003624 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003625 mFlinger.setPowerModeInternal(
3626 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003627 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003628 return true;
3629 }
3630 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003631 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003632 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003633}
3634
3635// ---------------------------------------------------------------------------
3636
Lloyd Pique755e3192018-01-31 16:46:15 -08003637status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3638 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003639 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003640
Mathias Agopianbd115332013-04-18 16:41:04 -07003641 IPCThreadState* ipc = IPCThreadState::self();
3642 const int pid = ipc->getCallingPid();
3643 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003644
Mathias Agopianbd115332013-04-18 16:41:04 -07003645 if ((uid != AID_SHELL) &&
3646 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003647 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003648 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003649 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003650 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003651 // (this would indicate SF is stuck, but we want to be able to
3652 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003653 status_t err = mStateLock.timedLock(s2ns(1));
3654 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003655 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003656 result.appendFormat(
3657 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3658 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003659 }
3660
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003661 bool dumpAll = true;
3662 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003663 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003664
3665 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003666 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003667 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3668 dumpAll = false;
3669 }
3670
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003671 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003672 if ((index < numArgs) &&
3673 (args[index] == String16("--list"))) {
3674 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003675 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003676 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003677 }
3678
3679 if ((index < numArgs) &&
3680 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003681 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003682 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003683 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003684 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003685
3686 if ((index < numArgs) &&
3687 (args[index] == String16("--latency-clear"))) {
3688 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003689 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003690 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003691 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003692
3693 if ((index < numArgs) &&
3694 (args[index] == String16("--dispsync"))) {
3695 index++;
3696 mPrimaryDispSync.dump(result);
3697 dumpAll = false;
3698 }
Dan Stozab90cf072015-03-05 11:05:59 -08003699
3700 if ((index < numArgs) &&
3701 (args[index] == String16("--static-screen"))) {
3702 index++;
3703 dumpStaticScreenStats(result);
3704 dumpAll = false;
3705 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003706
3707 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003708 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003709 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003710 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003711 dumpAll = false;
3712 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003713
3714 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3715 index++;
3716 dumpWideColorInfo(result);
3717 dumpAll = false;
3718 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003719
3720 if ((index < numArgs) &&
3721 (args[index] == String16("--enable-layer-stats"))) {
3722 index++;
3723 mLayerStats.enable();
3724 dumpAll = false;
3725 }
3726
3727 if ((index < numArgs) &&
3728 (args[index] == String16("--disable-layer-stats"))) {
3729 index++;
3730 mLayerStats.disable();
3731 dumpAll = false;
3732 }
3733
3734 if ((index < numArgs) &&
3735 (args[index] == String16("--clear-layer-stats"))) {
3736 index++;
3737 mLayerStats.clear();
3738 dumpAll = false;
3739 }
3740
3741 if ((index < numArgs) &&
3742 (args[index] == String16("--dump-layer-stats"))) {
3743 index++;
3744 mLayerStats.dump(result);
3745 dumpAll = false;
3746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003748
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003749 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003750 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003751 }
3752
Mathias Agopian9795c422009-08-26 16:36:26 -07003753 if (locked) {
3754 mStateLock.unlock();
3755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756 }
3757 write(fd, result.string(), result.size());
3758 return NO_ERROR;
3759}
3760
Dan Stozac7014012014-02-14 15:03:43 -08003761void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3762 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003763{
Robert Carr2047fae2016-11-28 14:09:09 -08003764 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003765 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003766 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003767}
3768
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003769void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003770 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003771{
3772 String8 name;
3773 if (index < args.size()) {
3774 name = String8(args[index]);
3775 index++;
3776 }
3777
David Sodman105b7dc2017-11-04 20:28:14 -07003778 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003779 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003780 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003781
3782 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003783 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003784 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003785 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003786 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003787 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003788 }
Robert Carr2047fae2016-11-28 14:09:09 -08003789 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003790 }
3791}
3792
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003793void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003794 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003795{
3796 String8 name;
3797 if (index < args.size()) {
3798 name = String8(args[index]);
3799 index++;
3800 }
3801
Robert Carr2047fae2016-11-28 14:09:09 -08003802 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003803 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003804 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003805 }
Robert Carr2047fae2016-11-28 14:09:09 -08003806 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003807
Svetoslavd85084b2014-03-20 10:28:31 -07003808 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003809}
3810
Jamie Gennis6547ff42013-07-16 20:12:42 -07003811// This should only be called from the main thread. Otherwise it would need
3812// the lock and should use mCurrentState rather than mDrawingState.
3813void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003814 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003815 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003816 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003817
3818 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3819}
3820
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003821void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003822{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003823 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003824
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003825 if (isLayerTripleBufferingDisabled())
3826 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003827
3828 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003829 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003830 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003831 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003832 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3833 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003834 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003835}
3836
Dan Stozab90cf072015-03-05 11:05:59 -08003837void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3838{
3839 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003840 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3841 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003842 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003843 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003844 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3845 b + 1, bucketTimeSec, percent);
3846 }
David Sodman4a36e932017-11-07 14:29:47 -08003847 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003848 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003849 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003850 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003851 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003852}
3853
Dan Stozae77c7662016-05-13 11:37:28 -07003854void SurfaceFlinger::recordBufferingStats(const char* layerName,
3855 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003856 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3857 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003858 for (const auto& segment : history) {
3859 if (!segment.usedThirdBuffer) {
3860 stats.twoBufferTime += segment.totalTime;
3861 }
3862 if (segment.occupancyAverage < 1.0f) {
3863 stats.doubleBufferedTime += segment.totalTime;
3864 } else if (segment.occupancyAverage < 2.0f) {
3865 stats.tripleBufferedTime += segment.totalTime;
3866 }
3867 ++stats.numSegments;
3868 stats.totalTime += segment.totalTime;
3869 }
3870}
3871
Brian Andersond6927fb2016-07-23 23:37:30 -07003872void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3873 result.appendFormat("Layer frame timestamps:\n");
3874
3875 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3876 const size_t count = currentLayers.size();
3877 for (size_t i=0 ; i<count ; i++) {
3878 currentLayers[i]->dumpFrameEvents(result);
3879 }
3880}
3881
Dan Stozae77c7662016-05-13 11:37:28 -07003882void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3883 result.append("Buffering stats:\n");
3884 result.append(" [Layer name] <Active time> <Two buffer> "
3885 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003886 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003887 typedef std::tuple<std::string, float, float, float> BufferTuple;
3888 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003889 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003890 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003891 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003892 if (stats.numSegments == 0) {
3893 continue;
3894 }
3895 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3896 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3897 stats.totalTime;
3898 float doubleBufferRatio = static_cast<float>(
3899 stats.doubleBufferedTime) / stats.totalTime;
3900 float tripleBufferRatio = static_cast<float>(
3901 stats.tripleBufferedTime) / stats.totalTime;
3902 sorted.insert({activeTime, {name, twoBufferRatio,
3903 doubleBufferRatio, tripleBufferRatio}});
3904 }
3905 for (const auto& sortedPair : sorted) {
3906 float activeTime = sortedPair.first;
3907 const BufferTuple& values = sortedPair.second;
3908 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3909 std::get<0>(values).c_str(), activeTime,
3910 std::get<1>(values), std::get<2>(values),
3911 std::get<3>(values));
3912 }
3913 result.append("\n");
3914}
3915
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003916void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3917 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003918 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003919
3920 // TODO: print out if wide-color mode is active or not
3921
3922 for (size_t d = 0; d < mDisplays.size(); d++) {
3923 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3924 int32_t hwcId = displayDevice->getHwcDisplayId();
3925 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3926 continue;
3927 }
3928
3929 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003930 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003931 for (auto&& mode : modes) {
3932 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3933 }
3934
Peiyong Lina52f0292018-03-14 17:26:31 -07003935 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003936 result.appendFormat(" Current color mode: %s (%d)\n",
3937 decodeColorMode(currentMode).c_str(), currentMode);
3938 }
3939 result.append("\n");
3940}
3941
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003942LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003943 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003944 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3945 const State& state = useDrawing ? mDrawingState : mCurrentState;
3946 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003947 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003948 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003949 });
3950
3951 return layersProto;
3952}
3953
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003954LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
3955 LayersProto layersProto;
3956
3957 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
3958 SizeProto* resolution = layersProto.mutable_resolution();
3959 resolution->set_w(displayDevice->getWidth());
3960 resolution->set_h(displayDevice->getHeight());
3961
3962 mDrawingState.traverseInZOrder([&](Layer* layer) {
3963 if (!layer->visibleRegion.isEmpty() &&
3964 layer->getBE().mHwcLayers.count(hwcId)) {
3965 LayerProto* layerProto = layersProto.add_layers();
3966 layer->writeToProto(layerProto, hwcId);
3967 }
3968 });
3969
3970 return layersProto;
3971}
3972
Mathias Agopian74d211a2013-04-22 16:55:35 +02003973void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3974 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003976 bool colorize = false;
3977 if (index < args.size()
3978 && (args[index] == String16("--color"))) {
3979 colorize = true;
3980 index++;
3981 }
3982
3983 Colorizer colorizer(colorize);
3984
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003985 // figure out if we're stuck somewhere
3986 const nsecs_t now = systemTime();
3987 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3988 const nsecs_t inTransaction(mDebugInTransaction);
3989 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3990 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3991
3992 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003993 * Dump library configuration.
3994 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003995
3996 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003997 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003998 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003999 appendSfConfigString(result);
4000 appendUiConfigString(result);
4001 appendGuiConfigString(result);
4002 result.append("\n");
4003
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004004 result.append("\nWide-Color information:\n");
4005 dumpWideColorInfo(result);
4006
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004007 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004008 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004009 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004010 result.append(SyncFeatures::getInstance().toString());
4011 result.append("\n");
4012
David Sodman105b7dc2017-11-04 20:28:14 -07004013 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004014
Andy McFadden41d67d72014-04-25 16:58:34 -07004015 colorizer.bold(result);
4016 result.append("DispSync configuration: ");
4017 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004018 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004019 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004020 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004021 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004022 result.append("\n");
4023
Dan Stozab90cf072015-03-05 11:05:59 -08004024 // Dump static screen stats
4025 result.append("\n");
4026 dumpStaticScreenStats(result);
4027 result.append("\n");
4028
Dan Stozae77c7662016-05-13 11:37:28 -07004029 dumpBufferingStats(result);
4030
Andy McFadden4803b742012-09-24 19:07:20 -07004031 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032 * Dump the visible layer list
4033 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004034 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004035 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004036 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004037
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004038 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004039 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4040 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004041
4042 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004043 * Dump Display state
4044 */
4045
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004046 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004047 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004048 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004049 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4050 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004051 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004052 }
4053
4054 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004055 * Dump SurfaceFlinger global state
4056 */
4057
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004058 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004059 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004060 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004061
Mathias Agopian888c8222012-08-04 21:10:38 -07004062 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004063 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004064
David Sodmanbc815282017-11-05 18:57:52 -08004065 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004066
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004067 if (hw) {
4068 hw->undefinedRegion.dump(result, "undefinedRegion");
4069 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4070 hw->getOrientation(), hw->isDisplayOn());
4071 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004072 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004073 " last eglSwapBuffers() time: %f us\n"
4074 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004075 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004076 " refresh-rate : %f fps\n"
4077 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004078 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004079 " gpu_to_cpu_unsupported : %d\n"
4080 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004081 mLastSwapBufferTime/1000.0,
4082 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004083 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004084 1e9 / activeConfig->getVsyncPeriod(),
4085 activeConfig->getDpiX(),
4086 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004087 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004088
Mathias Agopian74d211a2013-04-22 16:55:35 +02004089 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004090 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004091
Mathias Agopian74d211a2013-04-22 16:55:35 +02004092 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004093 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004094
4095 /*
4096 * VSYNC state
4097 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004098 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004099 result.append("\n");
4100
4101 /*
4102 * HWC layer minidump
4103 */
4104 for (size_t d = 0; d < mDisplays.size(); d++) {
4105 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4106 int32_t hwcId = displayDevice->getHwcDisplayId();
4107 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4108 continue;
4109 }
4110
4111 result.appendFormat("Display %d HWC layers:\n", hwcId);
4112 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004113 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004114 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004115 });
Dan Stozae22aec72016-08-01 13:20:59 -07004116 result.append("\n");
4117 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004118
4119 /*
4120 * Dump HWComposer state
4121 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004122 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004123 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004124 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004125 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004126 result.appendFormat(" h/w composer %s\n",
4127 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004128 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004129
4130 /*
4131 * Dump gralloc state
4132 */
4133 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4134 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004135
4136 /*
4137 * Dump VrFlinger state if in use.
4138 */
4139 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4140 result.append("VrFlinger state:\n");
4141 result.append(mVrFlinger->Dump().c_str());
4142 result.append("\n");
4143 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004144}
4145
Mathias Agopian13127d82013-03-05 17:47:11 -08004146const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004147SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004148 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004149 wp<IBinder> dpy;
4150 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4151 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4152 dpy = mDisplays.keyAt(i);
4153 break;
4154 }
4155 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004156 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004157 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4158 // Just use the primary display so we have something to return
4159 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4160 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004161 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004162}
4163
Keun young Park63f165f2012-08-31 10:53:36 -07004164bool SurfaceFlinger::startDdmConnection()
4165{
4166 void* libddmconnection_dso =
4167 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4168 if (!libddmconnection_dso) {
4169 return false;
4170 }
4171 void (*DdmConnection_start)(const char* name);
4172 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004173 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004174 if (!DdmConnection_start) {
4175 dlclose(libddmconnection_dso);
4176 return false;
4177 }
4178 (*DdmConnection_start)(getServiceName());
4179 return true;
4180}
4181
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004182status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 switch (code) {
4184 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004185 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004187 case CLEAR_ANIMATION_FRAME_STATS:
4188 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004189 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004190 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004191 case ENABLE_VSYNC_INJECTIONS:
4192 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 {
4194 // codes that require permission check
4195 IPCThreadState* ipc = IPCThreadState::self();
4196 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004197 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004198 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004199 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004200 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004201 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004203 break;
4204 }
Robert Carr1db73f62016-12-21 12:58:51 -08004205 /*
4206 * Calling setTransactionState is safe, because you need to have been
4207 * granted a reference to Client* and Handle* to do anything with it.
4208 *
4209 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4210 */
4211 case SET_TRANSACTION_STATE:
4212 case CREATE_SCOPED_CONNECTION:
4213 {
4214 return OK;
4215 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004216 case CAPTURE_SCREEN:
4217 {
4218 // codes that require permission check
4219 IPCThreadState* ipc = IPCThreadState::self();
4220 const int pid = ipc->getCallingPid();
4221 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004222 if ((uid != AID_GRAPHICS) &&
4223 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004224 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004225 return PERMISSION_DENIED;
4226 }
4227 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 }
chaviwa76b2712017-09-20 12:02:26 -07004229 case CAPTURE_LAYERS: {
4230 IPCThreadState* ipc = IPCThreadState::self();
4231 const int pid = ipc->getCallingPid();
4232 const int uid = ipc->getCallingUid();
4233 if ((uid != AID_GRAPHICS) &&
4234 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4235 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4236 return PERMISSION_DENIED;
4237 }
4238 break;
4239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004240 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004241 return OK;
4242}
4243
4244status_t SurfaceFlinger::onTransact(
4245 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4246{
4247 status_t credentialCheck = CheckTransactCodeCredentials(code);
4248 if (credentialCheck != OK) {
4249 return credentialCheck;
4250 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004251
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004252 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4253 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004254 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004255 IPCThreadState* ipc = IPCThreadState::self();
4256 const int uid = ipc->getCallingUid();
4257 if (CC_UNLIKELY(uid != AID_SYSTEM
4258 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004259 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004260 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004261 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004262 return PERMISSION_DENIED;
4263 }
4264 int n;
4265 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004266 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004267 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004268 return NO_ERROR;
4269 case 1002: // SHOW_UPDATES
4270 n = data.readInt32();
4271 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004272 invalidateHwcGeometry();
4273 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004275 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004276 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004277 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004278 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004279 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004280 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004281 setTransactionFlags(
4282 eTransactionNeeded|
4283 eDisplayTransactionNeeded|
4284 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004285 return NO_ERROR;
4286 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004287 case 1006:{ // send empty update
4288 signalRefresh();
4289 return NO_ERROR;
4290 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004291 case 1008: // toggle use of hw composer
4292 n = data.readInt32();
4293 mDebugDisableHWC = n ? 1 : 0;
4294 invalidateHwcGeometry();
4295 repaintEverything();
4296 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004297 case 1009: // toggle use of transform hint
4298 n = data.readInt32();
4299 mDebugDisableTransformHint = n ? 1 : 0;
4300 invalidateHwcGeometry();
4301 repaintEverything();
4302 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004304 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305 reply->writeInt32(0);
4306 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004307 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004308 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004309 return NO_ERROR;
4310 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004311 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004312 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004313 return NO_ERROR;
4314 }
4315 case 1014: {
4316 // daltonize
4317 n = data.readInt32();
4318 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004319 case 1:
4320 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4321 break;
4322 case 2:
4323 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4324 break;
4325 case 3:
4326 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4327 break;
4328 default:
4329 mDaltonizer.setType(ColorBlindnessType::None);
4330 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004331 }
4332 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004333 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004334 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004335 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004336 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004337 invalidateHwcGeometry();
4338 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004339 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004340 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004341 case 1015: {
4342 // apply a color matrix
4343 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004344 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004345 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004346 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004347 for (size_t j = 0; j < 4; j++) {
4348 mColorMatrix[i][j] = data.readFloat();
4349 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004350 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004351 } else {
4352 mColorMatrix = mat4();
4353 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004354
4355 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4356 // the division by w in the fragment shader
4357 float4 lastRow(transpose(mColorMatrix)[3]);
4358 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4359 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4360 }
4361
Alan Viverette9c5a3332013-09-12 20:04:35 -07004362 invalidateHwcGeometry();
4363 repaintEverything();
4364 return NO_ERROR;
4365 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004366 // This is an experimental interface
4367 // Needs to be shifted to proper binder interface when we productize
4368 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004369 n = data.readInt32();
4370 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004371 return NO_ERROR;
4372 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004373 case 1017: {
4374 n = data.readInt32();
4375 mForceFullDamage = static_cast<bool>(n);
4376 return NO_ERROR;
4377 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004378 case 1018: { // Modify Choreographer's phase offset
4379 n = data.readInt32();
4380 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4381 return NO_ERROR;
4382 }
4383 case 1019: { // Modify SurfaceFlinger's phase offset
4384 n = data.readInt32();
4385 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4386 return NO_ERROR;
4387 }
Irvel468051e2016-06-13 16:44:44 -07004388 case 1020: { // Layer updates interceptor
4389 n = data.readInt32();
4390 if (n) {
4391 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004392 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004393 }
4394 else{
4395 ALOGV("Interceptor disabled");
4396 mInterceptor.disable();
4397 }
4398 return NO_ERROR;
4399 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004400 case 1021: { // Disable HWC virtual displays
4401 n = data.readInt32();
4402 mUseHwcVirtualDisplays = !n;
4403 return NO_ERROR;
4404 }
Romain Guy0147a172017-06-01 13:53:56 -07004405 case 1022: { // Set saturation boost
4406 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4407
4408 invalidateHwcGeometry();
4409 repaintEverything();
4410 return NO_ERROR;
4411 }
Romain Guy54f154a2017-10-24 21:40:32 +01004412 case 1023: { // Set native mode
4413 mForceNativeColorMode = data.readInt32() == 1;
4414
4415 invalidateHwcGeometry();
4416 repaintEverything();
4417 return NO_ERROR;
4418 }
4419 case 1024: { // Is wide color gamut rendering/color management supported?
4420 reply->writeBool(hasWideColorDisplay);
4421 return NO_ERROR;
4422 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004423 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004424 n = data.readInt32();
4425 if (n) {
4426 ALOGV("LayerTracing enabled");
4427 mTracing.enable();
4428 doTracing("tracing.enable");
4429 reply->writeInt32(NO_ERROR);
4430 } else {
4431 ALOGV("LayerTracing disabled");
4432 status_t err = mTracing.disable();
4433 reply->writeInt32(err);
4434 }
4435 return NO_ERROR;
4436 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004437 case 1026: { // Get layer tracing status
4438 reply->writeBool(mTracing.isEnabled());
4439 return NO_ERROR;
4440 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 }
4442 }
4443 return err;
4444}
4445
Steven Thomas6d8110b2017-08-31 18:24:21 -07004446void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004447 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004448 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004449}
4450
Steven Thomas6d8110b2017-08-31 18:24:21 -07004451void SurfaceFlinger::repaintEverything() {
4452 ConditionalLock _l(mStateLock,
4453 std::this_thread::get_id() != mMainThreadId);
4454 repaintEverythingLocked();
4455}
4456
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004457// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4458class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004459public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004460 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4461 ~WindowDisconnector() {
4462 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004463 }
4464
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004465private:
4466 ANativeWindow* mWindow;
4467 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004468};
4469
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004470status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4471 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4472 int32_t minLayerZ, int32_t maxLayerZ,
4473 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004474 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004475 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004476
chaviwa76b2712017-09-20 12:02:26 -07004477 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4478
4479 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4480 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4481
4482 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4483 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004484 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004485}
4486
4487status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004488 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004489 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004490 ATRACE_CALL();
4491
4492 class LayerRenderArea : public RenderArea {
4493 public:
Robert Carr578038f2018-03-09 12:25:24 -08004494 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4495 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4496 : RenderArea(reqHeight, reqWidth),
4497 mLayer(layer),
4498 mCrop(crop),
4499 mFlinger(flinger),
4500 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004501 Rect getBounds() const override {
4502 const Layer::State& layerState(mLayer->getDrawingState());
4503 return Rect(layerState.active.w, layerState.active.h);
4504 }
4505 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4506 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4507 bool isSecure() const override { return false; }
4508 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004509 const Transform& getTransform() const { return mTransform; }
4510
4511 class ReparentForDrawing {
4512 public:
4513 const sp<Layer>& oldParent;
4514 const sp<Layer>& newParent;
4515
4516 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4517 : oldParent(oldParent), newParent(newParent) {
4518 oldParent->reparentChildrenForDrawing(newParent);
4519 }
4520 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4521 };
4522
4523 void render(std::function<void()> drawLayers) override {
4524 if (!mChildrenOnly) {
4525 mTransform = mLayer->getTransform().inverse();
4526 drawLayers();
4527 } else {
4528 Rect bounds = getBounds();
4529 screenshotParentLayer =
4530 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4531 bounds.getWidth(), bounds.getHeight(), 0);
4532
4533 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4534 drawLayers();
4535 }
4536 }
chaviwa76b2712017-09-20 12:02:26 -07004537
chaviw7206d492017-11-10 16:16:12 -08004538 Rect getSourceCrop() const override {
4539 if (mCrop.isEmpty()) {
4540 return getBounds();
4541 } else {
4542 return mCrop;
4543 }
4544 }
chaviwa76b2712017-09-20 12:02:26 -07004545 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004546 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004547
4548 private:
chaviw7206d492017-11-10 16:16:12 -08004549 const sp<Layer> mLayer;
4550 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004551
4552 // In the "childrenOnly" case we reparent the children to a screenshot
4553 // layer which has no properties set and which does not draw.
4554 sp<ContainerLayer> screenshotParentLayer;
4555 Transform mTransform;
4556
4557 SurfaceFlinger* mFlinger;
4558 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004559 };
4560
4561 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4562 auto parent = layerHandle->owner.promote();
4563
chaviw7206d492017-11-10 16:16:12 -08004564 if (parent == nullptr || parent->isPendingRemoval()) {
4565 ALOGE("captureLayers called with a removed parent");
4566 return NAME_NOT_FOUND;
4567 }
4568
Robert Carr578038f2018-03-09 12:25:24 -08004569 const int uid = IPCThreadState::self()->getCallingUid();
4570 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4571 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4572 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4573 return PERMISSION_DENIED;
4574 }
4575
chaviw7206d492017-11-10 16:16:12 -08004576 Rect crop(sourceCrop);
4577 if (sourceCrop.width() <= 0) {
4578 crop.left = 0;
4579 crop.right = parent->getCurrentState().active.w;
4580 }
4581
4582 if (sourceCrop.height() <= 0) {
4583 crop.top = 0;
4584 crop.bottom = parent->getCurrentState().active.h;
4585 }
4586
4587 int32_t reqWidth = crop.width() * frameScale;
4588 int32_t reqHeight = crop.height() * frameScale;
4589
Robert Carr578038f2018-03-09 12:25:24 -08004590 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004591
Robert Carr578038f2018-03-09 12:25:24 -08004592 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004593 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4594 if (!layer->isVisible()) {
4595 return;
Robert Carr578038f2018-03-09 12:25:24 -08004596 } else if (childrenOnly && layer == parent.get()) {
4597 return;
chaviwa76b2712017-09-20 12:02:26 -07004598 }
4599 visitor(layer);
4600 });
4601 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004602 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004603}
4604
4605status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4606 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004607 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004608 bool useIdentityTransform) {
4609 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004610
chaviwa76b2712017-09-20 12:02:26 -07004611 renderArea.updateDimensions();
4612
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004613 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4614 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4615 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4616 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004617
4618 // This mutex protects syncFd and captureResult for communication of the return values from the
4619 // main thread back to this Binder thread
4620 std::mutex captureMutex;
4621 std::condition_variable captureCondition;
4622 std::unique_lock<std::mutex> captureLock(captureMutex);
4623 int syncFd = -1;
4624 std::optional<status_t> captureResult;
4625
Robert Carr03480e22018-01-04 16:02:06 -08004626 const int uid = IPCThreadState::self()->getCallingUid();
4627 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4628
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004629 sp<LambdaMessage> message = new LambdaMessage([&]() {
4630 // If there is a refresh pending, bug out early and tell the binder thread to try again
4631 // after the refresh.
4632 if (mRefreshPending) {
4633 ATRACE_NAME("Skipping screenshot for now");
4634 std::unique_lock<std::mutex> captureLock(captureMutex);
4635 captureResult = std::make_optional<status_t>(EAGAIN);
4636 captureCondition.notify_one();
4637 return;
4638 }
4639
4640 status_t result = NO_ERROR;
4641 int fd = -1;
4642 {
4643 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004644 renderArea.render([&]() {
4645 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4646 useIdentityTransform, forSystem, &fd);
4647 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004648 }
4649
4650 {
4651 std::unique_lock<std::mutex> captureLock(captureMutex);
4652 syncFd = fd;
4653 captureResult = std::make_optional<status_t>(result);
4654 captureCondition.notify_one();
4655 }
4656 });
4657
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004658 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004659 if (result == NO_ERROR) {
4660 captureCondition.wait(captureLock, [&]() { return captureResult; });
4661 while (*captureResult == EAGAIN) {
4662 captureResult.reset();
4663 result = postMessageAsync(message);
4664 if (result != NO_ERROR) {
4665 return result;
4666 }
4667 captureCondition.wait(captureLock, [&]() { return captureResult; });
4668 }
4669 result = *captureResult;
4670 }
4671
4672 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004673 sync_wait(syncFd, -1);
4674 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004675 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004676
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004677 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004678}
4679
chaviwa76b2712017-09-20 12:02:26 -07004680void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4681 TraverseLayersFunction traverseLayers, bool yswap,
4682 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004683 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004684
Lloyd Pique144e1162017-12-20 16:44:52 -08004685 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004686
4687 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004688 const auto raWidth = renderArea.getWidth();
4689 const auto raHeight = renderArea.getHeight();
4690
4691 const auto reqWidth = renderArea.getReqWidth();
4692 const auto reqHeight = renderArea.getReqHeight();
4693 Rect sourceCrop = renderArea.getSourceCrop();
4694
4695 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4696 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004697
Dan Stozac1879002014-05-22 15:59:05 -07004698 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004699 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004700 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004701 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004702 }
4703
4704 // ensure that sourceCrop is inside screen
4705 if (sourceCrop.left < 0) {
4706 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4707 }
chaviwa76b2712017-09-20 12:02:26 -07004708 if (sourceCrop.right > raWidth) {
4709 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004710 }
4711 if (sourceCrop.top < 0) {
4712 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4713 }
chaviwa76b2712017-09-20 12:02:26 -07004714 if (sourceCrop.bottom > raHeight) {
4715 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004716 }
4717
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004718 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004719 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004720 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004721 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4722 }
4723 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004724
Mathias Agopian180f10d2013-04-10 22:55:41 -07004725 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004726 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004727
4728 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004729 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4730 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004731 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004732
4733 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004734 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004735
chaviwa76b2712017-09-20 12:02:26 -07004736 traverseLayers([&](Layer* layer) {
4737 if (filtering) layer->setFiltering(true);
4738 layer->draw(renderArea, useIdentityTransform);
4739 if (filtering) layer->setFiltering(false);
4740 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004741}
4742
chaviwa76b2712017-09-20 12:02:26 -07004743status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4744 TraverseLayersFunction traverseLayers,
4745 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004746 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004747 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004748 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004749 ATRACE_CALL();
4750
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004751 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004752
4753 traverseLayers([&](Layer* layer) {
4754 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4755 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004756
Robert Carr03480e22018-01-04 16:02:06 -08004757 // We allow the system server to take screenshots of secure layers for
4758 // use in situations like the Screen-rotation animation and place
4759 // the impetus on WindowManager to not persist them.
4760 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004761 ALOGW("FB is protected: PERMISSION_DENIED");
4762 return PERMISSION_DENIED;
4763 }
4764
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004765 // this binds the given EGLImage as a framebuffer for the
4766 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004767 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004768 if (bufferBond.getStatus() != NO_ERROR) {
4769 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004770 return INVALID_OPERATION;
4771 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004772
Dan Stozaabcda352017-06-01 14:37:39 -07004773 // this will in fact render into our dequeued buffer
4774 // via an FBO, which means we didn't have to create
4775 // an EGLSurface and therefore we're not
4776 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004777 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004778
Dan Stozaabcda352017-06-01 14:37:39 -07004779 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004780 getRenderEngine().finish();
4781 *outSyncFd = -1;
4782
chaviwa76b2712017-09-20 12:02:26 -07004783 const auto reqWidth = renderArea.getReqWidth();
4784 const auto reqHeight = renderArea.getReqHeight();
4785
Dan Stozaabcda352017-06-01 14:37:39 -07004786 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4787 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004788 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004789 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004790 } else {
4791 base::unique_fd syncFd = getRenderEngine().flush();
4792 if (syncFd < 0) {
4793 getRenderEngine().finish();
4794 }
4795 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004796 }
4797
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004798 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004799}
4800
Mathias Agopiand5556842013-09-19 17:08:37 -07004801void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004802 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004803 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004804 for (size_t y = 0; y < h; y++) {
4805 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4806 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004807 if (p[x] != 0xFF000000) return;
4808 }
4809 }
chaviwa76b2712017-09-20 12:02:26 -07004810 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004811
Robert Carr2047fae2016-11-28 14:09:09 -08004812 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004813 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004814 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004815 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4816 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4817 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4818 static_cast<float>(state.color.a));
4819 i++;
4820 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004821 }
4822}
4823
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004824// ---------------------------------------------------------------------------
4825
Dan Stoza412903f2017-04-27 13:42:17 -07004826void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4827 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004828}
4829
Dan Stoza412903f2017-04-27 13:42:17 -07004830void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4831 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004832}
4833
chaviwa76b2712017-09-20 12:02:26 -07004834void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4835 int32_t maxLayerZ,
4836 const LayerVector::Visitor& visitor) {
4837 // We loop through the first level of layers without traversing,
4838 // as we need to interpret min/max layer Z in the top level Z space.
4839 for (const auto& layer : mDrawingState.layersSortedByZ) {
4840 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4841 continue;
4842 }
4843 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004844 // relative layers are traversed in Layer::traverseInZOrder
4845 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004846 continue;
4847 }
4848 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004849 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4850 return;
4851 }
chaviwa76b2712017-09-20 12:02:26 -07004852 if (!layer->isVisible()) {
4853 return;
4854 }
4855 visitor(layer);
4856 });
4857 }
4858}
4859
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004860}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004861
4862
4863#if defined(__gl_h_)
4864#error "don't include gl/gl.h in this file"
4865#endif
4866
4867#if defined(__gl2_h_)
4868#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004869#endif