blob: e70344e1d6f2168884a4ad32c5b975a676e91830 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
David Sodmanbc815282017-11-05 18:57:52 -0800157SurfaceFlingerBE::SurfaceFlingerBE()
158 : mHwcServiceName(getHwcServiceName()),
159 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800160 mFrameBuckets(),
161 mTotalTime(0),
162 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800163 mComposerSequenceId(0) {
164}
165
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800166SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800167 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700169 mTransactionPending(false),
170 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700172 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700173 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800175 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800177 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800178 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700181 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700182 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700183 mDebugInSwapBuffers(0),
184 mLastSwapBufferTime(0),
185 mDebugInTransaction(0),
186 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700187 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700188 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800196 mMainThreadId(std::this_thread::get_id()),
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800197 mCreateBufferQueue(&BufferQueue::createBufferQueue) {}
198
199SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800200 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800201
202 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
203 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
204
205 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
206 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
207
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800208 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
209 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
212 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
213
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700214 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
215 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
216
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800217 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
218 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
219
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 // Vr flinger is only enabled on Daydream ready devices.
221 useVrFlinger = getBool< ISurfaceFlingerConfigs,
222 &ISurfaceFlingerConfigs::useVrFlinger>(false);
223
Fabien Sanglard1971b632017-03-10 14:50:03 -0800224 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
225 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
226
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227 hasWideColorDisplay =
228 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
229
David Sodman99974d22017-11-28 12:04:33 -0800230 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 // debugging stuff...
233 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700234
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700236 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 property_get("debug.sf.showupdates", value, "0");
239 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241 property_get("debug.sf.ddms", value, "0");
242 mDebugDDMS = atoi(value);
243 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700244 if (!startDdmConnection()) {
245 // start failed, and DDMS debugging not enabled
246 mDebugDDMS = 0;
247 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700249 ALOGI_IF(mDebugRegion, "showupdates enabled");
250 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700251
252 property_get("debug.sf.disable_backpressure", value, "0");
253 mPropagateBackpressure = !atoi(value);
254 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700255
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800256 property_get("debug.sf.enable_hwc_vds", value, "0");
257 mUseHwcVirtualDisplays = atoi(value);
258 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800259
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800260 property_get("ro.sf.disable_triple_buffer", value, "1");
261 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800262 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700263
Dan Stoza0a0158c2018-03-16 13:38:54 -0700264 // TODO (b/74616334): Reduce the default value once we isolate the leak
265 const size_t defaultListSize = 4 * MAX_LAYERS;
266 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
267 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
268
Romain Guy11d63f42017-07-20 12:47:14 -0700269 // We should be reading 'persist.sys.sf.color_saturation' here
270 // but since /data may be encrypted, we need to wait until after vold
271 // comes online to attempt to read the property. The property is
272 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800273
274 if (useTrebleTestingOverride()) {
275 // Without the override SurfaceFlinger cannot connect to HIDL
276 // services that are not listed in the manifests. Considered
277 // deriving the setting from the set service name, but it
278 // would be brittle if the name that's not 'default' is used
279 // for production purposes later on.
280 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
281 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282}
283
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800284void SurfaceFlinger::onFirstRef()
285{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800286 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800287}
288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289SurfaceFlinger::~SurfaceFlinger()
290{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291}
292
Dan Stozac7014012014-02-14 15:03:43 -0800293void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800294{
295 // the window manager died on us. prepare its eulogy.
296
Andy McFadden13a082e2012-08-24 10:16:42 -0700297 // restore initial conditions (default device unblank, etc)
298 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299
300 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700301 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800302}
303
Robert Carr1db73f62016-12-21 12:58:51 -0800304static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700305 status_t err = client->initCheck();
306 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800307 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 }
Robert Carr1db73f62016-12-21 12:58:51 -0800309 return nullptr;
310}
311
312sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
313 return initClient(new Client(this));
314}
315
316sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
317 const sp<IGraphicBufferProducer>& gbp) {
318 if (authenticateSurfaceTexture(gbp) == false) {
319 return nullptr;
320 }
321 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
322 if (layer == nullptr) {
323 return nullptr;
324 }
325
326 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327}
328
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700329sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
330 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700331{
332 class DisplayToken : public BBinder {
333 sp<SurfaceFlinger> flinger;
334 virtual ~DisplayToken() {
335 // no more references, this display must be terminated
336 Mutex::Autolock _l(flinger->mStateLock);
337 flinger->mCurrentState.displays.removeItem(this);
338 flinger->setTransactionFlags(eDisplayTransactionNeeded);
339 }
340 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700341 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700342 : flinger(flinger) {
343 }
344 };
345
346 sp<BBinder> token = new DisplayToken(this);
347
348 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700349 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700350 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700351 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800352 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700353 return token;
354}
355
Jesse Hall6c913be2013-08-08 12:15:49 -0700356void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
357 Mutex::Autolock _l(mStateLock);
358
359 ssize_t idx = mCurrentState.displays.indexOfKey(display);
360 if (idx < 0) {
361 ALOGW("destroyDisplay: invalid display token");
362 return;
363 }
364
365 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
366 if (!info.isVirtualDisplay()) {
367 ALOGE("destroyDisplay called for non-virtual display");
368 return;
369 }
Lloyd Pique4dccc412018-01-22 17:21:36 -0800370 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700371 mCurrentState.displays.removeItemsAt(idx);
372 setTransactionFlags(eDisplayTransactionNeeded);
373}
374
Mathias Agopiane57f2922012-08-09 16:29:12 -0700375sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700376 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700377 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800378 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700379 }
Jesse Hall692c7232012-11-08 15:41:56 -0800380 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381}
382
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383void SurfaceFlinger::bootFinished()
384{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700385 if (mStartPropertySetThread->join() != NO_ERROR) {
386 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800387 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388 const nsecs_t now = systemTime();
389 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000390 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700391
392 // wait patiently for the window manager death
393 const String16 name("window");
394 sp<IBinder> window(defaultServiceManager()->getService(name));
395 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700396 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700397 }
398
Steven Thomas050b2c82017-03-06 11:45:16 -0800399 if (mVrFlinger) {
400 mVrFlinger->OnBootFinished();
401 }
402
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700403 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700404 // formerly we would just kill the process, but we now ask it to exit so it
405 // can choose where to stop the animation.
406 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700407
408 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
409 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
410 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700411
Thierry Strudel2924d012017-08-14 15:19:37 -0700412 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700413 readPersistentProperties();
414 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700415 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416}
417
Mathias Agopian3f844832013-08-07 21:24:32 -0700418void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700419 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800420 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700421 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700422 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800423 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
424 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700426 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 return true;
428 }
429 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700430 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700431}
432
Lloyd Piquee83f9312018-02-01 12:53:17 -0800433class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700435 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000436 const char* name) :
437 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700438 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700439 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000440 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
441 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442 mDispSync(dispSync),
443 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700444 mVsyncMutex(),
445 mPhaseOffset(phaseOffset),
446 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700447
Lloyd Piquee83f9312018-02-01 12:53:17 -0800448 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449
Lloyd Piquee83f9312018-02-01 12:53:17 -0800450 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000453 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 static_cast<DispSync::Callback*>(this));
455 if (err != NO_ERROR) {
456 ALOGE("error registering vsync callback: %s (%d)",
457 strerror(-err), err);
458 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700459 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 } else {
461 status_t err = mDispSync->removeEventListener(
462 static_cast<DispSync::Callback*>(this));
463 if (err != NO_ERROR) {
464 ALOGE("error unregistering vsync callback: %s (%d)",
465 strerror(-err), err);
466 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700467 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 }
471
Lloyd Piquee83f9312018-02-01 12:53:17 -0800472 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 mCallback = callback;
475 }
476
Lloyd Piquee83f9312018-02-01 12:53:17 -0800477 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mVsyncMutex);
479
480 // Normalize phaseOffset to [0, period)
481 auto period = mDispSync->getPeriod();
482 phaseOffset %= period;
483 if (phaseOffset < 0) {
484 // If we're here, then phaseOffset is in (-period, 0). After this
485 // operation, it will be in (0, period)
486 phaseOffset += period;
487 }
488 mPhaseOffset = phaseOffset;
489
490 // If we're not enabled, we don't need to mess with the listeners
491 if (!mEnabled) {
492 return;
493 }
494
495 // Remove the listener with the old offset
496 status_t err = mDispSync->removeEventListener(
497 static_cast<DispSync::Callback*>(this));
498 if (err != NO_ERROR) {
499 ALOGE("error unregistering vsync callback: %s (%d)",
500 strerror(-err), err);
501 }
502
503 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 static_cast<DispSync::Callback*>(this));
506 if (err != NO_ERROR) {
507 ALOGE("error registering vsync callback: %s (%d)",
508 strerror(-err), err);
509 }
510 }
511
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512private:
513 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800514 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700516 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 callback = mCallback;
518
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700519 if (mTraceVsync) {
520 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700521 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700522 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 }
524
Peiyong Lin566a3b42018-01-09 18:22:43 -0800525 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 callback->onVSyncEvent(when);
527 }
528 }
529
Tim Murray4a4e4a22016-04-19 16:29:23 +0000530 const char* const mName;
531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 int mValue;
533
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700534 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700535 const String8 mVsyncOnLabel;
536 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700537
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700539
540 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542
543 Mutex mVsyncMutex; // Protects the following
544 nsecs_t mPhaseOffset;
545 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700546};
547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700549public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800550 InjectVSyncSource() = default;
551 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700552
Lloyd Piquee83f9312018-02-01 12:53:17 -0800553 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700554 std::lock_guard<std::mutex> lock(mCallbackMutex);
555 mCallback = callback;
556 }
557
Lloyd Piquee83f9312018-02-01 12:53:17 -0800558 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700559 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700560 if (mCallback) {
561 mCallback->onVSyncEvent(when);
562 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700563 }
564
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 void setVSyncEnabled(bool) override {}
566 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700567
568private:
569 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800570 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700571};
572
Wei Wangf9b05ee2017-07-19 20:59:39 -0700573// Do not call property_set on main thread which will be blocked by init
574// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700576 ALOGI( "SurfaceFlinger's main thread ready to run. "
577 "Initializing graphics H/W...");
578
Thierry Strudel2924d012017-08-14 15:19:37 -0700579 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800584 mEventThreadSource =
585 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
586 true, "app");
587 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
588 "appEventThread");
589 mSfEventThreadSource =
590 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
591 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800592
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800593 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
594 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800595 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800598 getBE().mRenderEngine =
599 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
600 hasWideColorDisplay
601 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
602 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800603 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700604
605 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
606 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800607 getBE().mHwc.reset(
608 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700609 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800610 // Process any initial hotplug and resulting display changes.
611 processDisplayHotplugEventsLocked();
612 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
613 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800614
Lloyd Piquefcd86612017-12-14 17:15:36 -0800615 // make the default display GLContext current so that we can create textures
616 // when creating Layers (which may happens before we render something)
617 getDefaultDisplayDeviceLocked()->makeCurrent();
618
Steven Thomas050b2c82017-03-06 11:45:16 -0800619 if (useVrFlinger) {
620 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700621 // This callback is called from the vr flinger dispatch thread. We
622 // need to call signalTransaction(), which requires holding
623 // mStateLock when we're not on the main thread. Acquiring
624 // mStateLock from the vr flinger dispatch thread might trigger a
625 // deadlock in surface flinger (see b/66916578), so post a message
626 // to be handled on the main thread instead.
627 sp<LambdaMessage> message = new LambdaMessage([=]() {
628 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
629 mVrFlingerRequestsDisplay = requestDisplay;
630 signalTransaction();
631 });
632 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 };
David Sodman105b7dc2017-11-04 20:28:14 -0700634 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
635 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800636 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 if (!mVrFlinger) {
638 ALOGE("Failed to start vrflinger");
639 }
640 }
641
Lloyd Pique379adc12018-01-22 17:31:47 -0800642 mEventControlThread = std::make_unique<impl::EventControlThread>(
643 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700644
Mathias Agopian92a979a2012-08-02 18:32:23 -0700645 // initialize our drawing state
646 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700647
Andy McFadden13a082e2012-08-24 10:16:42 -0700648 // set initial conditions (e.g. unblank default device)
649 initializeDisplays();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800650 ALOGV("Displays initialized");
Andy McFadden13a082e2012-08-24 10:16:42 -0700651
David Sodmanbc815282017-11-05 18:57:52 -0800652 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700653
Wei Wangf9b05ee2017-07-19 20:59:39 -0700654 // Inform native graphics APIs whether the present timestamp is supported:
655 if (getHwComposer().hasCapability(
656 HWC2::Capability::PresentFenceIsNotReliable)) {
657 mStartPropertySetThread = new StartPropertySetThread(false);
658 } else {
659 mStartPropertySetThread = new StartPropertySetThread(true);
660 }
661
662 if (mStartPropertySetThread->Start() != NO_ERROR) {
663 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800664 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800665
Dan Stoza9e56aa02015-11-02 13:00:03 -0800666 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700667}
668
Romain Guy11d63f42017-07-20 12:47:14 -0700669void SurfaceFlinger::readPersistentProperties() {
670 char value[PROPERTY_VALUE_MAX];
671
672 property_get("persist.sys.sf.color_saturation", value, "1.0");
673 mSaturation = atof(value);
674 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100675
676 property_get("persist.sys.sf.native_mode", value, "0");
677 mForceNativeColorMode = atoi(value) == 1;
678 if (mForceNativeColorMode) {
679 ALOGV("Forcing native color mode");
680 }
Romain Guy11d63f42017-07-20 12:47:14 -0700681}
682
Mathias Agopiana67e4182012-06-19 17:26:12 -0700683void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800684 // Start boot animation service by setting a property mailbox
685 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700686 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800687 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688 if (mStartPropertySetThread->join() != NO_ERROR) {
689 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800690 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700691}
692
Mathias Agopian875d8e12013-06-07 15:35:48 -0700693size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800694 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700695}
696
Mathias Agopian875d8e12013-06-07 15:35:48 -0700697size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800698 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700699}
700
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800702
Jamie Gennis582270d2011-08-17 18:19:00 -0700703bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800704 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800705 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800706 return authenticateSurfaceTextureLocked(bufferProducer);
707}
708
709bool SurfaceFlinger::authenticateSurfaceTextureLocked(
710 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800711 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800712 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800713}
714
Brian Anderson6b376712017-04-04 10:51:39 -0700715status_t SurfaceFlinger::getSupportedFrameTimestamps(
716 std::vector<FrameEvent>* outSupported) const {
717 *outSupported = {
718 FrameEvent::REQUESTED_PRESENT,
719 FrameEvent::ACQUIRE,
720 FrameEvent::LATCH,
721 FrameEvent::FIRST_REFRESH_START,
722 FrameEvent::LAST_REFRESH_START,
723 FrameEvent::GPU_COMPOSITION_DONE,
724 FrameEvent::DEQUEUE_READY,
725 FrameEvent::RELEASE,
726 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700727 ConditionalLock _l(mStateLock,
728 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700729 if (!getHwComposer().hasCapability(
730 HWC2::Capability::PresentFenceIsNotReliable)) {
731 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
732 }
733 return NO_ERROR;
734}
735
Dan Stoza7f7da322014-05-02 15:26:25 -0700736status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
737 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800738 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700739 return BAD_VALUE;
740 }
741
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500742 if (!display.get())
743 return NAME_NOT_FOUND;
744
Jesse Hall692c7232012-11-08 15:41:56 -0800745 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700746 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800747 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700748 type = i;
749 break;
750 }
751 }
752
753 if (type < 0) {
754 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700755 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757 // TODO: Not sure if display density should handled by SF any longer
758 class Density {
759 static int getDensityFromProperty(char const* propName) {
760 char property[PROPERTY_VALUE_MAX];
761 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800762 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700763 density = atoi(property);
764 }
765 return density;
766 }
767 public:
768 static int getEmuDensity() {
769 return getDensityFromProperty("qemu.sf.lcd_density"); }
770 static int getBuildDensity() {
771 return getDensityFromProperty("ro.sf.lcd_density"); }
772 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700773
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700775
Steven Thomas6d8110b2017-08-31 18:24:21 -0700776 ConditionalLock _l(mStateLock,
777 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800778 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 DisplayInfo info = DisplayInfo();
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 float xdpi = hwConfig->getDpiX();
782 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783
784 if (type == DisplayDevice::DISPLAY_PRIMARY) {
785 // The density of the device is provided by a build property
786 float density = Density::getBuildDensity() / 160.0f;
787 if (density == 0) {
788 // the build doesn't provide a density -- this is wrong!
789 // use xdpi instead
790 ALOGE("ro.sf.lcd_density must be defined as a build property");
791 density = xdpi / 160.0f;
792 }
793 if (Density::getEmuDensity()) {
794 // if "qemu.sf.lcd_density" is specified, it overrides everything
795 xdpi = ydpi = density = Density::getEmuDensity();
796 density /= 160.0f;
797 }
798 info.density = density;
799
800 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700801 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800802 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 } else {
804 // TODO: where should this value come from?
805 static const int TV_DENSITY = 213;
806 info.density = TV_DENSITY / 160.0f;
807 info.orientation = 0;
808 }
809
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 info.w = hwConfig->getWidth();
811 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 info.xdpi = xdpi;
813 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900815 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816
Andy McFadden91b2ca82014-06-13 14:04:23 -0700817 // This is how far in advance a buffer must be queued for
818 // presentation at a given time. If you want a buffer to appear
819 // on the screen at time N, you must submit the buffer before
820 // (N - presentationDeadline).
821 //
822 // Normally it's one full refresh period (to give SF a chance to
823 // latch the buffer), but this can be reduced by configuring a
824 // DispSync offset. Any additional delays introduced by the hardware
825 // composer or panel must be accounted for here.
826 //
827 // We add an additional 1ms to allow for processing time and
828 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800830 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
832 // All non-virtual displays are currently considered secure.
833 info.secure = true;
834
Michael Wright28f24d02016-07-12 13:30:53 -0700835 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 }
837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 return NO_ERROR;
839}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700840
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800841status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700842 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800843 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700844 return BAD_VALUE;
845 }
846
847 // FIXME for now we always return stats for the primary display
848 memset(stats, 0, sizeof(*stats));
849 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
850 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
851 return NO_ERROR;
852}
853
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700854int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800855 if (display == nullptr) {
856 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800857 return BAD_VALUE;
858 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700859
860 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800861 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700862 return device->getActiveConfig();
863 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700864
Dan Stoza24a42e92015-03-09 10:04:11 -0700865 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700868void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
869 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
870 this);
871 int32_t type = hw->getDisplayType();
872 int currentMode = hw->getActiveConfig();
873
874 if (mode == currentMode) {
875 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
876 return;
877 }
878
879 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
880 ALOGW("Trying to set config for virtual display");
881 return;
882 }
883
884 hw->setActiveConfig(mode);
885 getHwComposer().setActiveConfig(type, mode);
886}
887
888status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
889 class MessageSetActiveConfig: public MessageBase {
890 SurfaceFlinger& mFlinger;
891 sp<IBinder> mDisplay;
892 int mMode;
893 public:
894 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
895 int mode) :
896 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
897 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700898 Vector<DisplayInfo> configs;
899 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700900 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700901 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700902 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700903 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700904 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700905 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800906 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700907 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700908 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
910 ALOGW("Attempt to set active config = %d for virtual display",
911 mMode);
912 } else {
913 mFlinger.setActiveConfigInternal(hw, mMode);
914 }
915 return true;
916 }
917 };
918 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
919 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700920 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700921}
Michael Wright28f24d02016-07-12 13:30:53 -0700922status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700923 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700924 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
925 return BAD_VALUE;
926 }
927
928 if (!display.get()) {
929 return NAME_NOT_FOUND;
930 }
931
932 int32_t type = NAME_NOT_FOUND;
933 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
934 if (display == mBuiltinDisplays[i]) {
935 type = i;
936 break;
937 }
938 }
939
940 if (type < 0) {
941 return type;
942 }
943
Peiyong Lina52f0292018-03-14 17:26:31 -0700944 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700945 {
946 ConditionalLock _l(mStateLock,
947 std::this_thread::get_id() != mMainThreadId);
948 modes = getHwComposer().getColorModes(type);
949 }
Michael Wright28f24d02016-07-12 13:30:53 -0700950 outColorModes->clear();
951 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
952
953 return NO_ERROR;
954}
955
Peiyong Lina52f0292018-03-14 17:26:31 -0700956ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700957 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700958 if (device != nullptr) {
959 return device->getActiveColorMode();
960 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700961 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700962}
963
964void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700965 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700966 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700967 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700968
969 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700970 return;
971 }
972
973 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
974 ALOGW("Trying to set config for virtual display");
975 return;
976 }
977
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600978 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
979 hw->getDisplayType());
980
Michael Wright28f24d02016-07-12 13:30:53 -0700981 hw->setActiveColorMode(mode);
982 getHwComposer().setActiveColorMode(type, mode);
983}
984
985
986status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700988 class MessageSetActiveColorMode: public MessageBase {
989 SurfaceFlinger& mFlinger;
990 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -0700991 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -0700992 public:
993 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -0700995 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
996 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -0700997 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -0700998 mFlinger.getDisplayColorModes(mDisplay, &modes);
999 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001001 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1002 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001003 return true;
1004 }
1005 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1006 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001007 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1008 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001009 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001010 ALOGW("Attempt to set active color mode %s %d for virtual display",
1011 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001012 } else {
1013 mFlinger.setActiveColorModeInternal(hw, mMode);
1014 }
1015 return true;
1016 }
1017 };
1018 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1019 postMessageSync(msg);
1020 return NO_ERROR;
1021}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001022
Svetoslavd85084b2014-03-20 10:28:31 -07001023status_t SurfaceFlinger::clearAnimationFrameStats() {
1024 Mutex::Autolock _l(mStateLock);
1025 mAnimFrameTracker.clearStats();
1026 return NO_ERROR;
1027}
1028
1029status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1030 Mutex::Autolock _l(mStateLock);
1031 mAnimFrameTracker.getStats(outStats);
1032 return NO_ERROR;
1033}
1034
Dan Stozac4f471e2016-03-24 09:31:08 -07001035status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1036 HdrCapabilities* outCapabilities) const {
1037 Mutex::Autolock _l(mStateLock);
1038
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001039 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001040 if (displayDevice == nullptr) {
1041 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1042 return BAD_VALUE;
1043 }
1044
1045 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001046 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001047 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001048 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1049 // insert HDR10 as we will force client composition for HDR10
1050 // layers
1051 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1052 types.push_back(HAL_HDR_HDR10);
1053
1054 *outCapabilities = HdrCapabilities(types,
1055 capabilities->getDesiredMaxLuminance(),
1056 capabilities->getDesiredMaxAverageLuminance(),
1057 capabilities->getDesiredMinLuminance());
1058 } else {
1059 *outCapabilities = std::move(*capabilities);
1060 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001061 } else {
1062 return BAD_VALUE;
1063 }
1064
1065 return NO_ERROR;
1066}
1067
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1070 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071
Chia-I Wu90f669f2017-10-05 14:24:41 -07001072 if (mInjectVSyncs == enable) {
1073 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001074 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001075
1076 if (enable) {
1077 ALOGV("VSync Injections enabled");
1078 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001079 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001080 mInjectorEventThread =
1081 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1082 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001084 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 } else {
1086 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001087 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001088 }
1089
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001090 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 });
1092 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001093 return NO_ERROR;
1094}
1095
1096status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 Mutex::Autolock _l(mStateLock);
1098
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099 if (!mInjectVSyncs) {
1100 ALOGE("VSync Injections not enabled");
1101 return BAD_VALUE;
1102 }
1103 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1104 ALOGV("Injecting VSync inside SurfaceFlinger");
1105 mVSyncInjector->onInjectSyncEvent(when);
1106 }
1107 return NO_ERROR;
1108}
1109
Lloyd Pique755e3192018-01-31 16:46:15 -08001110status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1111 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001112 IPCThreadState* ipc = IPCThreadState::self();
1113 const int pid = ipc->getCallingPid();
1114 const int uid = ipc->getCallingUid();
1115 if ((uid != AID_SHELL) &&
1116 !PermissionCache::checkPermission(sDump, pid, uid)) {
1117 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1118 return PERMISSION_DENIED;
1119 }
1120
1121 // Try to acquire a lock for 1s, fail gracefully
1122 const status_t err = mStateLock.timedLock(s2ns(1));
1123 const bool locked = (err == NO_ERROR);
1124 if (!locked) {
1125 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1126 return TIMED_OUT;
1127 }
1128
1129 outLayers->clear();
1130 mCurrentState.traverseInZOrder([&](Layer* layer) {
1131 outLayers->push_back(layer->getLayerDebugInfo());
1132 });
1133
1134 mStateLock.unlock();
1135 return NO_ERROR;
1136}
1137
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001138// ----------------------------------------------------------------------------
1139
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001140sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1141 ISurfaceComposer::VsyncSource vsyncSource) {
1142 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1143 return mSFEventThread->createEventConnection();
1144 } else {
1145 return mEventThread->createEventConnection();
1146 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001147}
1148
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001149// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150
1151void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001152 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001153}
1154
1155void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001156 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001157}
1158
1159void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001160 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161}
1162
1163void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001164 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166}
1167
1168status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001169 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001170 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001171}
1172
1173status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001174 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001175 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176 if (res == NO_ERROR) {
1177 msg->wait();
1178 }
1179 return res;
1180}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001182void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001183 do {
1184 waitForEvent();
1185 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186}
1187
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188void SurfaceFlinger::enableHardwareVsync() {
1189 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001192 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1193 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001195 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001196}
1197
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 Mutex::Autolock _l(mHWVsyncLock);
1200
Jesse Hall948fe0c2013-10-14 12:56:09 -07001201 if (makeAvailable) {
1202 mHWVsyncAvailable = true;
1203 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001204 // Hardware vsync is not currently available, so abort the resync
1205 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 return;
1207 }
1208
David Sodman105b7dc2017-11-04 20:28:14 -07001209 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001210 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211
1212 mPrimaryDispSync.reset();
1213 mPrimaryDispSync.setPeriod(period);
1214
1215 if (!mPrimaryHWVsyncEnabled) {
1216 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001217 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1218 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 mPrimaryHWVsyncEnabled = true;
1220 }
1221}
1222
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224 Mutex::Autolock _l(mHWVsyncLock);
1225 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1227 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryDispSync.endResync();
1229 mPrimaryHWVsyncEnabled = false;
1230 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001231 if (makeUnavailable) {
1232 mHWVsyncAvailable = false;
1233 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234}
1235
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236void SurfaceFlinger::resyncWithRateLimit() {
1237 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001238
1239 // No explicit locking is needed here since EventThread holds a lock while calling this method
1240 static nsecs_t sLastResyncAttempted = 0;
1241 const nsecs_t now = systemTime();
1242 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001243 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244 }
Dan Stoza57164302017-05-08 14:03:54 -07001245 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001246}
1247
Steven Thomasb02664d2017-07-26 18:48:28 -07001248void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1249 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001250 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001251 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001252 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001253 return;
1254 }
1255
1256 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001257 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001258 return;
1259 }
1260
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262
Jamie Gennisd1700752013-10-14 12:22:52 -07001263 { // Scope for the lock
1264 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001265 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001266 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001268 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001269
1270 if (needsHwVsync) {
1271 enableHardwareVsync();
1272 } else {
1273 disableHardwareVsync(false);
1274 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001275}
1276
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001277void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001278 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1279 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001280}
1281
Lloyd Pique715a2c12017-12-14 17:18:08 -08001282void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1283 HWC2::Connection connection) {
1284 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1285 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001286
Lloyd Piqueba04e622017-12-14 17:11:26 -08001287 // Ignore events that do not have the right sequenceId.
1288 if (sequenceId != getBE().mComposerSequenceId) {
1289 return;
1290 }
1291
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 // Only lock if we're not on the main thread. This function is normally
1293 // called on a hwbinder thread, but for the primary display it's called on
1294 // the main thread with the state lock already held, so don't attempt to
1295 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001296 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001297
Lloyd Pique715a2c12017-12-14 17:18:08 -08001298 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001299
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001300 if (std::this_thread::get_id() == mMainThreadId) {
1301 // Process all pending hot plug events immediately if we are on the main thread.
1302 processDisplayHotplugEventsLocked();
1303 }
1304
Lloyd Piqueba04e622017-12-14 17:11:26 -08001305 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001306}
1307
Steven Thomasb02664d2017-07-26 18:48:28 -07001308void SurfaceFlinger::onRefreshReceived(int sequenceId,
1309 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001310 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001311 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001312 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001313 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001314 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001315}
1316
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001320 getHwComposer().setVsyncEnabled(disp,
1321 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001322}
1323
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001324// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001325void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327 // Clear the drawing state so that the logic inside of
1328 // handleTransactionLocked will fire. It will determine the delta between
1329 // mCurrentState and mDrawingState and re-apply all changes when we make the
1330 // transition.
1331 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001332 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333 mDisplays.clear();
1334}
1335
Steven Thomas050b2c82017-03-06 11:45:16 -08001336void SurfaceFlinger::updateVrFlinger() {
1337 if (!mVrFlinger)
1338 return;
1339 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001340 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001341 return;
1342 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001343
David Sodman105b7dc2017-11-04 20:28:14 -07001344 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 ALOGE("Vr flinger is only supported for remote hardware composer"
1346 " service connections. Ignoring request to transition to vr"
1347 " flinger.");
1348 mVrFlingerRequestsDisplay = false;
1349 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001350 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001351
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 int currentDisplayPowerMode = getDisplayDeviceLocked(
1355 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001356
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001362 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001363 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1364 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001365 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366
David Sodman105b7dc2017-11-04 20:28:14 -07001367 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1368 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001369
1370 if (vrFlingerRequestsDisplay) {
1371 mVrFlinger->GrantDisplayOwnership();
1372 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001373 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375
1376 mVisibleRegionsDirty = true;
1377 invalidateHwcGeometry();
1378
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001379 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1381 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1382 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001385 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 const nsecs_t period = activeConfig->getVsyncPeriod();
1387 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001388
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 // Use phase of 0 since phase is not known.
1390 // Use latency of 0, which will snap to the ideal latency.
1391 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001392
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393 android_atomic_or(1, &mRepaintEverything);
1394 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395}
1396
Mathias Agopian4fec8732012-06-29 14:12:52 -07001397void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001398 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001399 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001400 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001401 bool frameMissed = !mHadClientComposition &&
1402 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001403 (mPreviousPresentFence->getSignalTime() ==
1404 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001405 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001406 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001407 signalLayerUpdate();
1408 break;
1409 }
1410
Steven Thomas050b2c82017-03-06 11:45:16 -08001411 // Now that we're going to make it to the handleMessageTransaction()
1412 // call below it's safe to call updateVrFlinger(), which will
1413 // potentially trigger a display handoff.
1414 updateVrFlinger();
1415
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 bool refreshNeeded = handleMessageTransaction();
1417 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001418 refreshNeeded |= mRepaintEverything;
David Sodman56912832017-11-28 10:27:38 -08001419
1420 const nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1421
1422 preComposition(refreshStartTime);
1423 rebuildLayerStacks();
1424
1425 calculateWorkingSet();
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 if (refreshNeeded) {
David Sodman56912832017-11-28 10:27:38 -08001428
Dan Stoza58784442014-12-02 16:58:17 -08001429 // Signal a refresh if a transaction modified the window state,
1430 // a new buffer was latched, or if HWC has requested a full
1431 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 signalRefresh();
1433 }
1434 break;
1435 }
1436 case MessageQueue::REFRESH: {
1437 handleMessageRefresh();
1438 break;
1439 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001440 }
1441}
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001444 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001446 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001450}
1451
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455}
1456
David Sodman56912832017-11-28 10:27:38 -08001457void SurfaceFlinger::calculateWorkingSet() {
1458 ATRACE_CALL();
1459 ALOGV(__FUNCTION__);
1460
1461 // build the h/w work list
1462 if (CC_UNLIKELY(mGeometryInvalid)) {
1463 mGeometryInvalid = false;
1464 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1465 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1466 const auto hwcId = displayDevice->getHwcDisplayId();
1467 if (hwcId >= 0) {
1468 const Vector<sp<Layer>>& currentLayers(
1469 displayDevice->getVisibleLayersSortedByZ());
1470 for (size_t i = 0; i < currentLayers.size(); i++) {
1471 const auto& layer = currentLayers[i];
1472
1473 if (!layer->hasHwcLayer(hwcId)) {
1474 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1475 layer->forceClientComposition(hwcId);
1476 continue;
1477 }
1478 }
1479
1480 layer->setGeometry(displayDevice, i);
1481 if (mDebugDisableHWC || mDebugRegion) {
1482 layer->forceClientComposition(hwcId);
1483 }
1484 }
1485 }
1486 }
1487 }
1488 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
1489
1490 // Set the per-frame data
1491 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1492 auto& displayDevice = mDisplays[displayId];
1493 const auto hwcId = displayDevice->getHwcDisplayId();
1494
1495 if (hwcId < 0) {
1496 continue;
1497 }
1498 if (colorMatrix != mPreviousColorMatrix) {
1499 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
1500 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1501 "display %zd: %d", displayId, result);
1502 }
1503 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1504 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1505 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
1506 !displayDevice->getHdrSupport()) {
1507 layer->forceClientComposition(hwcId);
1508 }
1509
1510 if (layer->getForceClientComposition(hwcId)) {
1511 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1512 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1513 continue;
1514 }
1515
1516 layer->setPerFrameData(displayDevice);
1517 }
1518
1519 if (hasWideColorDisplay) {
1520 ColorMode newColorMode;
1521 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1522
1523 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1524 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1525 displayDevice->getHdrSupport());
1526 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1527 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1528 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1529 }
1530 newColorMode = pickColorMode(newDataSpace);
1531
1532 setActiveColorModeInternal(displayDevice, newColorMode);
1533 }
1534 }
1535
1536 mPreviousColorMatrix = colorMatrix;
1537 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1538 auto& displayDevice = mDisplays[displayId];
1539 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1540 auto hwcId = displayDevice->getHwcDisplayId();
1541 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(hwcId);
1542 if (!layer->setHwcLayer(hwcId)) {
1543 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1544 }
1545 layer->getBE().compositionInfo.hwc.hwid = hwcId;
1546 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1547 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1548 }
1549 }
1550}
1551
Mathias Agopian4fec8732012-06-29 14:12:52 -07001552void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001554
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001555 mRefreshPending = false;
1556
Pablo Ceballos40845df2016-01-25 17:41:15 -08001557 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001558
Dan Stoza05dacfb2016-07-01 13:33:38 -07001559 setUpHWComposer();
1560 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001561 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001562 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001563 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001565
David Sodman105b7dc2017-11-04 20:28:14 -07001566 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001567
1568 mHadClientComposition = false;
1569 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1570 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1571 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001572 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001573 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001574
Dan Stoza9e56aa02015-11-02 13:00:03 -08001575 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001577
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578void SurfaceFlinger::doDebugFlashRegions()
1579{
1580 // is debugging enabled
1581 if (CC_LIKELY(!mDebugRegion))
1582 return;
1583
1584 const bool repaintEverything = mRepaintEverything;
1585 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1586 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001587 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 // transform the dirty region into this screen's coordinate space
1589 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1590 if (!dirtyRegion.isEmpty()) {
1591 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001592 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593
1594 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001596 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001597 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1598
Mathias Agopianda27af92012-09-13 18:17:13 -07001599 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001600 }
1601 }
1602 }
1603
1604 postFramebuffer();
1605
1606 if (mDebugRegion > 1) {
1607 usleep(mDebugRegion * 1000);
1608 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001609
Dan Stoza9e56aa02015-11-02 13:00:03 -08001610 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001611 auto& displayDevice = mDisplays[displayId];
1612 if (!displayDevice->isDisplayOn()) {
1613 continue;
1614 }
1615
David Sodman105b7dc2017-11-04 20:28:14 -07001616 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1617 ALOGE_IF(result != NO_ERROR,
1618 "prepareFrame for display %zd failed:"
1619 " %d (%s)",
1620 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001621 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622}
1623
Adrian Roos1e1a1282017-11-01 19:05:31 +01001624void SurfaceFlinger::doTracing(const char* where) {
1625 ATRACE_CALL();
1626 ATRACE_NAME(where);
1627 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001628 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001629 }
1630}
1631
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001632void SurfaceFlinger::logLayerStats() {
1633 ATRACE_CALL();
1634 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1635 int32_t hwcId = -1;
1636 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1637 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1638 if (displayDevice->isPrimary()) {
1639 hwcId = displayDevice->getHwcDisplayId();
1640 break;
1641 }
1642 }
1643 if (hwcId < 0) {
1644 ALOGE("LayerStats: Hmmm, no primary display?");
1645 return;
1646 }
1647 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1648 }
1649}
1650
Brian Andersond6927fb2016-07-23 23:37:30 -07001651void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 ATRACE_CALL();
1654 ALOGV("preComposition");
1655
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001657 mDrawingState.traverseInZOrder([&](Layer* layer) {
1658 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659 needExtraInvalidate = true;
1660 }
Robert Carr2047fae2016-11-28 14:09:09 -08001661 });
1662
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663 if (needExtraInvalidate) {
1664 signalLayerUpdate();
1665 }
1666}
1667
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668void SurfaceFlinger::updateCompositorTiming(
1669 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1670 std::shared_ptr<FenceTime>& presentFenceTime) {
1671 // Update queue of past composite+present times and determine the
1672 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001673 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001675 while (!getBE().mCompositePresentTimes.empty()) {
1676 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 // Cached values should have been updated before calling this method,
1678 // which helps avoid duplicate syscalls.
1679 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1680 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1681 break;
1682 }
1683 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001684 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 }
1686
1687 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001688 while (getBE().mCompositePresentTimes.size() > 16) {
1689 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690 }
1691
Brian Andersond0010582017-03-07 13:20:31 -08001692 setCompositorTimingSnapped(
1693 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1694}
1695
1696void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1697 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 // Integer division and modulo round toward 0 not -inf, so we need to
1699 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001700 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1702 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1703
Brian Andersond0010582017-03-07 13:20:31 -08001704 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1705 if (idealLatency <= 0) {
1706 idealLatency = vsyncInterval;
1707 }
1708
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 // Snap the latency to a value that removes scheduling jitter from the
1710 // composition and present times, which often have >1ms of jitter.
1711 // Reducing jitter is important if an app attempts to extrapolate
1712 // something (such as user input) to an accurate diasplay time.
1713 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1714 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001715 nsecs_t bias = vsyncInterval / 2;
1716 int64_t extraVsyncs =
1717 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1718 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1719 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001720
David Sodman99974d22017-11-28 12:04:33 -08001721 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1722 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1723 getBE().mCompositorTiming.interval = vsyncInterval;
1724 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725}
1726
1727void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001728{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001729 ATRACE_CALL();
1730 ALOGV("postComposition");
1731
Brian Anderson3546a3f2016-07-14 11:51:14 -07001732 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001733 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001734 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001735 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001736 }
1737
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001738 // |mStateLock| not needed as we are on the main thread
1739 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001740
David Sodman73beded2017-11-15 11:56:06 -08001741 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001742 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001743 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001744 glCompositionDoneFenceTime =
1745 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001746 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747 } else {
1748 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1749 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001750
David Sodman73beded2017-11-15 11:56:06 -08001751 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001752 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001753 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001754 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001755
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1757 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1758
1759 // We use the refreshStartTime which might be sampled a little later than
1760 // when we started doing work for this frame, but that should be okay
1761 // since updateCompositorTiming has snapping logic.
1762 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001764 CompositorTiming compositorTiming;
1765 {
David Sodman99974d22017-11-28 12:04:33 -08001766 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1767 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001768 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001769
Robert Carr2047fae2016-11-28 14:09:09 -08001770 mDrawingState.traverseInZOrder([&](Layer* layer) {
1771 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001772 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001773 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001774 recordBufferingStats(layer->getName().string(),
1775 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001776 }
Robert Carr2047fae2016-11-28 14:09:09 -08001777 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001778
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001779 if (presentFenceTime->isValid()) {
1780 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001781 enableHardwareVsync();
1782 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001783 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001784 }
1785 }
1786
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001787 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001788 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001789 enableHardwareVsync();
1790 }
1791 }
1792
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001793 if (mAnimCompositionPending) {
1794 mAnimCompositionPending = false;
1795
Brian Anderson4e606e32017-03-16 15:34:57 -07001796 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001797 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001798 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001799 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001800 // The HWC doesn't support present fences, so use the refresh
1801 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001802 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001803 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001804 mAnimFrameTracker.setActualPresentTime(presentTime);
1805 }
1806 mAnimFrameTracker.advanceFrame();
1807 }
Dan Stozab90cf072015-03-05 11:05:59 -08001808
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001809 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1810 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001811 return;
1812 }
1813
1814 nsecs_t currentTime = systemTime();
1815 if (mHasPoweredOff) {
1816 mHasPoweredOff = false;
1817 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001818 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001819 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001820 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1821 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001822 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001823 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001824 }
David Sodman4a36e932017-11-07 14:29:47 -08001825 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001826 }
David Sodman4a36e932017-11-07 14:29:47 -08001827 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828}
1829
1830void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001831 ATRACE_CALL();
1832 ALOGV("rebuildLayerStacks");
1833
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001836 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 mVisibleRegionsDirty = false;
1838 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001839
Jeff Sharkey76488112017-02-27 14:15:18 -07001840 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1841 Region opaqueRegion;
1842 Region dirtyRegion;
1843 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001844 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001845 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1846 const Transform& tr(displayDevice->getTransform());
1847 const Rect bounds(displayDevice->getBounds());
1848 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001849 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001850
Jeff Sharkey76488112017-02-27 14:15:18 -07001851 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001852 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001853 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1854 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 Region drawRegion(tr.transform(
1856 layer->visibleNonTransparentRegion));
1857 drawRegion.andSelf(bounds);
1858 if (!drawRegion.isEmpty()) {
1859 layersSortedByZ.add(layer);
1860 } else {
David Sodman56912832017-11-28 10:27:38 -08001861 if (layer->hasHwcLayer(displayDevice->getHwcDisplayId())) {
1862 // Clear out the HWC layer if this layer was
1863 // previously visible, but no longer is
1864 hwcLayerDestroyed = layer->destroyHwcLayer(
1865 displayDevice->getHwcDisplayId());
1866 }
1867 }
1868 } else {
1869 if (layer->hasHwcLayer(displayDevice->getHwcDisplayId())) {
1870 // WM changes displayDevice->layerStack upon sleep/awake.
1871 // Here we make sure we delete the HWC layers even if
1872 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001873 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001874 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001875 }
Chia-I Wu83806892017-11-16 10:50:20 -08001876 }
1877
1878 // If a layer is not going to get a release fence because
1879 // it is invisible, but it is also going to release its
1880 // old buffer, add it to the list of layers needing
1881 // fences.
1882 if (hwcLayerDestroyed) {
1883 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1884 mLayersWithQueuedFrames.cend(), layer);
1885 if (found != mLayersWithQueuedFrames.cend()) {
1886 layersNeedingFences.add(layer);
1887 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001888 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001889 });
1890 }
1891 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001892 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001893 displayDevice->undefinedRegion.set(bounds);
1894 displayDevice->undefinedRegion.subtractSelf(
1895 tr.transform(opaqueRegion));
1896 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001897 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001898 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001900
Romain Guy0147a172017-06-01 13:53:56 -07001901mat4 SurfaceFlinger::computeSaturationMatrix() const {
1902 if (mSaturation == 1.0f) {
1903 return mat4();
1904 }
1905
1906 // Rec.709 luma coefficients
1907 float3 luminance{0.213f, 0.715f, 0.072f};
1908 luminance *= 1.0f - mSaturation;
1909 return mat4(
1910 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1911 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1912 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1913 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1914 );
1915}
1916
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001917// pickColorMode translates a given dataspace into the best available color mode.
1918// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001919ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001920 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001921 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001922 }
1923
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001924 switch (dataSpace) {
1925 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1926 // system expects.
1927 case HAL_DATASPACE_UNKNOWN:
1928 case HAL_DATASPACE_SRGB:
1929 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001930 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001931 break;
1932
1933 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001934 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001935 break;
1936
1937 default:
1938 // TODO (courtneygo): Do we want to assert an error here?
1939 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1940 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001941 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001942 break;
1943 }
1944}
1945
Romain Guy0147a172017-06-01 13:53:56 -07001946android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001947 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001948 // Only support sRGB and Display-P3 right now.
1949 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1950 return HAL_DATASPACE_DISPLAY_P3;
1951 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001952 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1953 return HAL_DATASPACE_DISPLAY_P3;
1954 }
1955 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1956 return HAL_DATASPACE_DISPLAY_P3;
1957 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001958 if (!hasHdr) {
1959 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1960 return HAL_DATASPACE_DISPLAY_P3;
1961 }
1962 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1963 return HAL_DATASPACE_DISPLAY_P3;
1964 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001965 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001966
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001967 return HAL_DATASPACE_V0_SRGB;
1968}
1969
David Sodman5a5f1482017-12-15 11:11:59 -08001970void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
1971{
1972 HWC2::Error error;
1973 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
1974 "CompositionType is sideband, but sideband stream is nullptr");
1975 error = (*compositionInfo.hwc.hwcLayer)
1976 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
1977 if (error != HWC2::Error::None) {
1978 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
1979 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
1980 static_cast<int32_t>(error));
1981 }
1982}
1983
David Sodman14fe0362017-12-14 17:31:04 -08001984void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
David Sodman56912832017-11-28 10:27:38 -08001985{
1986 HWC2::Error error;
1987
1988 if (!compositionInfo.hwc.skipGeometry) {
David Sodman14fe0362017-12-14 17:31:04 -08001989 error = (*compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
1990 ALOGE_IF(error != HWC2::Error::None,
1991 "[SF] Failed to set blend mode %s:"
1992 " %s (%d)",
1993 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
1994 static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08001995
David Sodman14fe0362017-12-14 17:31:04 -08001996 error = (*compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
1997 ALOGE_IF(error != HWC2::Error::None,
1998 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
1999 compositionInfo.hwc.displayFrame.left,
2000 compositionInfo.hwc.displayFrame.right,
2001 compositionInfo.hwc.displayFrame.top,
2002 compositionInfo.hwc.displayFrame.bottom,
2003 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002004
David Sodman14fe0362017-12-14 17:31:04 -08002005 error = (*compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2006 ALOGE_IF(error != HWC2::Error::None,
2007 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2008 compositionInfo.hwc.sourceCrop.left,
2009 compositionInfo.hwc.sourceCrop.right,
2010 compositionInfo.hwc.sourceCrop.top,
2011 compositionInfo.hwc.sourceCrop.bottom,
2012 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002013
2014 error = (*compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2015 ALOGE_IF(error != HWC2::Error::None,
2016 "[SF] Failed to set plane alpha %.3f: "
2017 "%s (%d)",
2018 compositionInfo.hwc.alpha,
2019 to_string(error).c_str(), static_cast<int32_t>(error));
2020
2021
2022 error = (*compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2023 ALOGE_IF(error != HWC2::Error::None,
2024 "[SF] Failed to set Z %u: %s (%d)",
2025 compositionInfo.hwc.z,
2026 to_string(error).c_str(), static_cast<int32_t>(error));
2027
David Sodman14fe0362017-12-14 17:31:04 -08002028 error = (*compositionInfo.hwc.hwcLayer)
2029 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
David Sodman56912832017-11-28 10:27:38 -08002030 ALOGE_IF(error != HWC2::Error::None,
2031 "[SF] Failed to set info (%d)",
2032 static_cast<int32_t>(error));
2033
David Sodman14fe0362017-12-14 17:31:04 -08002034 error = (*compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
David Sodman56912832017-11-28 10:27:38 -08002035 ALOGE_IF(error != HWC2::Error::None,
David Sodman14fe0362017-12-14 17:31:04 -08002036 "[SF] Failed to set transform %s: "
2037 "%s (%d)",
2038 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2039 static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002040 }
2041
2042 error = (*compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2043 ALOGE_IF(error != HWC2::Error::None,
2044 "[SF] Failed to set composition type: %s (%d)",
David Sodman14fe0362017-12-14 17:31:04 -08002045 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002046
2047 error = (*compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2048 ALOGE_IF(error != HWC2::Error::None,
2049 "[SF] Failed to set dataspace: %s (%d)",
2050 to_string(error).c_str(), static_cast<int32_t>(error));
2051
2052 error = (*compositionInfo.hwc.hwcLayer)->setHdrMetadata(compositionInfo.hwc.hdrMetadata);
2053 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2054 "[SF] Failed to set hdrMetadata: %s (%d)",
2055 to_string(error).c_str(), static_cast<int32_t>(error));
2056
David Sodman14fe0362017-12-14 17:31:04 -08002057 error = (*compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2058 ALOGE_IF(error != HWC2::Error::None,
2059 "[SF] Failed to set color: %s (%d)",
2060 to_string(error).c_str(), static_cast<int32_t>(error));
2061
2062 error = (*compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2063 ALOGE_IF(error != HWC2::Error::None,
2064 "[SF] Failed to set visible region: %s (%d)",
2065 to_string(error).c_str(), static_cast<int32_t>(error));
2066}
2067
2068void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2069{
2070 HWC2::Error error;
2071
2072 error = (*compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2073 ALOGE_IF(error != HWC2::Error::None,
2074 "[SF] Failed to set surface damage: %s (%d)",
2075 to_string(error).c_str(), static_cast<int32_t>(error));
2076
David Sodman56912832017-11-28 10:27:38 -08002077 if (compositionInfo.updateBuffer) {
2078 error = (*compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2079 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2080 ALOGE_IF(error != HWC2::Error::None,
2081 "[SF] Failed to set buffer: %s (%d)",
2082 to_string(error).c_str(), static_cast<int32_t>(error));
2083 }
2084}
2085
Mathias Agopiancd60f992012-08-16 16:28:27 -07002086void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 ATRACE_CALL();
2088 ALOGV("setUpHWComposer");
2089
Jesse Hall028dc8f2013-08-20 16:35:32 -07002090 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07002091 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
2092 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2093 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2094
2095 // If nothing has changed (!dirty), don't recompose.
2096 // If something changed, but we don't currently have any visible layers,
2097 // and didn't when we last did a composition, then skip it this time.
2098 // The second rule does two things:
2099 // - When all layers are removed from a display, we'll emit one black
2100 // frame, then nothing more until we get new layers.
2101 // - When a display is created with a private layer stack, we won't
2102 // emit any black frames until a layer is added to the layer stack.
2103 bool mustRecompose = dirty && !(empty && wasEmpty);
2104
2105 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2106 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2107 mustRecompose ? "doing" : "skipping",
2108 dirty ? "+" : "-",
2109 empty ? "+" : "-",
2110 wasEmpty ? "+" : "-");
2111
Dan Stoza71433162014-02-04 16:22:36 -08002112 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002113
2114 if (mustRecompose) {
2115 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2116 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002117 }
2118
David Sodman56912832017-11-28 10:27:38 -08002119 {
2120 ATRACE_NAME("Programming_HWCOMPOSER");
2121 for (auto compositionInfo : getBE().mCompositionInfo) {
2122 ALOGV("[SF] hwcLayer=%p(%lu), compositionType=%d",
2123 static_cast<HWC2::Layer*>(*compositionInfo.hwc.hwcLayer),
2124 compositionInfo.hwc.hwcLayer.use_count(), compositionInfo.compositionType);
Jamie Gennisa4310c82012-09-25 20:26:00 -07002125
David Sodman56912832017-11-28 10:27:38 -08002126 switch (compositionInfo.compositionType)
2127 {
2128 case HWC2::Composition::Invalid:
David Sodman56912832017-11-28 10:27:38 -08002129 case HWC2::Composition::Client:
David Sodman56912832017-11-28 10:27:38 -08002130 case HWC2::Composition::Cursor:
David Sodman5a5f1482017-12-15 11:11:59 -08002131 break;
2132
David Sodman56912832017-11-28 10:27:38 -08002133 case HWC2::Composition::Sideband:
David Sodman5a5f1482017-12-15 11:11:59 -08002134 configureSidebandComposition(compositionInfo);
David Sodman56912832017-11-28 10:27:38 -08002135 break;
2136
David Sodman14fe0362017-12-14 17:31:04 -08002137 case HWC2::Composition::SolidColor:
2138 configureHwcCommonData(compositionInfo);
2139 break;
2140
David Sodman56912832017-11-28 10:27:38 -08002141 case HWC2::Composition::Device:
David Sodman14fe0362017-12-14 17:31:04 -08002142 configureHwcCommonData(compositionInfo);
David Sodman56912832017-11-28 10:27:38 -08002143 configureDeviceComposition(compositionInfo);
2144 break;
Riley Andrews03414a12014-07-01 14:22:59 -07002145 }
2146 }
David Sodman56912832017-11-28 10:27:38 -08002147 getBE().mCompositionInfo.clear();
David Sodman4b7c4bc2017-11-17 12:13:59 -08002148 }
2149
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002151 auto& displayDevice = mDisplays[displayId];
2152 if (!displayDevice->isDisplayOn()) {
2153 continue;
2154 }
2155
David Sodman105b7dc2017-11-04 20:28:14 -07002156 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2158 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002159 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002160}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002161
Mathias Agopiancd60f992012-08-16 16:28:27 -07002162void SurfaceFlinger::doComposition() {
2163 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002164 ALOGV("doComposition");
2165
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002166 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002167 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002168 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002169 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170 // transform the dirty region into this screen's coordinate space
2171 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002172
2173 // repaint the framebuffer (if needed)
2174 doDisplayComposition(hw, dirtyRegion);
2175
Mathias Agopiancd60f992012-08-16 16:28:27 -07002176 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002177 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002178 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002179 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002180 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002181}
2182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183void SurfaceFlinger::postFramebuffer()
2184{
Mathias Agopian841cde52012-03-01 15:44:37 -08002185 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002187
Mathias Agopiana44b0412011-10-16 18:46:35 -07002188 const nsecs_t now = systemTime();
2189 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002190
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2192 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002193 if (!displayDevice->isDisplayOn()) {
2194 continue;
2195 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 const auto hwcId = displayDevice->getHwcDisplayId();
2197 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002198 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002199 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002200 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002201 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002203 // The layer buffer from the previous frame (if any) is released
2204 // by HWC only when the release fence from this frame (if any) is
2205 // signaled. Always get the release fence from HWC first.
2206 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002207 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002208
2209 // If the layer was client composited in the previous frame, we
2210 // need to merge with the previous client target acquire fence.
2211 // Since we do not track that, always merge with the current
2212 // client target acquire fence when it is available, even though
2213 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002215 releaseFence = Fence::merge("LayerRelease", releaseFence,
2216 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002217 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002218
David Sodmanb8af7922017-12-21 15:17:55 -08002219 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 }
Chia-I Wu83806892017-11-16 10:50:20 -08002221
2222 // We've got a list of layers needing fences, that are disjoint with
2223 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2224 // supply them with the present fence.
2225 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002226 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002227 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002228 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002229 }
2230 }
2231
Dan Stoza9e56aa02015-11-02 13:00:03 -08002232 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002233 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002234 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002235 }
2236
Mathias Agopiana44b0412011-10-16 18:46:35 -07002237 mLastSwapBufferTime = systemTime() - now;
2238 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002239
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002240 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002241 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2242 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2243 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2244 logFrameStats();
2245 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002246 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247}
2248
Mathias Agopian87baae12012-07-31 12:38:26 -07002249void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250{
Mathias Agopian841cde52012-03-01 15:44:37 -08002251 ATRACE_CALL();
2252
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002253 // here we keep a copy of the drawing state (that is the state that's
2254 // going to be overwritten by handleTransactionLocked()) outside of
2255 // mStateLock so that the side-effects of the State assignment
2256 // don't happen with mStateLock held (which can cause deadlocks).
2257 State drawingState(mDrawingState);
2258
Mathias Agopianca4d3602011-05-19 15:38:14 -07002259 Mutex::Autolock _l(mStateLock);
2260 const nsecs_t now = systemTime();
2261 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262
Mathias Agopianca4d3602011-05-19 15:38:14 -07002263 // Here we're guaranteed that some transaction flags are set
2264 // so we can call handleTransactionLocked() unconditionally.
2265 // We call getTransactionFlags(), which will also clear the flags,
2266 // with mStateLock held to guarantee that mCurrentState won't change
2267 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002268
Mathias Agopiane57f2922012-08-09 16:29:12 -07002269 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002270 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002271
Mathias Agopianca4d3602011-05-19 15:38:14 -07002272 mLastTransactionTime = systemTime() - now;
2273 mDebugInTransaction = 0;
2274 invalidateHwcGeometry();
2275 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002276}
2277
Lloyd Pique715a2c12017-12-14 17:18:08 -08002278DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2279 HWC2::Connection connection) const {
2280 // Figure out whether the event is for the primary display or an
2281 // external display by matching the Hwc display id against one for a
2282 // connected display. If we did not find a match, we then check what
2283 // displays are not already connected to determine the type. If we don't
2284 // have a connected primary display, we assume the new display is meant to
2285 // be the primary display, and then if we don't have an external display,
2286 // we assume it is that.
2287 const auto primaryDisplayId =
2288 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2289 const auto externalDisplayId =
2290 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2291 if (primaryDisplayId && primaryDisplayId == display) {
2292 return DisplayDevice::DISPLAY_PRIMARY;
2293 } else if (externalDisplayId && externalDisplayId == display) {
2294 return DisplayDevice::DISPLAY_EXTERNAL;
2295 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2296 return DisplayDevice::DISPLAY_PRIMARY;
2297 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2298 return DisplayDevice::DISPLAY_EXTERNAL;
2299 }
2300
2301 return DisplayDevice::DISPLAY_ID_INVALID;
2302}
2303
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2305 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002306 auto displayType = determineDisplayType(event.display, event.connection);
2307 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2308 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2309 continue;
2310 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
2312 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2313 ALOGE("External displays are not supported by the vr hardware composer.");
2314 continue;
2315 }
2316
Lloyd Pique715a2c12017-12-14 17:18:08 -08002317 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002318
2319 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002320 if (!mBuiltinDisplays[displayType].get()) {
2321 ALOGV("Creating built in display %d", displayType);
2322 mBuiltinDisplays[displayType] = new BBinder();
2323 // All non-virtual displays are currently considered secure.
2324 DisplayDeviceState info(displayType, true);
2325 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2326 "Built-in Screen" : "External Screen";
2327 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2328 mInterceptor->saveDisplayCreation(info);
2329 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002330 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002331 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002332
Lloyd Piquefcd86612017-12-14 17:15:36 -08002333 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2334 if (idx >= 0) {
2335 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4dccc412018-01-22 17:21:36 -08002336 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002337 mCurrentState.displays.removeItemsAt(idx);
2338 }
2339 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340 }
2341
2342 processDisplayChangesLocked();
2343 }
2344
2345 mPendingHotplugEvents.clear();
2346}
2347
Lloyd Pique347200f2017-12-14 17:00:15 -08002348void SurfaceFlinger::processDisplayChangesLocked() {
2349 // here we take advantage of Vector's copy-on-write semantics to
2350 // improve performance by skipping the transaction entirely when
2351 // know that the lists are identical
2352 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2353 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2354 if (!curr.isIdenticalTo(draw)) {
2355 mVisibleRegionsDirty = true;
2356 const size_t cc = curr.size();
2357 size_t dc = draw.size();
2358
2359 // find the displays that were removed
2360 // (ie: in drawing state but not in current state)
2361 // also handle displays that changed
2362 // (ie: displays that are in both lists)
2363 for (size_t i = 0; i < dc;) {
2364 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2365 if (j < 0) {
2366 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002367 // Call makeCurrent() on the primary display so we can
2368 // be sure that nothing associated with this display
2369 // is current.
2370 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2371 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2372 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2373 if (hw != nullptr) hw->disconnect(getHwComposer());
2374 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2375 mEventThread->onHotplugReceived(draw[i].type, false);
2376 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 } else {
2378 // this display is in both lists. see if something changed.
2379 const DisplayDeviceState& state(curr[j]);
2380 const wp<IBinder>& display(curr.keyAt(j));
2381 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2382 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2383 if (state_binder != draw_binder) {
2384 // changing the surface is like destroying and
2385 // recreating the DisplayDevice, so we just remove it
2386 // from the drawing state, so that it get re-added
2387 // below.
2388 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2389 if (hw != nullptr) hw->disconnect(getHwComposer());
2390 mDisplays.removeItem(display);
2391 mDrawingState.displays.removeItemsAt(i);
2392 dc--;
2393 // at this point we must loop to the next item
2394 continue;
2395 }
2396
2397 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2398 if (disp != nullptr) {
2399 if (state.layerStack != draw[i].layerStack) {
2400 disp->setLayerStack(state.layerStack);
2401 }
2402 if ((state.orientation != draw[i].orientation) ||
2403 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2404 disp->setProjection(state.orientation, state.viewport, state.frame);
2405 }
2406 if (state.width != draw[i].width || state.height != draw[i].height) {
2407 disp->setDisplaySize(state.width, state.height);
2408 }
2409 }
2410 }
2411 ++i;
2412 }
2413
2414 // find displays that were added
2415 // (ie: in current state but not in drawing state)
2416 for (size_t i = 0; i < cc; i++) {
2417 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2418 const DisplayDeviceState& state(curr[i]);
2419
2420 sp<DisplaySurface> dispSurface;
2421 sp<IGraphicBufferProducer> producer;
2422 sp<IGraphicBufferProducer> bqProducer;
2423 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002424 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425
2426 int32_t hwcId = -1;
2427 if (state.isVirtualDisplay()) {
2428 // Virtual displays without a surface are dormant:
2429 // they have external state (layer stack, projection,
2430 // etc.) but no internal state (i.e. a DisplayDevice).
2431 if (state.surface != nullptr) {
2432 // Allow VR composer to use virtual displays.
2433 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2434 int width = 0;
2435 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2436 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2437 int height = 0;
2438 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2439 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2440 int intFormat = 0;
2441 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2442 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2443 auto format = static_cast<android_pixel_format_t>(intFormat);
2444
2445 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2446 }
2447
2448 // TODO: Plumb requested format back up to consumer
2449
2450 sp<VirtualDisplaySurface> vds =
2451 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2452 bqProducer, bqConsumer,
2453 state.displayName);
2454
2455 dispSurface = vds;
2456 producer = vds;
2457 }
2458 } else {
2459 ALOGE_IF(state.surface != nullptr,
2460 "adding a supported display, but rendering "
2461 "surface is provided (%p), ignoring it",
2462 state.surface.get());
2463
2464 hwcId = state.type;
2465 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2466 producer = bqProducer;
2467 }
2468
2469 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002470
Lloyd Pique347200f2017-12-14 17:00:15 -08002471 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002472 bool hasWideColorSupport = false;
2473 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002474 std::vector<ColorMode> modes =
Lloyd Piquefcd86612017-12-14 17:15:36 -08002475 getHwComposer().getColorModes(state.type);
Peiyong Lina52f0292018-03-14 17:26:31 -07002476 for (ColorMode colorMode : modes) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002477 switch (colorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002478 case ColorMode::DISPLAY_P3:
2479 case ColorMode::ADOBE_RGB:
2480 case ColorMode::DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002481 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002482 break;
2483 default:
2484 break;
2485 }
2486 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002487 }
2488
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002489 bool hasHdrSupport = false;
2490 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2491 getHwComposer().getHdrCapabilities(state.type);
2492 if (hdrCapabilities) {
2493 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2494 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2495 hasHdrSupport = iter != types.cend();
2496 }
2497
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 sp<DisplayDevice> hw =
2499 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002500 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002501 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002502
Peiyong Lina52f0292018-03-14 17:26:31 -07002503 ColorMode defaultColorMode = ColorMode::NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002504 if (hasWideColorSupport) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002505 defaultColorMode = ColorMode::SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002506 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002507 setActiveColorModeInternal(hw, defaultColorMode);
2508 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 hw->setLayerStack(state.layerStack);
2510 hw->setProjection(state.orientation, state.viewport, state.frame);
2511 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002512
Lloyd Pique347200f2017-12-14 17:00:15 -08002513 mDisplays.add(display, hw);
2514 if (!state.isVirtualDisplay()) {
2515 mEventThread->onHotplugReceived(state.type, true);
2516 }
2517 }
2518 }
2519 }
2520 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002521
2522 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002523}
2524
Mathias Agopian87baae12012-07-31 12:38:26 -07002525void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002526{
Dan Stoza7dde5992015-05-22 09:51:44 -07002527 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002528 mCurrentState.traverseInZOrder([](Layer* layer) {
2529 layer->notifyAvailableFrames();
2530 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 /*
2533 * Traversal of the children
2534 * (perform the transaction for each of them if needed)
2535 */
2536
Mathias Agopian3559b072012-08-15 13:46:03 -07002537 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002538 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002540 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541
2542 const uint32_t flags = layer->doTransaction(0);
2543 if (flags & Layer::eVisibleRegion)
2544 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002545 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546 }
2547
2548 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002549 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550 */
2551
Mathias Agopiane57f2922012-08-09 16:29:12 -07002552 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556
Mathias Agopian84300952012-11-21 16:02:13 -08002557 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2558 // The transform hint might have changed for some layers
2559 // (either because a display has changed, or because a layer
2560 // as changed).
2561 //
2562 // Walk through all the layers in currentLayers,
2563 // and update their transform hint.
2564 //
2565 // If a layer is visible only on a single display, then that
2566 // display is used to calculate the hint, otherwise we use the
2567 // default display.
2568 //
2569 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2570 // the hint is set before we acquire a buffer from the surface texture.
2571 //
2572 // NOTE: layer transactions have taken place already, so we use their
2573 // drawing state. However, SurfaceFlinger's own transaction has not
2574 // happened yet, so we must use the current state layer list
2575 // (soon to become the drawing state list).
2576 //
2577 sp<const DisplayDevice> disp;
2578 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002579 bool first = true;
2580 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002581 // NOTE: we rely on the fact that layers are sorted by
2582 // layerStack first (so we don't have to traverse the list
2583 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002584 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002585 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002586 currentlayerStack = layerStack;
2587 // figure out if this layerstack is mirrored
2588 // (more than one display) if so, pick the default display,
2589 // if not, pick the only display it's on.
2590 disp.clear();
2591 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2592 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002593 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002594 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002595 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002596 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002597 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002598 break;
2599 }
2600 }
2601 }
2602 }
Chet Haase91d25932013-04-11 15:24:55 -07002603
Robert Carr56a0b9a2017-12-04 16:06:13 -08002604 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002605 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002606 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2607 // redraw after transform hint changes. See bug 8508397.
2608
2609 // could be null when this layer is using a layerStack
2610 // that is not visible on any display. Also can occur at
2611 // screen off/on times.
2612 disp = getDefaultDisplayDeviceLocked();
2613 }
2614 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002615 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002616 if (disp != nullptr) {
2617 layer->updateTransformHint(disp);
2618 }
Robert Carr2047fae2016-11-28 14:09:09 -08002619
2620 first = false;
2621 });
Mathias Agopian84300952012-11-21 16:02:13 -08002622 }
2623
2624
Mathias Agopian3559b072012-08-15 13:46:03 -07002625 /*
2626 * Perform our own transaction if needed
2627 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628
2629 if (mLayersAdded) {
2630 mLayersAdded = false;
2631 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002632 mVisibleRegionsDirty = true;
2633 }
2634
2635 // some layers might have been removed, so
2636 // we need to update the regions they're exposing.
2637 if (mLayersRemoved) {
2638 mLayersRemoved = false;
2639 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002640 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002642 // this layer is not visible anymore
2643 // TODO: we could traverse the tree from front to back and
2644 // compute the actual visible region
2645 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 Region visibleReg;
2647 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002648 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002649 }
Robert Carr2047fae2016-11-28 14:09:09 -08002650 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 }
2652
2653 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002654
2655 updateCursorAsync();
2656}
2657
2658void SurfaceFlinger::updateCursorAsync()
2659{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2661 auto& displayDevice = mDisplays[displayId];
2662 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002663 continue;
2664 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665
2666 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2667 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002668 }
2669 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002670}
2671
2672void SurfaceFlinger::commitTransaction()
2673{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002674 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002675 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002676 for (const auto& l : mLayersPendingRemoval) {
2677 recordBufferingStats(l->getName().string(),
2678 l->getOccupancyHistory(true));
2679 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002680 }
2681 mLayersPendingRemoval.clear();
2682 }
2683
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002684 // If this transaction is part of a window animation then the next frame
2685 // we composite should be considered an animation as well.
2686 mAnimCompositionPending = mAnimTransactionPending;
2687
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689 mDrawingState.traverseInZOrder([](Layer* layer) {
2690 layer->commitChildList();
2691 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002692 mTransactionPending = false;
2693 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002694 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695}
2696
Chia-I Wuab0c3192017-08-01 11:29:00 -07002697void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002698 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699{
Mathias Agopian841cde52012-03-01 15:44:37 -08002700 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002702
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703 Region aboveOpaqueLayers;
2704 Region aboveCoveredLayers;
2705 Region dirty;
2706
Mathias Agopian87baae12012-07-31 12:38:26 -07002707 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708
Robert Carr2047fae2016-11-28 14:09:09 -08002709 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002711 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712
Jesse Hall01e29052013-02-19 16:13:35 -08002713 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002714 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002715 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002716
Mathias Agopianab028732010-03-16 16:41:46 -07002717 /*
2718 * opaqueRegion: area of a surface that is fully opaque.
2719 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002721
2722 /*
2723 * visibleRegion: area of a surface that is visible on screen
2724 * and not fully transparent. This is essentially the layer's
2725 * footprint minus the opaque regions above it.
2726 * Areas covered by a translucent surface are considered visible.
2727 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002729
2730 /*
2731 * coveredRegion: area of a surface that is covered by all
2732 * visible regions above it (which includes the translucent areas).
2733 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002735
Jesse Halla8026d22012-09-25 13:25:04 -07002736 /*
2737 * transparentRegion: area of a surface that is hinted to be completely
2738 * transparent. This is only used to tell when the layer has no visible
2739 * non-transparent regions and can be removed from the layer list. It
2740 * does not affect the visibleRegion of this layer or any layers
2741 * beneath it. The hint may not be correct if apps don't respect the
2742 * SurfaceView restrictions (which, sadly, some don't).
2743 */
2744 Region transparentRegion;
2745
Mathias Agopianab028732010-03-16 16:41:46 -07002746
2747 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002748 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002749 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002753 if (!visibleRegion.isEmpty()) {
2754 // Remove the transparent area from the visible region
2755 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002756 if (tr.preserveRects()) {
2757 // transform the transparent region
2758 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002760 // transformation too complex, can't do the
2761 // transparent region optimization.
2762 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002763 }
Mathias Agopianab028732010-03-16 16:41:46 -07002764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765
Mathias Agopianab028732010-03-16 16:41:46 -07002766 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002767 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002768 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002769 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2770 // the opaque region is the layer's footprint
2771 opaqueRegion = visibleRegion;
2772 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 }
2774 }
2775
Robert Carre5f4f692018-01-12 13:12:28 -08002776 if (visibleRegion.isEmpty()) {
2777 layer->clearVisibilityRegions();
2778 return;
2779 }
2780
Mathias Agopianab028732010-03-16 16:41:46 -07002781 // Clip the covered region to the visible region
2782 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2783
2784 // Update aboveCoveredLayers for next (lower) layer
2785 aboveCoveredLayers.orSelf(visibleRegion);
2786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 // subtract the opaque region covered by the layers above us
2788 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789
2790 // compute this layer's dirty region
2791 if (layer->contentDirty) {
2792 // we need to invalidate the whole region
2793 dirty = visibleRegion;
2794 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 layer->contentDirty = false;
2797 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002798 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002799 * the exposed region consists of two components:
2800 * 1) what's VISIBLE now and was COVERED before
2801 * 2) what's EXPOSED now less what was EXPOSED before
2802 *
2803 * note that (1) is conservative, we start with the whole
2804 * visible region but only keep what used to be covered by
2805 * something -- which mean it may have been exposed.
2806 *
2807 * (2) handles areas that were not covered by anything but got
2808 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002809 */
Mathias Agopianab028732010-03-16 16:41:46 -07002810 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 const Region oldVisibleRegion = layer->visibleRegion;
2812 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002813 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2814 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
2816 dirty.subtractSelf(aboveOpaqueLayers);
2817
2818 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002819 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820
Mathias Agopianab028732010-03-16 16:41:46 -07002821 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002823
Jesse Halla8026d22012-09-25 13:25:04 -07002824 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 layer->setVisibleRegion(visibleRegion);
2826 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002827 layer->setVisibleNonTransparentRegion(
2828 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002829 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830
Mathias Agopian87baae12012-07-31 12:38:26 -07002831 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832}
2833
Chia-I Wuab0c3192017-08-01 11:29:00 -07002834void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002835 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002836 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002837 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002838 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002839 }
2840 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002841}
2842
Dan Stoza6b9454d2014-11-07 16:00:59 -08002843bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 ALOGV("handlePageFlip");
2846
Brian Andersond6927fb2016-07-23 23:37:30 -07002847 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848
Mathias Agopian4fec8732012-06-29 14:12:52 -07002849 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002850 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002851 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002852
2853 // Store the set of layers that need updates. This set must not change as
2854 // buffers are being latched, as this could result in a deadlock.
2855 // Example: Two producers share the same command stream and:
2856 // 1.) Layer 0 is latched
2857 // 2.) Layer 0 gets a new frame
2858 // 2.) Layer 1 gets a new frame
2859 // 3.) Layer 1 is latched.
2860 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2861 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002862 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002863 if (layer->hasQueuedFrame()) {
2864 frameQueued = true;
2865 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002866 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002867 } else {
2868 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002869 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002870 } else {
2871 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002872 }
Robert Carr2047fae2016-11-28 14:09:09 -08002873 });
2874
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002876 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002877 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002878 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002879 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002880 newDataLatched = true;
2881 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002882 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002883
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002884 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885
2886 // If we will need to wake up at some time in the future to deal with a
2887 // queued frame that shouldn't be displayed during this vsync period, wake
2888 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002889 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002890 signalLayerUpdate();
2891 }
2892
2893 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002894 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895}
2896
Mathias Agopianad456f92011-01-13 17:53:01 -08002897void SurfaceFlinger::invalidateHwcGeometry()
2898{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002899 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002900}
2901
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002902
Fabien Sanglard830b8472016-11-30 16:35:58 -08002903void SurfaceFlinger::doDisplayComposition(
2904 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002905 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906{
Dan Stoza71433162014-02-04 16:22:36 -08002907 // We only need to actually compose the display if:
2908 // 1) It is being handled by hardware composer, which may need this to
2909 // keep its virtual display state machine in sync, or
2910 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002911 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002912 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002913 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002914 return;
2915 }
2916
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002918 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002919
2920 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002921 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922}
2923
Chia-I Wub02087d2017-11-09 10:19:54 -08002924bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002925{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002927
Chia-I Wub02087d2017-11-09 10:19:54 -08002928 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002929 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002931
2932 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002933 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2934 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002935 if (applyColorMatrix) {
2936 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2937 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2938 }
2939
David Sodman105b7dc2017-11-04 20:28:14 -07002940 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
David Sodman4b7c4bc2017-11-17 12:13:59 -08002941 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 if (hasClientComposition) {
2943 ALOGV("hasClientComposition");
2944
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002945 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002946 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002947 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002948 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2949 }
2950 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2951
Chia-I Wu7f402902017-11-09 12:51:10 -08002952 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002953 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002955 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002956
2957 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002958 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002959 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2960 }
2961 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002962 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002963
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002964 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002965 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002967 // when using overlays, we assume a fully transparent framebuffer
2968 // NOTE: we could reduce how much we need to clear, for instance
2969 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002970 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002971 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002972 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002973 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002974 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002975 // we're left with the letterbox region
2976 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002978
2979 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002981
Mathias Agopianb9494d52012-04-18 02:28:45 -07002982 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002983 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002984 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002986 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002987 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002988
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002990 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002991 // scissor on the main display. It should never be needed
2992 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 const Rect& bounds(displayDevice->getBounds());
2994 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002995 if (scissor != bounds) {
2996 // scissor doesn't match the screen's dimensions, so we
2997 // need to clear everything outside of it and enable
2998 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002999
Mathias Agopianf45c5102012-10-24 16:29:17 -07003000 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003001 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003002 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003003 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003004 }
3005 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003006 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003007
Mathias Agopian85d751c2012-08-29 16:59:24 -07003008 /*
3009 * and then, render the layers targeted at the framebuffer
3010 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003011
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 ALOGV("Rendering client layers");
3013 const Transform& displayTransform = displayDevice->getTransform();
3014 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07003015 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 bool firstLayer = true;
3017 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003018 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 displayTransform.transform(layer->visibleRegion)));
3020 ALOGV("Layer: %s", layer->getName().string());
3021 ALOGV(" Composition type: %s",
3022 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07003023 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 switch (layer->getCompositionType(hwcId)) {
3025 case HWC2::Composition::Cursor:
3026 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08003027 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07003029 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07003031 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07003033 // never clear the very first layer since we're
3034 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07003035 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003036 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003037 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003038 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07003040 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07003041 break;
3042 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003044 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003045 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003046 } else {
3047 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003050 }
3051 } else {
3052 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003053 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003054 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003055 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003056 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003057 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003058 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003059 }
3060 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003061
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003062 if (applyColorMatrix) {
3063 getRenderEngine().setupColorTransform(oldColorMatrix);
3064 }
3065
Mathias Agopianf45c5102012-10-24 16:29:17 -07003066 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003067 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003068 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069}
3070
Fabien Sanglard830b8472016-11-30 16:35:58 -08003071void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3072 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003073 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003074 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075}
3076
Dan Stoza7d89d062015-04-30 13:29:25 -07003077status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003078 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003079 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 const sp<Layer>& lbc,
3081 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003082{
Dan Stoza7d89d062015-04-30 13:29:25 -07003083 // add this layer to the current state list
3084 {
3085 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003087 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3088 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003089 return NO_MEMORY;
3090 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 if (parent == nullptr) {
3092 mCurrentState.layersSortedByZ.add(lbc);
3093 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003094 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003095 ALOGE("addClientLayer called with a removed parent");
3096 return NAME_NOT_FOUND;
3097 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 parent->addChild(lbc);
3099 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003100
Dan Stoza101d8dc2018-02-27 15:42:25 -08003101 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003102 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3103 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3104 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3105 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3106 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003107 mLayersAdded = true;
3108 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003109 }
3110
Mathias Agopian96f08192010-06-02 23:28:45 -07003111 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003112 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003113
Dan Stoza7d89d062015-04-30 13:29:25 -07003114 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003115}
3116
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003117status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003118 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003119 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3120}
Robert Carr7f9b8992017-03-10 11:08:39 -08003121
chaviwca27f252018-02-06 16:46:39 -08003122status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3123 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003124 if (layer->isPendingRemoval()) {
3125 return NO_ERROR;
3126 }
3127
Robert Carr1f0a16a2016-10-24 16:27:39 -07003128 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003129 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003130 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003131 if (topLevelOnly) {
3132 return NO_ERROR;
3133 }
3134
Chia-I Wu98f1c102017-05-30 14:54:08 -07003135 sp<Layer> ancestor = p;
3136 while (ancestor->getParent() != nullptr) {
3137 ancestor = ancestor->getParent();
3138 }
3139 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3140 ALOGE("removeLayer called with a layer whose parent has been removed");
3141 return NAME_NOT_FOUND;
3142 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003143
3144 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003145 } else {
3146 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003147 }
3148
Robert Carr136e2f62017-02-08 17:54:29 -08003149 // As a matter of normal operation, the LayerCleaner will produce a second
3150 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3151 // so we will succeed in promoting it, but it's already been removed
3152 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3153 // otherwise something has gone wrong and we are leaking the layer.
3154 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3156 layer->getName().string(),
3157 (p != nullptr) ? p->getName().string() : "no-parent");
3158 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003159 } else if (index < 0) {
3160 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162
Chia-I Wuc6657022017-08-15 11:18:17 -07003163 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003164 mLayersPendingRemoval.add(layer);
3165 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003166 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 setTransactionFlags(eTransactionNeeded);
3168 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169}
3170
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003171uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003172 return android_atomic_release_load(&mTransactionFlags);
3173}
3174
Mathias Agopian3f844832013-08-07 21:24:32 -07003175uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3177}
3178
Mathias Agopian3f844832013-08-07 21:24:32 -07003179uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3181 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003182 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 }
3184 return old;
3185}
3186
chaviwca27f252018-02-06 16:46:39 -08003187bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3188 for (const ComposerState& state : states) {
3189 // Here we need to check that the interface we're given is indeed
3190 // one of our own. A malicious client could give us a nullptr
3191 // IInterface, or one of its own or even one of our own but a
3192 // different type. All these situations would cause us to crash.
3193 if (state.client == nullptr) {
3194 return true;
3195 }
3196
3197 sp<IBinder> binder = IInterface::asBinder(state.client);
3198 if (binder == nullptr) {
3199 return true;
3200 }
3201
3202 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3203 return true;
3204 }
3205 }
3206 return false;
3207}
3208
Mathias Agopian8b33f032012-07-24 20:43:54 -07003209void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003210 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003211 const Vector<DisplayState>& displays,
3212 uint32_t flags)
3213{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003214 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003215 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003216 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003217
chaviwca27f252018-02-06 16:46:39 -08003218 if (containsAnyInvalidClientState(states)) {
3219 return;
3220 }
3221
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003222 if (flags & eAnimation) {
3223 // For window updates that are part of an animation we must wait for
3224 // previous animation "frames" to be handled.
3225 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003226 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003227 if (CC_UNLIKELY(err != NO_ERROR)) {
3228 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003229 // caller after a few seconds.
3230 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3231 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003232 mAnimTransactionPending = false;
3233 break;
3234 }
3235 }
3236 }
3237
chaviwca27f252018-02-06 16:46:39 -08003238 for (const DisplayState& display : displays) {
3239 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003240 }
3241
chaviwca27f252018-02-06 16:46:39 -08003242 for (const ComposerState& state : states) {
3243 transactionFlags |= setClientStateLocked(state);
3244 }
3245
3246 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3247 // as destroyed should only occur after setting all other states. This is to allow for a
3248 // child re-parent to happen before marking its original parent as destroyed (which would
3249 // then mark the child as destroyed).
3250 for (const ComposerState& state : states) {
3251 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003252 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003253
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003254 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3255 // anyway. This can be used as a flush mechanism for previous async transactions.
3256 // Empty animation transaction can be used to simulate back-pressure, so also force a
3257 // transaction for empty animation transactions.
3258 if (transactionFlags == 0 &&
3259 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003260 transactionFlags = eTransactionNeeded;
3261 }
3262
Mathias Agopian386aa982011-11-07 21:58:03 -08003263 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003264 if (mInterceptor->isEnabled()) {
3265 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003266 }
Irvel468051e2016-06-13 16:44:44 -07003267
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 // this triggers the transaction
3269 setTransactionFlags(transactionFlags);
3270
3271 // if this is a synchronous transaction, wait for it to take effect
3272 // before returning.
3273 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003274 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003275 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003276 if (flags & eAnimation) {
3277 mAnimTransactionPending = true;
3278 }
3279 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003280 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3281 if (CC_UNLIKELY(err != NO_ERROR)) {
3282 // just in case something goes wrong in SF, return to the
3283 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003284 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3285 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003286 break;
3287 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 }
3290}
3291
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3293{
Jesse Hall9a143922012-10-04 16:29:19 -07003294 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3295 if (dpyIdx < 0)
3296 return 0;
3297
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003299 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003300 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003301 const uint32_t what = s.what;
3302 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003303 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003304 disp.surface = s.surface;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 }
3308 if (what & DisplayState::eLayerStackChanged) {
3309 if (disp.layerStack != s.layerStack) {
3310 disp.layerStack = s.layerStack;
3311 flags |= eDisplayTransactionNeeded;
3312 }
3313 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003314 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003315 if (disp.orientation != s.orientation) {
3316 disp.orientation = s.orientation;
3317 flags |= eDisplayTransactionNeeded;
3318 }
3319 if (disp.frame != s.frame) {
3320 disp.frame = s.frame;
3321 flags |= eDisplayTransactionNeeded;
3322 }
3323 if (disp.viewport != s.viewport) {
3324 disp.viewport = s.viewport;
3325 flags |= eDisplayTransactionNeeded;
3326 }
3327 }
Michael Lentine47e45402014-07-18 15:34:25 -07003328 if (what & DisplayState::eDisplaySizeChanged) {
3329 if (disp.width != s.width) {
3330 disp.width = s.width;
3331 flags |= eDisplayTransactionNeeded;
3332 }
3333 if (disp.height != s.height) {
3334 disp.height = s.height;
3335 flags |= eDisplayTransactionNeeded;
3336 }
3337 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003338 }
3339 return flags;
3340}
3341
chaviwca27f252018-02-06 16:46:39 -08003342uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3343 const layer_state_t& s = composerState.state;
3344 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3345
Mathias Agopian13127d82013-03-05 17:47:11 -08003346 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003347 if (layer == nullptr) {
3348 return 0;
3349 }
3350
3351 if (layer->isPendingRemoval()) {
3352 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3353 return 0;
3354 }
3355
3356 uint32_t flags = 0;
3357
3358 const uint32_t what = s.what;
3359 bool geometryAppliesWithResize =
3360 what & layer_state_t::eGeometryAppliesWithResize;
3361 if (what & layer_state_t::ePositionChanged) {
3362 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3363 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003364 }
chaviw8b3871a2017-11-01 17:41:01 -07003365 }
3366 if (what & layer_state_t::eLayerChanged) {
3367 // NOTE: index needs to be calculated before we update the state
3368 const auto& p = layer->getParent();
3369 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003370 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003371 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003372 mCurrentState.layersSortedByZ.removeAt(idx);
3373 mCurrentState.layersSortedByZ.add(layer);
3374 // we need traversal (state changed)
3375 // AND transaction (list changed)
3376 flags |= eTransactionNeeded|eTraversalNeeded;
3377 }
chaviw8b3871a2017-11-01 17:41:01 -07003378 } else {
3379 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003380 flags |= eTransactionNeeded|eTraversalNeeded;
3381 }
3382 }
chaviw8b3871a2017-11-01 17:41:01 -07003383 }
3384 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003385 // NOTE: index needs to be calculated before we update the state
3386 const auto& p = layer->getParent();
3387 if (p == nullptr) {
3388 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3389 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3390 mCurrentState.layersSortedByZ.removeAt(idx);
3391 mCurrentState.layersSortedByZ.add(layer);
3392 // we need traversal (state changed)
3393 // AND transaction (list changed)
3394 flags |= eTransactionNeeded|eTraversalNeeded;
3395 }
3396 } else {
3397 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3398 flags |= eTransactionNeeded|eTraversalNeeded;
3399 }
chaviw8b3871a2017-11-01 17:41:01 -07003400 }
3401 }
3402 if (what & layer_state_t::eSizeChanged) {
3403 if (layer->setSize(s.w, s.h)) {
3404 flags |= eTraversalNeeded;
3405 }
3406 }
3407 if (what & layer_state_t::eAlphaChanged) {
3408 if (layer->setAlpha(s.alpha))
3409 flags |= eTraversalNeeded;
3410 }
3411 if (what & layer_state_t::eColorChanged) {
3412 if (layer->setColor(s.color))
3413 flags |= eTraversalNeeded;
3414 }
3415 if (what & layer_state_t::eMatrixChanged) {
3416 if (layer->setMatrix(s.matrix))
3417 flags |= eTraversalNeeded;
3418 }
3419 if (what & layer_state_t::eTransparentRegionChanged) {
3420 if (layer->setTransparentRegionHint(s.transparentRegion))
3421 flags |= eTraversalNeeded;
3422 }
3423 if (what & layer_state_t::eFlagsChanged) {
3424 if (layer->setFlags(s.flags, s.mask))
3425 flags |= eTraversalNeeded;
3426 }
3427 if (what & layer_state_t::eCropChanged) {
3428 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3429 flags |= eTraversalNeeded;
3430 }
3431 if (what & layer_state_t::eFinalCropChanged) {
3432 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3433 flags |= eTraversalNeeded;
3434 }
3435 if (what & layer_state_t::eLayerStackChanged) {
3436 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3437 // We only allow setting layer stacks for top level layers,
3438 // everything else inherits layer stack from its parent.
3439 if (layer->hasParent()) {
3440 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3441 layer->getName().string());
3442 } else if (idx < 0) {
3443 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3444 "that also does not appear in the top level layer list. Something"
3445 " has gone wrong.", layer->getName().string());
3446 } else if (layer->setLayerStack(s.layerStack)) {
3447 mCurrentState.layersSortedByZ.removeAt(idx);
3448 mCurrentState.layersSortedByZ.add(layer);
3449 // we need traversal (state changed)
3450 // AND transaction (list changed)
3451 flags |= eTransactionNeeded|eTraversalNeeded;
3452 }
3453 }
3454 if (what & layer_state_t::eDeferTransaction) {
3455 if (s.barrierHandle != nullptr) {
3456 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3457 } else if (s.barrierGbp != nullptr) {
3458 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3459 if (authenticateSurfaceTextureLocked(gbp)) {
3460 const auto& otherLayer =
3461 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3462 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3463 } else {
3464 ALOGE("Attempt to defer transaction to to an"
3465 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003466 }
3467 }
chaviw8b3871a2017-11-01 17:41:01 -07003468 // We don't trigger a traversal here because if no other state is
3469 // changed, we don't want this to cause any more work
3470 }
3471 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003472 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003473 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003474 if (!hadParent) {
3475 mCurrentState.layersSortedByZ.remove(layer);
3476 }
chaviw8b3871a2017-11-01 17:41:01 -07003477 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003478 }
chaviw8b3871a2017-11-01 17:41:01 -07003479 }
3480 if (what & layer_state_t::eReparentChildren) {
3481 if (layer->reparentChildren(s.reparentHandle)) {
3482 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003483 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003484 }
chaviw8b3871a2017-11-01 17:41:01 -07003485 if (what & layer_state_t::eDetachChildren) {
3486 layer->detachChildren();
3487 }
3488 if (what & layer_state_t::eOverrideScalingModeChanged) {
3489 layer->setOverrideScalingMode(s.overrideScalingMode);
3490 // We don't trigger a traversal here because if no other state is
3491 // changed, we don't want this to cause any more work
3492 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003493 return flags;
3494}
3495
chaviwca27f252018-02-06 16:46:39 -08003496void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3497 const layer_state_t& state = composerState.state;
3498 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3499
3500 sp<Layer> layer(client->getLayerUser(state.surface));
3501 if (layer == nullptr) {
3502 return;
3503 }
3504
3505 if (layer->isPendingRemoval()) {
3506 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3507 return;
3508 }
3509
3510 if (state.what & layer_state_t::eDestroySurface) {
3511 removeLayerLocked(mStateLock, layer);
3512 }
3513}
3514
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003515status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003516 const String8& name,
3517 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003519 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3520 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003522 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003523 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003524 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003525 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003526 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003527
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003528 status_t result = NO_ERROR;
3529
3530 sp<Layer> layer;
3531
Cody Northropbc755282017-03-31 12:00:08 -06003532 String8 uniqueName = getUniqueLayerName(name);
3533
Mathias Agopian3165cc22012-08-08 19:42:09 -07003534 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3535 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003536 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003537 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003538 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540 break;
chaviw13fdc492017-06-27 12:40:18 -07003541 case ISurfaceComposerClient::eFXSurfaceColor:
3542 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003543 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003544 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 break;
3546 default:
3547 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 break;
3549 }
3550
Dan Stoza7d89d062015-04-30 13:29:25 -07003551 if (result != NO_ERROR) {
3552 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003554
Chia-I Wuab0c3192017-08-01 11:29:00 -07003555 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3556 // TODO b/64227542
3557 if (windowType == 441731) {
3558 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3559 layer->setPrimaryDisplayOnly();
3560 }
3561
Albert Chaulk479c60c2017-01-27 14:21:34 -05003562 layer->setInfo(windowType, ownerUid);
3563
Robert Carr1f0a16a2016-10-24 16:27:39 -07003564 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003565 if (result != NO_ERROR) {
3566 return result;
3567 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003568 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003569
3570 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572}
3573
Cody Northropbc755282017-03-31 12:00:08 -06003574String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3575{
3576 bool matchFound = true;
3577 uint32_t dupeCounter = 0;
3578
3579 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3580 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3581
3582 // Loop over layers until we're sure there is no matching name
3583 while (matchFound) {
3584 matchFound = false;
3585 mDrawingState.traverseInZOrder([&](Layer* layer) {
3586 if (layer->getName() == uniqueName) {
3587 matchFound = true;
3588 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3589 }
3590 });
3591 }
3592
3593 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3594
3595 return uniqueName;
3596}
3597
David Sodman0c69cad2017-08-21 12:12:51 -07003598status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3600 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601{
3602 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003603 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 case PIXEL_FORMAT_TRANSPARENT:
3605 case PIXEL_FORMAT_TRANSLUCENT:
3606 format = PIXEL_FORMAT_RGBA_8888;
3607 break;
3608 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003609 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 break;
3611 }
3612
David Sodman0c69cad2017-08-21 12:12:51 -07003613 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3614 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003616 *handle = layer->getHandle();
3617 *gbp = layer->getProducer();
3618 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620
David Sodman0c69cad2017-08-21 12:12:51 -07003621 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623}
3624
chaviw13fdc492017-06-27 12:40:18 -07003625status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003626 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003627 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628{
chaviw13fdc492017-06-27 12:40:18 -07003629 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003631 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003632}
3633
Mathias Agopianac9fa422013-02-11 16:40:36 -08003634status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635{
Robert Carr9524cb32017-02-13 11:32:32 -08003636 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003637 status_t err = NO_ERROR;
3638 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003639 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003640 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003641 err = removeLayer(l);
3642 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3643 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003644 }
3645 return err;
3646}
3647
Mathias Agopian13127d82013-03-05 17:47:11 -08003648status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003649{
Mathias Agopian67106042013-03-14 19:18:13 -07003650 // called by ~LayerCleaner() when all references to the IBinder (handle)
3651 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003652 sp<Layer> l = layer.promote();
3653 if (l == nullptr) {
3654 // The layer has already been removed, carry on
3655 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003656 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003657 // If we have a parent, then we can continue to live as long as it does.
3658 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003659}
3660
Mathias Agopianb60314a2012-04-10 22:09:54 -07003661// ---------------------------------------------------------------------------
3662
Andy McFadden13a082e2012-08-24 10:16:42 -07003663void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003664 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003665 Vector<ComposerState> state;
3666 Vector<DisplayState> displays;
3667 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003668 d.what = DisplayState::eDisplayProjectionChanged |
3669 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003670 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003671 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003672 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003673 d.frame.makeInvalid();
3674 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003675 d.width = 0;
3676 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003677 displays.add(d);
3678 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003679 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3680 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003681
David Sodman105b7dc2017-11-04 20:28:14 -07003682 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003683 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003684 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003685
Brian Andersond0010582017-03-07 13:20:31 -08003686 // Use phase of 0 since phase is not known.
3687 // Use latency of 0, which will snap to the ideal latency.
3688 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003689}
3690
3691void SurfaceFlinger::initializeDisplays() {
3692 class MessageScreenInitialized : public MessageBase {
3693 SurfaceFlinger* flinger;
3694 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003695 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003696 virtual bool handler() {
3697 flinger->onInitializeDisplays();
3698 return true;
3699 }
3700 };
3701 sp<MessageBase> msg = new MessageScreenInitialized(this);
3702 postMessageAsync(msg); // we may be called from main thread, use async message
3703}
3704
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003706 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3708 this);
3709 int32_t type = hw->getDisplayType();
3710 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003711
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003712 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003713 return;
3714 }
3715
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003716 hw->setPowerMode(mode);
3717 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3718 ALOGW("Trying to set power mode for virtual display");
3719 return;
3720 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003721
Lloyd Pique4dccc412018-01-22 17:21:36 -08003722 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003723 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003724 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3725 if (idx < 0) {
3726 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3727 return;
3728 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003729 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003730 }
3731
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003732 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003733 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003735 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3736 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003737 // FIXME: eventthread only knows about the main display right now
3738 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003739 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003742 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003743 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003744 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003745
3746 struct sched_param param = {0};
3747 param.sched_priority = 1;
3748 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3749 ALOGW("Couldn't set SCHED_FIFO on display on");
3750 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003751 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003752 // Turn off the display
3753 struct sched_param param = {0};
3754 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3755 ALOGW("Couldn't set SCHED_OTHER on display off");
3756 }
3757
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003758 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3759 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003760 disableHardwareVsync(true); // also cancels any in-progress resync
3761
Mathias Agopiancde87a32012-09-13 14:09:01 -07003762 // FIXME: eventthread only knows about the main display right now
3763 mEventThread->onScreenReleased();
3764 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003765
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 getHwComposer().setPowerMode(type, mode);
3767 mVisibleRegionsDirty = true;
3768 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003769 } else if (mode == HWC_POWER_MODE_DOZE ||
3770 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003771 // Update display while dozing
3772 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003773 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3774 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003775 // FIXME: eventthread only knows about the main display right now
3776 mEventThread->onScreenAcquired();
3777 resyncToHardwareVsync(true);
3778 }
3779 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3780 // Leave display going to doze
3781 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3782 disableHardwareVsync(true); // also cancels any in-progress resync
3783 // FIXME: eventthread only knows about the main display right now
3784 mEventThread->onScreenReleased();
3785 }
3786 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003787 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003788 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003789 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003791}
3792
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3794 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003795 SurfaceFlinger& mFlinger;
3796 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003798 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003799 MessageSetPowerMode(SurfaceFlinger& flinger,
3800 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3801 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003802 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003804 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003805 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003806 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003807 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003808 ALOGW("Attempt to set power mode = %d for virtual display",
3809 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003810 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003811 mFlinger.setPowerModeInternal(
3812 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003813 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003814 return true;
3815 }
3816 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003817 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003818 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003819}
3820
3821// ---------------------------------------------------------------------------
3822
Lloyd Pique755e3192018-01-31 16:46:15 -08003823status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3824 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003825 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003826
Mathias Agopianbd115332013-04-18 16:41:04 -07003827 IPCThreadState* ipc = IPCThreadState::self();
3828 const int pid = ipc->getCallingPid();
3829 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003830
Mathias Agopianbd115332013-04-18 16:41:04 -07003831 if ((uid != AID_SHELL) &&
3832 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003833 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003834 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003835 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003836 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003837 // (this would indicate SF is stuck, but we want to be able to
3838 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003839 status_t err = mStateLock.timedLock(s2ns(1));
3840 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003841 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003842 result.appendFormat(
3843 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3844 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003845 }
3846
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847 bool dumpAll = true;
3848 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003850
3851 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003852 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003853 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3854 dumpAll = false;
3855 }
3856
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003857 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003858 if ((index < numArgs) &&
3859 (args[index] == String16("--list"))) {
3860 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003861 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003862 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863 }
3864
3865 if ((index < numArgs) &&
3866 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003867 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003868 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003869 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003871
3872 if ((index < numArgs) &&
3873 (args[index] == String16("--latency-clear"))) {
3874 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003875 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003876 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003877 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003878
3879 if ((index < numArgs) &&
3880 (args[index] == String16("--dispsync"))) {
3881 index++;
3882 mPrimaryDispSync.dump(result);
3883 dumpAll = false;
3884 }
Dan Stozab90cf072015-03-05 11:05:59 -08003885
3886 if ((index < numArgs) &&
3887 (args[index] == String16("--static-screen"))) {
3888 index++;
3889 dumpStaticScreenStats(result);
3890 dumpAll = false;
3891 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003892
3893 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003894 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003895 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003896 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003897 dumpAll = false;
3898 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003899
3900 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3901 index++;
3902 dumpWideColorInfo(result);
3903 dumpAll = false;
3904 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003905
3906 if ((index < numArgs) &&
3907 (args[index] == String16("--enable-layer-stats"))) {
3908 index++;
3909 mLayerStats.enable();
3910 dumpAll = false;
3911 }
3912
3913 if ((index < numArgs) &&
3914 (args[index] == String16("--disable-layer-stats"))) {
3915 index++;
3916 mLayerStats.disable();
3917 dumpAll = false;
3918 }
3919
3920 if ((index < numArgs) &&
3921 (args[index] == String16("--clear-layer-stats"))) {
3922 index++;
3923 mLayerStats.clear();
3924 dumpAll = false;
3925 }
3926
3927 if ((index < numArgs) &&
3928 (args[index] == String16("--dump-layer-stats"))) {
3929 index++;
3930 mLayerStats.dump(result);
3931 dumpAll = false;
3932 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003934
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003936 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003937 }
3938
Mathias Agopian9795c422009-08-26 16:36:26 -07003939 if (locked) {
3940 mStateLock.unlock();
3941 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 }
3943 write(fd, result.string(), result.size());
3944 return NO_ERROR;
3945}
3946
Dan Stozac7014012014-02-14 15:03:43 -08003947void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3948 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949{
Robert Carr2047fae2016-11-28 14:09:09 -08003950 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003951 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003952 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953}
3954
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957{
3958 String8 name;
3959 if (index < args.size()) {
3960 name = String8(args[index]);
3961 index++;
3962 }
3963
David Sodman105b7dc2017-11-04 20:28:14 -07003964 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003965 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003966 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003967
3968 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003969 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003970 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003971 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003972 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003973 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003974 }
Robert Carr2047fae2016-11-28 14:09:09 -08003975 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976 }
3977}
3978
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003980 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003981{
3982 String8 name;
3983 if (index < args.size()) {
3984 name = String8(args[index]);
3985 index++;
3986 }
3987
Robert Carr2047fae2016-11-28 14:09:09 -08003988 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003990 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003991 }
Robert Carr2047fae2016-11-28 14:09:09 -08003992 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003993
Svetoslavd85084b2014-03-20 10:28:31 -07003994 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995}
3996
Jamie Gennis6547ff42013-07-16 20:12:42 -07003997// This should only be called from the main thread. Otherwise it would need
3998// the lock and should use mCurrentState rather than mDrawingState.
3999void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004000 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004001 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004002 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004003
4004 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4005}
4006
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004007void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004008{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004009 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004010
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004011 if (isLayerTripleBufferingDisabled())
4012 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004013
4014 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004015 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004016 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004017 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004018 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4019 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004020 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004021}
4022
Dan Stozab90cf072015-03-05 11:05:59 -08004023void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4024{
4025 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004026 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4027 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004028 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004029 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004030 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4031 b + 1, bucketTimeSec, percent);
4032 }
David Sodman4a36e932017-11-07 14:29:47 -08004033 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004035 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004036 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004037 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004038}
4039
Dan Stozae77c7662016-05-13 11:37:28 -07004040void SurfaceFlinger::recordBufferingStats(const char* layerName,
4041 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004042 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4043 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004044 for (const auto& segment : history) {
4045 if (!segment.usedThirdBuffer) {
4046 stats.twoBufferTime += segment.totalTime;
4047 }
4048 if (segment.occupancyAverage < 1.0f) {
4049 stats.doubleBufferedTime += segment.totalTime;
4050 } else if (segment.occupancyAverage < 2.0f) {
4051 stats.tripleBufferedTime += segment.totalTime;
4052 }
4053 ++stats.numSegments;
4054 stats.totalTime += segment.totalTime;
4055 }
4056}
4057
Brian Andersond6927fb2016-07-23 23:37:30 -07004058void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4059 result.appendFormat("Layer frame timestamps:\n");
4060
4061 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4062 const size_t count = currentLayers.size();
4063 for (size_t i=0 ; i<count ; i++) {
4064 currentLayers[i]->dumpFrameEvents(result);
4065 }
4066}
4067
Dan Stozae77c7662016-05-13 11:37:28 -07004068void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4069 result.append("Buffering stats:\n");
4070 result.append(" [Layer name] <Active time> <Two buffer> "
4071 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004072 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004073 typedef std::tuple<std::string, float, float, float> BufferTuple;
4074 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004075 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004076 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004077 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004078 if (stats.numSegments == 0) {
4079 continue;
4080 }
4081 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4082 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4083 stats.totalTime;
4084 float doubleBufferRatio = static_cast<float>(
4085 stats.doubleBufferedTime) / stats.totalTime;
4086 float tripleBufferRatio = static_cast<float>(
4087 stats.tripleBufferedTime) / stats.totalTime;
4088 sorted.insert({activeTime, {name, twoBufferRatio,
4089 doubleBufferRatio, tripleBufferRatio}});
4090 }
4091 for (const auto& sortedPair : sorted) {
4092 float activeTime = sortedPair.first;
4093 const BufferTuple& values = sortedPair.second;
4094 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4095 std::get<0>(values).c_str(), activeTime,
4096 std::get<1>(values), std::get<2>(values),
4097 std::get<3>(values));
4098 }
4099 result.append("\n");
4100}
4101
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004102void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4103 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01004104 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004105
4106 // TODO: print out if wide-color mode is active or not
4107
4108 for (size_t d = 0; d < mDisplays.size(); d++) {
4109 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4110 int32_t hwcId = displayDevice->getHwcDisplayId();
4111 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4112 continue;
4113 }
4114
4115 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004116 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004117 for (auto&& mode : modes) {
4118 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4119 }
4120
Peiyong Lina52f0292018-03-14 17:26:31 -07004121 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004122 result.appendFormat(" Current color mode: %s (%d)\n",
4123 decodeColorMode(currentMode).c_str(), currentMode);
4124 }
4125 result.append("\n");
4126}
4127
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004128LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004129 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004130 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4131 const State& state = useDrawing ? mDrawingState : mCurrentState;
4132 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004133 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004134 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004135 });
4136
4137 return layersProto;
4138}
4139
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004140LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4141 LayersProto layersProto;
4142
4143 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
4144 SizeProto* resolution = layersProto.mutable_resolution();
4145 resolution->set_w(displayDevice->getWidth());
4146 resolution->set_h(displayDevice->getHeight());
4147
4148 mDrawingState.traverseInZOrder([&](Layer* layer) {
4149 if (!layer->visibleRegion.isEmpty() &&
4150 layer->getBE().mHwcLayers.count(hwcId)) {
4151 LayerProto* layerProto = layersProto.add_layers();
4152 layer->writeToProto(layerProto, hwcId);
4153 }
4154 });
4155
4156 return layersProto;
4157}
4158
Mathias Agopian74d211a2013-04-22 16:55:35 +02004159void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4160 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004161{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004162 bool colorize = false;
4163 if (index < args.size()
4164 && (args[index] == String16("--color"))) {
4165 colorize = true;
4166 index++;
4167 }
4168
4169 Colorizer colorizer(colorize);
4170
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004171 // figure out if we're stuck somewhere
4172 const nsecs_t now = systemTime();
4173 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4174 const nsecs_t inTransaction(mDebugInTransaction);
4175 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4176 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4177
4178 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004179 * Dump library configuration.
4180 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004181
4182 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004183 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004184 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004185 appendSfConfigString(result);
4186 appendUiConfigString(result);
4187 appendGuiConfigString(result);
4188 result.append("\n");
4189
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004190 result.append("\nWide-Color information:\n");
4191 dumpWideColorInfo(result);
4192
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004193 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004194 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004195 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004196 result.append(SyncFeatures::getInstance().toString());
4197 result.append("\n");
4198
David Sodman105b7dc2017-11-04 20:28:14 -07004199 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004200
Andy McFadden41d67d72014-04-25 16:58:34 -07004201 colorizer.bold(result);
4202 result.append("DispSync configuration: ");
4203 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004204 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004205 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004206 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004207 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004208 result.append("\n");
4209
Dan Stozab90cf072015-03-05 11:05:59 -08004210 // Dump static screen stats
4211 result.append("\n");
4212 dumpStaticScreenStats(result);
4213 result.append("\n");
4214
Dan Stozae77c7662016-05-13 11:37:28 -07004215 dumpBufferingStats(result);
4216
Andy McFadden4803b742012-09-24 19:07:20 -07004217 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004218 * Dump the visible layer list
4219 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004220 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004221 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004222 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4223 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004224 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004225
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004226 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004227 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004228 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004229
4230 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004231 * Dump Display state
4232 */
4233
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004234 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004235 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004237 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4238 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004239 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004240 }
4241
4242 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004243 * Dump SurfaceFlinger global state
4244 */
4245
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004246 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004247 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249
Mathias Agopian888c8222012-08-04 21:10:38 -07004250 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004251 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004252
David Sodmanbc815282017-11-05 18:57:52 -08004253 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004255 if (hw) {
4256 hw->undefinedRegion.dump(result, "undefinedRegion");
4257 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4258 hw->getOrientation(), hw->isDisplayOn());
4259 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004260 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261 " last eglSwapBuffers() time: %f us\n"
4262 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004263 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264 " refresh-rate : %f fps\n"
4265 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004266 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004267 " gpu_to_cpu_unsupported : %d\n"
4268 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269 mLastSwapBufferTime/1000.0,
4270 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004271 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004272 1e9 / activeConfig->getVsyncPeriod(),
4273 activeConfig->getDpiX(),
4274 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004275 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004276
Mathias Agopian74d211a2013-04-22 16:55:35 +02004277 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279
Mathias Agopian74d211a2013-04-22 16:55:35 +02004280 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004281 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282
4283 /*
4284 * VSYNC state
4285 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004286 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004287 result.append("\n");
4288
4289 /*
4290 * HWC layer minidump
4291 */
4292 for (size_t d = 0; d < mDisplays.size(); d++) {
4293 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4294 int32_t hwcId = displayDevice->getHwcDisplayId();
4295 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4296 continue;
4297 }
4298
4299 result.appendFormat("Display %d HWC layers:\n", hwcId);
4300 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004301 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004302 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004303 });
Dan Stozae22aec72016-08-01 13:20:59 -07004304 result.append("\n");
4305 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004306
4307 /*
4308 * Dump HWComposer state
4309 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004310 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004311 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004312 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004313 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004314 result.appendFormat(" h/w composer %s\n",
4315 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004316 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317
4318 /*
4319 * Dump gralloc state
4320 */
4321 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4322 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004323
4324 /*
4325 * Dump VrFlinger state if in use.
4326 */
4327 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4328 result.append("VrFlinger state:\n");
4329 result.append(mVrFlinger->Dump().c_str());
4330 result.append("\n");
4331 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332}
4333
Mathias Agopian13127d82013-03-05 17:47:11 -08004334const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004335SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004336 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004337 wp<IBinder> dpy;
4338 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4339 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4340 dpy = mDisplays.keyAt(i);
4341 break;
4342 }
4343 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004344 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004345 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4346 // Just use the primary display so we have something to return
4347 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4348 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004349 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004350}
4351
Keun young Park63f165f2012-08-31 10:53:36 -07004352bool SurfaceFlinger::startDdmConnection()
4353{
4354 void* libddmconnection_dso =
4355 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4356 if (!libddmconnection_dso) {
4357 return false;
4358 }
4359 void (*DdmConnection_start)(const char* name);
4360 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004361 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004362 if (!DdmConnection_start) {
4363 dlclose(libddmconnection_dso);
4364 return false;
4365 }
4366 (*DdmConnection_start)(getServiceName());
4367 return true;
4368}
4369
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004370status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 switch (code) {
4372 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004373 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004374 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004375 case CLEAR_ANIMATION_FRAME_STATS:
4376 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004377 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004378 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004379 case ENABLE_VSYNC_INJECTIONS:
4380 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 {
4382 // codes that require permission check
4383 IPCThreadState* ipc = IPCThreadState::self();
4384 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004385 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004386 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004387 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004388 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004389 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004390 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004391 break;
4392 }
Robert Carr1db73f62016-12-21 12:58:51 -08004393 /*
4394 * Calling setTransactionState is safe, because you need to have been
4395 * granted a reference to Client* and Handle* to do anything with it.
4396 *
4397 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4398 */
4399 case SET_TRANSACTION_STATE:
4400 case CREATE_SCOPED_CONNECTION:
4401 {
4402 return OK;
4403 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004404 case CAPTURE_SCREEN:
4405 {
4406 // codes that require permission check
4407 IPCThreadState* ipc = IPCThreadState::self();
4408 const int pid = ipc->getCallingPid();
4409 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004410 if ((uid != AID_GRAPHICS) &&
4411 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004412 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004413 return PERMISSION_DENIED;
4414 }
4415 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416 }
chaviwa76b2712017-09-20 12:02:26 -07004417 case CAPTURE_LAYERS: {
4418 IPCThreadState* ipc = IPCThreadState::self();
4419 const int pid = ipc->getCallingPid();
4420 const int uid = ipc->getCallingUid();
4421 if ((uid != AID_GRAPHICS) &&
4422 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4423 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4424 return PERMISSION_DENIED;
4425 }
4426 break;
4427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004428 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004429 return OK;
4430}
4431
4432status_t SurfaceFlinger::onTransact(
4433 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4434{
4435 status_t credentialCheck = CheckTransactCodeCredentials(code);
4436 if (credentialCheck != OK) {
4437 return credentialCheck;
4438 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004439
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004440 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4441 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004442 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004443 IPCThreadState* ipc = IPCThreadState::self();
4444 const int uid = ipc->getCallingUid();
4445 if (CC_UNLIKELY(uid != AID_SYSTEM
4446 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004447 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004448 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004449 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004450 return PERMISSION_DENIED;
4451 }
4452 int n;
4453 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004454 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004455 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004456 return NO_ERROR;
4457 case 1002: // SHOW_UPDATES
4458 n = data.readInt32();
4459 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004460 invalidateHwcGeometry();
4461 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004462 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004463 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004464 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004465 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004466 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004467 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004468 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004469 setTransactionFlags(
4470 eTransactionNeeded|
4471 eDisplayTransactionNeeded|
4472 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004473 return NO_ERROR;
4474 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004475 case 1006:{ // send empty update
4476 signalRefresh();
4477 return NO_ERROR;
4478 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004479 case 1008: // toggle use of hw composer
4480 n = data.readInt32();
4481 mDebugDisableHWC = n ? 1 : 0;
4482 invalidateHwcGeometry();
4483 repaintEverything();
4484 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004485 case 1009: // toggle use of transform hint
4486 n = data.readInt32();
4487 mDebugDisableTransformHint = n ? 1 : 0;
4488 invalidateHwcGeometry();
4489 repaintEverything();
4490 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004491 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004492 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 reply->writeInt32(0);
4494 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004495 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004496 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497 return NO_ERROR;
4498 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004499 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004500 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004501 return NO_ERROR;
4502 }
4503 case 1014: {
4504 // daltonize
4505 n = data.readInt32();
4506 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004507 case 1:
4508 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4509 break;
4510 case 2:
4511 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4512 break;
4513 case 3:
4514 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4515 break;
4516 default:
4517 mDaltonizer.setType(ColorBlindnessType::None);
4518 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004519 }
4520 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004521 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004522 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004523 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004524 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004525 invalidateHwcGeometry();
4526 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004527 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 case 1015: {
4530 // apply a color matrix
4531 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004533 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004534 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004535 for (size_t j = 0; j < 4; j++) {
4536 mColorMatrix[i][j] = data.readFloat();
4537 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004538 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004539 } else {
4540 mColorMatrix = mat4();
4541 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004542
4543 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4544 // the division by w in the fragment shader
4545 float4 lastRow(transpose(mColorMatrix)[3]);
4546 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4547 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4548 }
4549
Alan Viverette9c5a3332013-09-12 20:04:35 -07004550 invalidateHwcGeometry();
4551 repaintEverything();
4552 return NO_ERROR;
4553 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004554 // This is an experimental interface
4555 // Needs to be shifted to proper binder interface when we productize
4556 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004557 n = data.readInt32();
4558 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004559 return NO_ERROR;
4560 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004561 case 1017: {
4562 n = data.readInt32();
4563 mForceFullDamage = static_cast<bool>(n);
4564 return NO_ERROR;
4565 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004566 case 1018: { // Modify Choreographer's phase offset
4567 n = data.readInt32();
4568 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4569 return NO_ERROR;
4570 }
4571 case 1019: { // Modify SurfaceFlinger's phase offset
4572 n = data.readInt32();
4573 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4574 return NO_ERROR;
4575 }
Irvel468051e2016-06-13 16:44:44 -07004576 case 1020: { // Layer updates interceptor
4577 n = data.readInt32();
4578 if (n) {
4579 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004580 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004581 }
4582 else{
4583 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004584 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004585 }
4586 return NO_ERROR;
4587 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004588 case 1021: { // Disable HWC virtual displays
4589 n = data.readInt32();
4590 mUseHwcVirtualDisplays = !n;
4591 return NO_ERROR;
4592 }
Romain Guy0147a172017-06-01 13:53:56 -07004593 case 1022: { // Set saturation boost
4594 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4595
4596 invalidateHwcGeometry();
4597 repaintEverything();
4598 return NO_ERROR;
4599 }
Romain Guy54f154a2017-10-24 21:40:32 +01004600 case 1023: { // Set native mode
4601 mForceNativeColorMode = data.readInt32() == 1;
4602
4603 invalidateHwcGeometry();
4604 repaintEverything();
4605 return NO_ERROR;
4606 }
4607 case 1024: { // Is wide color gamut rendering/color management supported?
4608 reply->writeBool(hasWideColorDisplay);
4609 return NO_ERROR;
4610 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004611 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004612 n = data.readInt32();
4613 if (n) {
4614 ALOGV("LayerTracing enabled");
4615 mTracing.enable();
4616 doTracing("tracing.enable");
4617 reply->writeInt32(NO_ERROR);
4618 } else {
4619 ALOGV("LayerTracing disabled");
4620 status_t err = mTracing.disable();
4621 reply->writeInt32(err);
4622 }
4623 return NO_ERROR;
4624 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004625 case 1026: { // Get layer tracing status
4626 reply->writeBool(mTracing.isEnabled());
4627 return NO_ERROR;
4628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 }
4630 }
4631 return err;
4632}
4633
Steven Thomas6d8110b2017-08-31 18:24:21 -07004634void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004635 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004636 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004637}
4638
Steven Thomas6d8110b2017-08-31 18:24:21 -07004639void SurfaceFlinger::repaintEverything() {
4640 ConditionalLock _l(mStateLock,
4641 std::this_thread::get_id() != mMainThreadId);
4642 repaintEverythingLocked();
4643}
4644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004645// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4646class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004647public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004648 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4649 ~WindowDisconnector() {
4650 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004651 }
4652
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004653private:
4654 ANativeWindow* mWindow;
4655 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004656};
4657
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004658status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4659 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4660 int32_t minLayerZ, int32_t maxLayerZ,
4661 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004662 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004664
chaviwa76b2712017-09-20 12:02:26 -07004665 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4666
4667 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004668 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4669
chaviwa76b2712017-09-20 12:02:26 -07004670 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4671
4672 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4673 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004674 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004675}
4676
4677status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004678 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004679 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004680 ATRACE_CALL();
4681
4682 class LayerRenderArea : public RenderArea {
4683 public:
Robert Carr578038f2018-03-09 12:25:24 -08004684 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4685 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4686 : RenderArea(reqHeight, reqWidth),
4687 mLayer(layer),
4688 mCrop(crop),
4689 mFlinger(flinger),
4690 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004691 Rect getBounds() const override {
4692 const Layer::State& layerState(mLayer->getDrawingState());
4693 return Rect(layerState.active.w, layerState.active.h);
4694 }
4695 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4696 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4697 bool isSecure() const override { return false; }
4698 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004699 const Transform& getTransform() const { return mTransform; }
4700
4701 class ReparentForDrawing {
4702 public:
4703 const sp<Layer>& oldParent;
4704 const sp<Layer>& newParent;
4705
4706 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4707 : oldParent(oldParent), newParent(newParent) {
4708 oldParent->reparentChildrenForDrawing(newParent);
4709 }
4710 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4711 };
4712
4713 void render(std::function<void()> drawLayers) override {
4714 if (!mChildrenOnly) {
4715 mTransform = mLayer->getTransform().inverse();
4716 drawLayers();
4717 } else {
4718 Rect bounds = getBounds();
4719 screenshotParentLayer =
4720 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4721 bounds.getWidth(), bounds.getHeight(), 0);
4722
4723 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4724 drawLayers();
4725 }
4726 }
chaviwa76b2712017-09-20 12:02:26 -07004727
chaviw7206d492017-11-10 16:16:12 -08004728 Rect getSourceCrop() const override {
4729 if (mCrop.isEmpty()) {
4730 return getBounds();
4731 } else {
4732 return mCrop;
4733 }
4734 }
chaviwa76b2712017-09-20 12:02:26 -07004735 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004736 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004737
4738 private:
chaviw7206d492017-11-10 16:16:12 -08004739 const sp<Layer> mLayer;
4740 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004741
4742 // In the "childrenOnly" case we reparent the children to a screenshot
4743 // layer which has no properties set and which does not draw.
4744 sp<ContainerLayer> screenshotParentLayer;
4745 Transform mTransform;
4746
4747 SurfaceFlinger* mFlinger;
4748 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004749 };
4750
4751 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4752 auto parent = layerHandle->owner.promote();
4753
chaviw7206d492017-11-10 16:16:12 -08004754 if (parent == nullptr || parent->isPendingRemoval()) {
4755 ALOGE("captureLayers called with a removed parent");
4756 return NAME_NOT_FOUND;
4757 }
4758
Robert Carr578038f2018-03-09 12:25:24 -08004759 const int uid = IPCThreadState::self()->getCallingUid();
4760 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4761 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4762 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4763 return PERMISSION_DENIED;
4764 }
4765
chaviw7206d492017-11-10 16:16:12 -08004766 Rect crop(sourceCrop);
4767 if (sourceCrop.width() <= 0) {
4768 crop.left = 0;
4769 crop.right = parent->getCurrentState().active.w;
4770 }
4771
4772 if (sourceCrop.height() <= 0) {
4773 crop.top = 0;
4774 crop.bottom = parent->getCurrentState().active.h;
4775 }
4776
4777 int32_t reqWidth = crop.width() * frameScale;
4778 int32_t reqHeight = crop.height() * frameScale;
4779
Robert Carr578038f2018-03-09 12:25:24 -08004780 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004781
Robert Carr578038f2018-03-09 12:25:24 -08004782 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004783 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4784 if (!layer->isVisible()) {
4785 return;
Robert Carr578038f2018-03-09 12:25:24 -08004786 } else if (childrenOnly && layer == parent.get()) {
4787 return;
chaviwa76b2712017-09-20 12:02:26 -07004788 }
4789 visitor(layer);
4790 });
4791 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004792 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004793}
4794
4795status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4796 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004797 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004798 bool useIdentityTransform) {
4799 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004800
chaviwa76b2712017-09-20 12:02:26 -07004801 renderArea.updateDimensions();
4802
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004803 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4804 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4805 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4806 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004807
4808 // This mutex protects syncFd and captureResult for communication of the return values from the
4809 // main thread back to this Binder thread
4810 std::mutex captureMutex;
4811 std::condition_variable captureCondition;
4812 std::unique_lock<std::mutex> captureLock(captureMutex);
4813 int syncFd = -1;
4814 std::optional<status_t> captureResult;
4815
Robert Carr03480e22018-01-04 16:02:06 -08004816 const int uid = IPCThreadState::self()->getCallingUid();
4817 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4818
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004819 sp<LambdaMessage> message = new LambdaMessage([&]() {
4820 // If there is a refresh pending, bug out early and tell the binder thread to try again
4821 // after the refresh.
4822 if (mRefreshPending) {
4823 ATRACE_NAME("Skipping screenshot for now");
4824 std::unique_lock<std::mutex> captureLock(captureMutex);
4825 captureResult = std::make_optional<status_t>(EAGAIN);
4826 captureCondition.notify_one();
4827 return;
4828 }
4829
4830 status_t result = NO_ERROR;
4831 int fd = -1;
4832 {
4833 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004834 renderArea.render([&]() {
4835 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4836 useIdentityTransform, forSystem, &fd);
4837 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004838 }
4839
4840 {
4841 std::unique_lock<std::mutex> captureLock(captureMutex);
4842 syncFd = fd;
4843 captureResult = std::make_optional<status_t>(result);
4844 captureCondition.notify_one();
4845 }
4846 });
4847
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004848 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004849 if (result == NO_ERROR) {
4850 captureCondition.wait(captureLock, [&]() { return captureResult; });
4851 while (*captureResult == EAGAIN) {
4852 captureResult.reset();
4853 result = postMessageAsync(message);
4854 if (result != NO_ERROR) {
4855 return result;
4856 }
4857 captureCondition.wait(captureLock, [&]() { return captureResult; });
4858 }
4859 result = *captureResult;
4860 }
4861
4862 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004863 sync_wait(syncFd, -1);
4864 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004865 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004866
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004867 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004868}
4869
chaviwa76b2712017-09-20 12:02:26 -07004870void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4871 TraverseLayersFunction traverseLayers, bool yswap,
4872 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004873 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004874
Lloyd Pique144e1162017-12-20 16:44:52 -08004875 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004876
4877 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004878 const auto raWidth = renderArea.getWidth();
4879 const auto raHeight = renderArea.getHeight();
4880
4881 const auto reqWidth = renderArea.getReqWidth();
4882 const auto reqHeight = renderArea.getReqHeight();
4883 Rect sourceCrop = renderArea.getSourceCrop();
4884
4885 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4886 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004887
Dan Stozac1879002014-05-22 15:59:05 -07004888 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004889 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004890 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004891 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004892 }
4893
4894 // ensure that sourceCrop is inside screen
4895 if (sourceCrop.left < 0) {
4896 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4897 }
chaviwa76b2712017-09-20 12:02:26 -07004898 if (sourceCrop.right > raWidth) {
4899 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004900 }
4901 if (sourceCrop.top < 0) {
4902 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4903 }
chaviwa76b2712017-09-20 12:02:26 -07004904 if (sourceCrop.bottom > raHeight) {
4905 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004906 }
4907
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004908 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004909 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004910 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004911 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4912 }
4913 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004914
Mathias Agopian180f10d2013-04-10 22:55:41 -07004915 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004916 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004917
4918 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004919 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4920 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004921 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004922
4923 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004924 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004925
chaviwa76b2712017-09-20 12:02:26 -07004926 traverseLayers([&](Layer* layer) {
4927 if (filtering) layer->setFiltering(true);
David Sodmandc5e0622018-01-05 23:10:57 -08004928 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004929 if (filtering) layer->setFiltering(false);
4930 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004931}
4932
chaviwa76b2712017-09-20 12:02:26 -07004933status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4934 TraverseLayersFunction traverseLayers,
4935 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004936 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004937 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004938 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004939 ATRACE_CALL();
4940
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004941 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004942
4943 traverseLayers([&](Layer* layer) {
4944 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4945 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004946
Robert Carr03480e22018-01-04 16:02:06 -08004947 // We allow the system server to take screenshots of secure layers for
4948 // use in situations like the Screen-rotation animation and place
4949 // the impetus on WindowManager to not persist them.
4950 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004951 ALOGW("FB is protected: PERMISSION_DENIED");
4952 return PERMISSION_DENIED;
4953 }
4954
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004955 // this binds the given EGLImage as a framebuffer for the
4956 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004957 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004958 if (bufferBond.getStatus() != NO_ERROR) {
4959 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004960 return INVALID_OPERATION;
4961 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004962
Dan Stozaabcda352017-06-01 14:37:39 -07004963 // this will in fact render into our dequeued buffer
4964 // via an FBO, which means we didn't have to create
4965 // an EGLSurface and therefore we're not
4966 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004967 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004968
Dan Stozaabcda352017-06-01 14:37:39 -07004969 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004970 getRenderEngine().finish();
4971 *outSyncFd = -1;
4972
chaviwa76b2712017-09-20 12:02:26 -07004973 const auto reqWidth = renderArea.getReqWidth();
4974 const auto reqHeight = renderArea.getReqHeight();
4975
Dan Stozaabcda352017-06-01 14:37:39 -07004976 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4977 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004978 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004979 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004980 } else {
4981 base::unique_fd syncFd = getRenderEngine().flush();
4982 if (syncFd < 0) {
4983 getRenderEngine().finish();
4984 }
4985 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004986 }
4987
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004988 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004989}
4990
Mathias Agopiand5556842013-09-19 17:08:37 -07004991void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004992 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004993 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004994 for (size_t y = 0; y < h; y++) {
4995 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4996 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004997 if (p[x] != 0xFF000000) return;
4998 }
4999 }
chaviwa76b2712017-09-20 12:02:26 -07005000 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005001
Robert Carr2047fae2016-11-28 14:09:09 -08005002 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005003 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005004 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005005 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5006 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5007 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5008 static_cast<float>(state.color.a));
5009 i++;
5010 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005011 }
5012}
5013
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005014// ---------------------------------------------------------------------------
5015
Dan Stoza412903f2017-04-27 13:42:17 -07005016void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5017 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005018}
5019
Dan Stoza412903f2017-04-27 13:42:17 -07005020void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5021 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005022}
5023
chaviwa76b2712017-09-20 12:02:26 -07005024void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5025 int32_t maxLayerZ,
5026 const LayerVector::Visitor& visitor) {
5027 // We loop through the first level of layers without traversing,
5028 // as we need to interpret min/max layer Z in the top level Z space.
5029 for (const auto& layer : mDrawingState.layersSortedByZ) {
5030 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5031 continue;
5032 }
5033 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005034 // relative layers are traversed in Layer::traverseInZOrder
5035 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005036 continue;
5037 }
5038 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005039 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5040 return;
5041 }
chaviwa76b2712017-09-20 12:02:26 -07005042 if (!layer->isVisible()) {
5043 return;
5044 }
5045 visitor(layer);
5046 });
5047 }
5048}
5049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005051
Mathias Agopian3f844832013-08-07 21:24:32 -07005052#if defined(__gl_h_)
5053#error "don't include gl/gl.h in this file"
5054#endif
5055
5056#if defined(__gl2_h_)
5057#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005058#endif