blob: af53a323dea37b5858f439811449b4f69579da59 [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();
650
David Sodmanbc815282017-11-05 18:57:52 -0800651 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700652
Wei Wangf9b05ee2017-07-19 20:59:39 -0700653 // Inform native graphics APIs whether the present timestamp is supported:
654 if (getHwComposer().hasCapability(
655 HWC2::Capability::PresentFenceIsNotReliable)) {
656 mStartPropertySetThread = new StartPropertySetThread(false);
657 } else {
658 mStartPropertySetThread = new StartPropertySetThread(true);
659 }
660
661 if (mStartPropertySetThread->Start() != NO_ERROR) {
662 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800664
Dan Stoza9e56aa02015-11-02 13:00:03 -0800665 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700666}
667
Romain Guy11d63f42017-07-20 12:47:14 -0700668void SurfaceFlinger::readPersistentProperties() {
669 char value[PROPERTY_VALUE_MAX];
670
671 property_get("persist.sys.sf.color_saturation", value, "1.0");
672 mSaturation = atof(value);
673 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100674
675 property_get("persist.sys.sf.native_mode", value, "0");
676 mForceNativeColorMode = atoi(value) == 1;
677 if (mForceNativeColorMode) {
678 ALOGV("Forcing native color mode");
679 }
Romain Guy11d63f42017-07-20 12:47:14 -0700680}
681
Mathias Agopiana67e4182012-06-19 17:26:12 -0700682void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Start boot animation service by setting a property mailbox
684 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800686 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687 if (mStartPropertySetThread->join() != NO_ERROR) {
688 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800689 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800693 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
Mathias Agopian875d8e12013-06-07 15:35:48 -0700696size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800697 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700698}
699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800701
Jamie Gennis582270d2011-08-17 18:19:00 -0700702bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800704 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800705 return authenticateSurfaceTextureLocked(bufferProducer);
706}
707
708bool SurfaceFlinger::authenticateSurfaceTextureLocked(
709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800710 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800711 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800712}
713
Brian Anderson6b376712017-04-04 10:51:39 -0700714status_t SurfaceFlinger::getSupportedFrameTimestamps(
715 std::vector<FrameEvent>* outSupported) const {
716 *outSupported = {
717 FrameEvent::REQUESTED_PRESENT,
718 FrameEvent::ACQUIRE,
719 FrameEvent::LATCH,
720 FrameEvent::FIRST_REFRESH_START,
721 FrameEvent::LAST_REFRESH_START,
722 FrameEvent::GPU_COMPOSITION_DONE,
723 FrameEvent::DEQUEUE_READY,
724 FrameEvent::RELEASE,
725 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700726 ConditionalLock _l(mStateLock,
727 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700728 if (!getHwComposer().hasCapability(
729 HWC2::Capability::PresentFenceIsNotReliable)) {
730 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
731 }
732 return NO_ERROR;
733}
734
Dan Stoza7f7da322014-05-02 15:26:25 -0700735status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
736 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800737 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 return BAD_VALUE;
739 }
740
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500741 if (!display.get())
742 return NAME_NOT_FOUND;
743
Jesse Hall692c7232012-11-08 15:41:56 -0800744 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700745 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800746 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700747 type = i;
748 break;
749 }
750 }
751
752 if (type < 0) {
753 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700754 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 // TODO: Not sure if display density should handled by SF any longer
757 class Density {
758 static int getDensityFromProperty(char const* propName) {
759 char property[PROPERTY_VALUE_MAX];
760 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800761 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 density = atoi(property);
763 }
764 return density;
765 }
766 public:
767 static int getEmuDensity() {
768 return getDensityFromProperty("qemu.sf.lcd_density"); }
769 static int getBuildDensity() {
770 return getDensityFromProperty("ro.sf.lcd_density"); }
771 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700774
Steven Thomas6d8110b2017-08-31 18:24:21 -0700775 ConditionalLock _l(mStateLock,
776 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 DisplayInfo info = DisplayInfo();
779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 float xdpi = hwConfig->getDpiX();
781 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700782
783 if (type == DisplayDevice::DISPLAY_PRIMARY) {
784 // The density of the device is provided by a build property
785 float density = Density::getBuildDensity() / 160.0f;
786 if (density == 0) {
787 // the build doesn't provide a density -- this is wrong!
788 // use xdpi instead
789 ALOGE("ro.sf.lcd_density must be defined as a build property");
790 density = xdpi / 160.0f;
791 }
792 if (Density::getEmuDensity()) {
793 // if "qemu.sf.lcd_density" is specified, it overrides everything
794 xdpi = ydpi = density = Density::getEmuDensity();
795 density /= 160.0f;
796 }
797 info.density = density;
798
799 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800801 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 } else {
803 // TODO: where should this value come from?
804 static const int TV_DENSITY = 213;
805 info.density = TV_DENSITY / 160.0f;
806 info.orientation = 0;
807 }
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.w = hwConfig->getWidth();
810 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 info.xdpi = xdpi;
812 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900814 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815
Andy McFadden91b2ca82014-06-13 14:04:23 -0700816 // This is how far in advance a buffer must be queued for
817 // presentation at a given time. If you want a buffer to appear
818 // on the screen at time N, you must submit the buffer before
819 // (N - presentationDeadline).
820 //
821 // Normally it's one full refresh period (to give SF a chance to
822 // latch the buffer), but this can be reduced by configuring a
823 // DispSync offset. Any additional delays introduced by the hardware
824 // composer or panel must be accounted for here.
825 //
826 // We add an additional 1ms to allow for processing time and
827 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800829 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
831 // All non-virtual displays are currently considered secure.
832 info.secure = true;
833
Michael Wright28f24d02016-07-12 13:30:53 -0700834 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return NO_ERROR;
838}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700839
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800840status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800842 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700843 return BAD_VALUE;
844 }
845
846 // FIXME for now we always return stats for the primary display
847 memset(stats, 0, sizeof(*stats));
848 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
849 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
850 return NO_ERROR;
851}
852
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700853int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800854 if (display == nullptr) {
855 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800856 return BAD_VALUE;
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
859 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800860 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700861 return device->getActiveConfig();
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
Dan Stoza24a42e92015-03-09 10:04:11 -0700864 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700867void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
868 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
869 this);
870 int32_t type = hw->getDisplayType();
871 int currentMode = hw->getActiveConfig();
872
873 if (mode == currentMode) {
874 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
875 return;
876 }
877
878 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
879 ALOGW("Trying to set config for virtual display");
880 return;
881 }
882
883 hw->setActiveConfig(mode);
884 getHwComposer().setActiveConfig(type, mode);
885}
886
887status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
888 class MessageSetActiveConfig: public MessageBase {
889 SurfaceFlinger& mFlinger;
890 sp<IBinder> mDisplay;
891 int mMode;
892 public:
893 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
894 int mode) :
895 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
896 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700897 Vector<DisplayInfo> configs;
898 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700899 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700900 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700902 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700903 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800905 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700907 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
909 ALOGW("Attempt to set active config = %d for virtual display",
910 mMode);
911 } else {
912 mFlinger.setActiveConfigInternal(hw, mMode);
913 }
914 return true;
915 }
916 };
917 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
918 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700919 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700920}
Michael Wright28f24d02016-07-12 13:30:53 -0700921status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700922 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700923 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
924 return BAD_VALUE;
925 }
926
927 if (!display.get()) {
928 return NAME_NOT_FOUND;
929 }
930
931 int32_t type = NAME_NOT_FOUND;
932 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
933 if (display == mBuiltinDisplays[i]) {
934 type = i;
935 break;
936 }
937 }
938
939 if (type < 0) {
940 return type;
941 }
942
Peiyong Lina52f0292018-03-14 17:26:31 -0700943 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700944 {
945 ConditionalLock _l(mStateLock,
946 std::this_thread::get_id() != mMainThreadId);
947 modes = getHwComposer().getColorModes(type);
948 }
Michael Wright28f24d02016-07-12 13:30:53 -0700949 outColorModes->clear();
950 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
951
952 return NO_ERROR;
953}
954
Peiyong Lina52f0292018-03-14 17:26:31 -0700955ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700957 if (device != nullptr) {
958 return device->getActiveColorMode();
959 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700960 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700961}
962
963void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700964 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700965 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700966 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700967
968 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700969 return;
970 }
971
972 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
973 ALOGW("Trying to set config for virtual display");
974 return;
975 }
976
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600977 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
978 hw->getDisplayType());
979
Michael Wright28f24d02016-07-12 13:30:53 -0700980 hw->setActiveColorMode(mode);
981 getHwComposer().setActiveColorMode(type, mode);
982}
983
984
985status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700986 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700987 class MessageSetActiveColorMode: public MessageBase {
988 SurfaceFlinger& mFlinger;
989 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -0700991 public:
992 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -0700994 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
995 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -0700997 mFlinger.getDisplayColorModes(mDisplay, &modes);
998 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -0700999 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001000 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1001 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001002 return true;
1003 }
1004 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1005 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1007 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001009 ALOGW("Attempt to set active color mode %s %d for virtual display",
1010 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001011 } else {
1012 mFlinger.setActiveColorModeInternal(hw, mMode);
1013 }
1014 return true;
1015 }
1016 };
1017 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1018 postMessageSync(msg);
1019 return NO_ERROR;
1020}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001021
Svetoslavd85084b2014-03-20 10:28:31 -07001022status_t SurfaceFlinger::clearAnimationFrameStats() {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.clearStats();
1025 return NO_ERROR;
1026}
1027
1028status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1029 Mutex::Autolock _l(mStateLock);
1030 mAnimFrameTracker.getStats(outStats);
1031 return NO_ERROR;
1032}
1033
Dan Stozac4f471e2016-03-24 09:31:08 -07001034status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1035 HdrCapabilities* outCapabilities) const {
1036 Mutex::Autolock _l(mStateLock);
1037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001038 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001039 if (displayDevice == nullptr) {
1040 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1041 return BAD_VALUE;
1042 }
1043
1044 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001045 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001046 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001047 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1048 // insert HDR10 as we will force client composition for HDR10
1049 // layers
1050 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1051 types.push_back(HAL_HDR_HDR10);
1052
1053 *outCapabilities = HdrCapabilities(types,
1054 capabilities->getDesiredMaxLuminance(),
1055 capabilities->getDesiredMaxAverageLuminance(),
1056 capabilities->getDesiredMinLuminance());
1057 } else {
1058 *outCapabilities = std::move(*capabilities);
1059 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001060 } else {
1061 return BAD_VALUE;
1062 }
1063
1064 return NO_ERROR;
1065}
1066
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1069 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 if (mInjectVSyncs == enable) {
1072 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001074
1075 if (enable) {
1076 ALOGV("VSync Injections enabled");
1077 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001078 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001079 mInjectorEventThread =
1080 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1081 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001083 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 } else {
1085 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001086 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 }
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001090 });
1091 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
1097
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 if (!mInjectVSyncs) {
1099 ALOGE("VSync Injections not enabled");
1100 return BAD_VALUE;
1101 }
1102 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1103 ALOGV("Injecting VSync inside SurfaceFlinger");
1104 mVSyncInjector->onInjectSyncEvent(when);
1105 }
1106 return NO_ERROR;
1107}
1108
Lloyd Pique755e3192018-01-31 16:46:15 -08001109status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1110 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001111 IPCThreadState* ipc = IPCThreadState::self();
1112 const int pid = ipc->getCallingPid();
1113 const int uid = ipc->getCallingUid();
1114 if ((uid != AID_SHELL) &&
1115 !PermissionCache::checkPermission(sDump, pid, uid)) {
1116 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1117 return PERMISSION_DENIED;
1118 }
1119
1120 // Try to acquire a lock for 1s, fail gracefully
1121 const status_t err = mStateLock.timedLock(s2ns(1));
1122 const bool locked = (err == NO_ERROR);
1123 if (!locked) {
1124 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1125 return TIMED_OUT;
1126 }
1127
1128 outLayers->clear();
1129 mCurrentState.traverseInZOrder([&](Layer* layer) {
1130 outLayers->push_back(layer->getLayerDebugInfo());
1131 });
1132
1133 mStateLock.unlock();
1134 return NO_ERROR;
1135}
1136
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001137// ----------------------------------------------------------------------------
1138
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001139sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1140 ISurfaceComposer::VsyncSource vsyncSource) {
1141 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1142 return mSFEventThread->createEventConnection();
1143 } else {
1144 return mEventThread->createEventConnection();
1145 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001146}
1147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001148// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149
1150void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001151 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152}
1153
1154void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001155 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156}
1157
1158void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001159 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160}
1161
1162void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001163 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001164 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165}
1166
1167status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001168 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001169 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001170}
1171
1172status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001173 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001174 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175 if (res == NO_ERROR) {
1176 msg->wait();
1177 }
1178 return res;
1179}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001180
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001181void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001182 do {
1183 waitForEvent();
1184 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185}
1186
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187void SurfaceFlinger::enableHardwareVsync() {
1188 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001191 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1192 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001194 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195}
1196
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 Mutex::Autolock _l(mHWVsyncLock);
1199
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 if (makeAvailable) {
1201 mHWVsyncAvailable = true;
1202 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001203 // Hardware vsync is not currently available, so abort the resync
1204 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001205 return;
1206 }
1207
David Sodman105b7dc2017-11-04 20:28:14 -07001208 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210
1211 mPrimaryDispSync.reset();
1212 mPrimaryDispSync.setPeriod(period);
1213
1214 if (!mPrimaryHWVsyncEnabled) {
1215 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1217 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryHWVsyncEnabled = true;
1219 }
1220}
1221
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 Mutex::Autolock _l(mHWVsyncLock);
1224 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1226 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 mPrimaryDispSync.endResync();
1228 mPrimaryHWVsyncEnabled = false;
1229 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230 if (makeUnavailable) {
1231 mHWVsyncAvailable = false;
1232 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233}
1234
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235void SurfaceFlinger::resyncWithRateLimit() {
1236 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001237
1238 // No explicit locking is needed here since EventThread holds a lock while calling this method
1239 static nsecs_t sLastResyncAttempted = 0;
1240 const nsecs_t now = systemTime();
1241 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001242 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001243 }
Dan Stoza57164302017-05-08 14:03:54 -07001244 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001245}
1246
Steven Thomasb02664d2017-07-26 18:48:28 -07001247void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1248 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001250 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001251 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001252 return;
1253 }
1254
1255 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001256 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001257 return;
1258 }
1259
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 { // Scope for the lock
1263 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001264 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001265 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001268
1269 if (needsHwVsync) {
1270 enableHardwareVsync();
1271 } else {
1272 disableHardwareVsync(false);
1273 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001274}
1275
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001277 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1278 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279}
1280
Lloyd Pique715a2c12017-12-14 17:18:08 -08001281void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1282 HWC2::Connection connection) {
1283 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1284 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285
Lloyd Piqueba04e622017-12-14 17:11:26 -08001286 // Ignore events that do not have the right sequenceId.
1287 if (sequenceId != getBE().mComposerSequenceId) {
1288 return;
1289 }
1290
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 // Only lock if we're not on the main thread. This function is normally
1292 // called on a hwbinder thread, but for the primary display it's called on
1293 // the main thread with the state lock already held, so don't attempt to
1294 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001295 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001296
Lloyd Pique715a2c12017-12-14 17:18:08 -08001297 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001298
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001299 if (std::this_thread::get_id() == mMainThreadId) {
1300 // Process all pending hot plug events immediately if we are on the main thread.
1301 processDisplayHotplugEventsLocked();
1302 }
1303
Lloyd Piqueba04e622017-12-14 17:11:26 -08001304 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001305}
1306
Steven Thomasb02664d2017-07-26 18:48:28 -07001307void SurfaceFlinger::onRefreshReceived(int sequenceId,
1308 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001309 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001313 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001314}
1315
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001318 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 getHwComposer().setVsyncEnabled(disp,
1320 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001321}
1322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001324void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326 // Clear the drawing state so that the logic inside of
1327 // handleTransactionLocked will fire. It will determine the delta between
1328 // mCurrentState and mDrawingState and re-apply all changes when we make the
1329 // transition.
1330 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001331 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332 mDisplays.clear();
1333}
1334
Steven Thomas050b2c82017-03-06 11:45:16 -08001335void SurfaceFlinger::updateVrFlinger() {
1336 if (!mVrFlinger)
1337 return;
1338 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001340 return;
1341 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342
David Sodman105b7dc2017-11-04 20:28:14 -07001343 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 ALOGE("Vr flinger is only supported for remote hardware composer"
1345 " service connections. Ignoring request to transition to vr"
1346 " flinger.");
1347 mVrFlingerRequestsDisplay = false;
1348 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001349 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 int currentDisplayPowerMode = getDisplayDeviceLocked(
1354 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001361 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001362 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1363 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001364 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
David Sodman105b7dc2017-11-04 20:28:14 -07001366 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1367 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001368
1369 if (vrFlingerRequestsDisplay) {
1370 mVrFlinger->GrantDisplayOwnership();
1371 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374
1375 mVisibleRegionsDirty = true;
1376 invalidateHwcGeometry();
1377
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001378 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1380 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1381 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001384 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 const nsecs_t period = activeConfig->getVsyncPeriod();
1386 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 // Use phase of 0 since phase is not known.
1389 // Use latency of 0, which will snap to the ideal latency.
1390 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392 android_atomic_or(1, &mRepaintEverything);
1393 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394}
1395
Mathias Agopian4fec8732012-06-29 14:12:52 -07001396void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001397 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001398 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001399 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001400 bool frameMissed = !mHadClientComposition &&
1401 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001402 (mPreviousPresentFence->getSignalTime() ==
1403 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001404 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001405 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001406 signalLayerUpdate();
1407 break;
1408 }
1409
Steven Thomas050b2c82017-03-06 11:45:16 -08001410 // Now that we're going to make it to the handleMessageTransaction()
1411 // call below it's safe to call updateVrFlinger(), which will
1412 // potentially trigger a display handoff.
1413 updateVrFlinger();
1414
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 bool refreshNeeded = handleMessageTransaction();
1416 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001417 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001419 // Signal a refresh if a transaction modified the window state,
1420 // a new buffer was latched, or if HWC has requested a full
1421 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001422 signalRefresh();
1423 }
1424 break;
1425 }
1426 case MessageQueue::REFRESH: {
1427 handleMessageRefresh();
1428 break;
1429 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001430 }
1431}
1432
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001434 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001436 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001437 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001438 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001439 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001440}
1441
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445}
1446
1447void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001448 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001449
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001450 mRefreshPending = false;
1451
Pablo Ceballos40845df2016-01-25 17:41:15 -08001452 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001453
Brian Andersond6927fb2016-07-23 23:37:30 -07001454 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001455 rebuildLayerStacks();
1456 setUpHWComposer();
1457 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001458 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001459 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001460 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001461 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001462
David Sodman105b7dc2017-11-04 20:28:14 -07001463 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001464
1465 mHadClientComposition = false;
1466 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1467 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1468 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001469 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001470 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001471
Dan Stoza9e56aa02015-11-02 13:00:03 -08001472 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475void SurfaceFlinger::doDebugFlashRegions()
1476{
1477 // is debugging enabled
1478 if (CC_LIKELY(!mDebugRegion))
1479 return;
1480
1481 const bool repaintEverything = mRepaintEverything;
1482 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1483 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001484 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 // transform the dirty region into this screen's coordinate space
1486 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1487 if (!dirtyRegion.isEmpty()) {
1488 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001489 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490
1491 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001493 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001494 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1495
Mathias Agopianda27af92012-09-13 18:17:13 -07001496 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497 }
1498 }
1499 }
1500
1501 postFramebuffer();
1502
1503 if (mDebugRegion > 1) {
1504 usleep(mDebugRegion * 1000);
1505 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001506
Dan Stoza9e56aa02015-11-02 13:00:03 -08001507 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001508 auto& displayDevice = mDisplays[displayId];
1509 if (!displayDevice->isDisplayOn()) {
1510 continue;
1511 }
1512
David Sodman105b7dc2017-11-04 20:28:14 -07001513 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1514 ALOGE_IF(result != NO_ERROR,
1515 "prepareFrame for display %zd failed:"
1516 " %d (%s)",
1517 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001518 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519}
1520
Adrian Roos1e1a1282017-11-01 19:05:31 +01001521void SurfaceFlinger::doTracing(const char* where) {
1522 ATRACE_CALL();
1523 ATRACE_NAME(where);
1524 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001525 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001526 }
1527}
1528
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001529void SurfaceFlinger::logLayerStats() {
1530 ATRACE_CALL();
1531 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1532 int32_t hwcId = -1;
1533 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1534 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1535 if (displayDevice->isPrimary()) {
1536 hwcId = displayDevice->getHwcDisplayId();
1537 break;
1538 }
1539 }
1540 if (hwcId < 0) {
1541 ALOGE("LayerStats: Hmmm, no primary display?");
1542 return;
1543 }
1544 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1545 }
1546}
1547
Brian Andersond6927fb2016-07-23 23:37:30 -07001548void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001550 ATRACE_CALL();
1551 ALOGV("preComposition");
1552
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001554 mDrawingState.traverseInZOrder([&](Layer* layer) {
1555 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556 needExtraInvalidate = true;
1557 }
Robert Carr2047fae2016-11-28 14:09:09 -08001558 });
1559
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 if (needExtraInvalidate) {
1561 signalLayerUpdate();
1562 }
1563}
1564
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565void SurfaceFlinger::updateCompositorTiming(
1566 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1567 std::shared_ptr<FenceTime>& presentFenceTime) {
1568 // Update queue of past composite+present times and determine the
1569 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001570 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001571 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001572 while (!getBE().mCompositePresentTimes.empty()) {
1573 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574 // Cached values should have been updated before calling this method,
1575 // which helps avoid duplicate syscalls.
1576 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1577 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1578 break;
1579 }
1580 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001581 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582 }
1583
1584 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001585 while (getBE().mCompositePresentTimes.size() > 16) {
1586 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587 }
1588
Brian Andersond0010582017-03-07 13:20:31 -08001589 setCompositorTimingSnapped(
1590 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1591}
1592
1593void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1594 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001595 // Integer division and modulo round toward 0 not -inf, so we need to
1596 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001597 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1599 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1600
Brian Andersond0010582017-03-07 13:20:31 -08001601 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1602 if (idealLatency <= 0) {
1603 idealLatency = vsyncInterval;
1604 }
1605
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 // Snap the latency to a value that removes scheduling jitter from the
1607 // composition and present times, which often have >1ms of jitter.
1608 // Reducing jitter is important if an app attempts to extrapolate
1609 // something (such as user input) to an accurate diasplay time.
1610 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1611 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001612 nsecs_t bias = vsyncInterval / 2;
1613 int64_t extraVsyncs =
1614 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1615 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1616 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617
David Sodman99974d22017-11-28 12:04:33 -08001618 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1619 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1620 getBE().mCompositorTiming.interval = vsyncInterval;
1621 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622}
1623
1624void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001626 ATRACE_CALL();
1627 ALOGV("postComposition");
1628
Brian Anderson3546a3f2016-07-14 11:51:14 -07001629 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001630 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001631 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001632 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001633 }
1634
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001635 // |mStateLock| not needed as we are on the main thread
1636 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001637
David Sodman73beded2017-11-15 11:56:06 -08001638 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001639 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001640 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001641 glCompositionDoneFenceTime =
1642 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001643 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001644 } else {
1645 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1646 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001647
David Sodman73beded2017-11-15 11:56:06 -08001648 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001649 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001650 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001651 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001652
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1654 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1655
1656 // We use the refreshStartTime which might be sampled a little later than
1657 // when we started doing work for this frame, but that should be okay
1658 // since updateCompositorTiming has snapping logic.
1659 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001660 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001661 CompositorTiming compositorTiming;
1662 {
David Sodman99974d22017-11-28 12:04:33 -08001663 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1664 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001665 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666
Robert Carr2047fae2016-11-28 14:09:09 -08001667 mDrawingState.traverseInZOrder([&](Layer* layer) {
1668 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001669 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001670 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001671 recordBufferingStats(layer->getName().string(),
1672 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001673 }
Robert Carr2047fae2016-11-28 14:09:09 -08001674 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001675
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001676 if (presentFenceTime->isValid()) {
1677 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001678 enableHardwareVsync();
1679 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001680 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001681 }
1682 }
1683
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001684 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001685 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001686 enableHardwareVsync();
1687 }
1688 }
1689
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001690 if (mAnimCompositionPending) {
1691 mAnimCompositionPending = false;
1692
Brian Anderson4e606e32017-03-16 15:34:57 -07001693 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001694 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001695 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001696 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001697 // The HWC doesn't support present fences, so use the refresh
1698 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001699 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001700 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001701 mAnimFrameTracker.setActualPresentTime(presentTime);
1702 }
1703 mAnimFrameTracker.advanceFrame();
1704 }
Dan Stozab90cf072015-03-05 11:05:59 -08001705
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001706 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1707 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001708 return;
1709 }
1710
1711 nsecs_t currentTime = systemTime();
1712 if (mHasPoweredOff) {
1713 mHasPoweredOff = false;
1714 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001715 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001716 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001717 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1718 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001719 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001720 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001721 }
David Sodman4a36e932017-11-07 14:29:47 -08001722 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001723 }
David Sodman4a36e932017-11-07 14:29:47 -08001724 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725}
1726
1727void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 ATRACE_CALL();
1729 ALOGV("rebuildLayerStacks");
1730
Mathias Agopiancd60f992012-08-16 16:28:27 -07001731 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001732 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001733 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001734 mVisibleRegionsDirty = false;
1735 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001736
Jeff Sharkey76488112017-02-27 14:15:18 -07001737 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1738 Region opaqueRegion;
1739 Region dirtyRegion;
1740 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001741 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001742 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1743 const Transform& tr(displayDevice->getTransform());
1744 const Rect bounds(displayDevice->getBounds());
1745 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001746 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001747
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001749 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001750 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1751 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001752 Region drawRegion(tr.transform(
1753 layer->visibleNonTransparentRegion));
1754 drawRegion.andSelf(bounds);
1755 if (!drawRegion.isEmpty()) {
1756 layersSortedByZ.add(layer);
1757 } else {
1758 // Clear out the HWC layer if this layer was
1759 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001760 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001761 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001763 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001764 // WM changes displayDevice->layerStack upon sleep/awake.
1765 // Here we make sure we delete the HWC layers even if
1766 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001767 hwcLayerDestroyed = layer->destroyHwcLayer(
1768 displayDevice->getHwcDisplayId());
1769 }
1770
1771 // If a layer is not going to get a release fence because
1772 // it is invisible, but it is also going to release its
1773 // old buffer, add it to the list of layers needing
1774 // fences.
1775 if (hwcLayerDestroyed) {
1776 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1777 mLayersWithQueuedFrames.cend(), layer);
1778 if (found != mLayersWithQueuedFrames.cend()) {
1779 layersNeedingFences.add(layer);
1780 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001781 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001782 });
1783 }
1784 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001785 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001786 displayDevice->undefinedRegion.set(bounds);
1787 displayDevice->undefinedRegion.subtractSelf(
1788 tr.transform(opaqueRegion));
1789 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001790 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001791 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001792}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001793
Romain Guy0147a172017-06-01 13:53:56 -07001794mat4 SurfaceFlinger::computeSaturationMatrix() const {
1795 if (mSaturation == 1.0f) {
1796 return mat4();
1797 }
1798
1799 // Rec.709 luma coefficients
1800 float3 luminance{0.213f, 0.715f, 0.072f};
1801 luminance *= 1.0f - mSaturation;
1802 return mat4(
1803 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1804 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1805 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1806 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1807 );
1808}
1809
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001810// pickColorMode translates a given dataspace into the best available color mode.
1811// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001812ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001813 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001814 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001815 }
1816
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001817 switch (dataSpace) {
1818 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1819 // system expects.
1820 case HAL_DATASPACE_UNKNOWN:
1821 case HAL_DATASPACE_SRGB:
1822 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001823 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001824 break;
1825
1826 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001827 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001828 break;
1829
1830 default:
1831 // TODO (courtneygo): Do we want to assert an error here?
1832 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1833 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001834 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001835 break;
1836 }
1837}
1838
Romain Guy0147a172017-06-01 13:53:56 -07001839android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001840 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001841 // Only support sRGB and Display-P3 right now.
1842 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1843 return HAL_DATASPACE_DISPLAY_P3;
1844 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001845 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1846 return HAL_DATASPACE_DISPLAY_P3;
1847 }
1848 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1849 return HAL_DATASPACE_DISPLAY_P3;
1850 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001851 if (!hasHdr) {
1852 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1853 return HAL_DATASPACE_DISPLAY_P3;
1854 }
1855 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1856 return HAL_DATASPACE_DISPLAY_P3;
1857 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001858 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001859
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001860 return HAL_DATASPACE_V0_SRGB;
1861}
1862
Mathias Agopiancd60f992012-08-16 16:28:27 -07001863void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001864 ATRACE_CALL();
1865 ALOGV("setUpHWComposer");
1866
Jesse Hall028dc8f2013-08-20 16:35:32 -07001867 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001868 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1869 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1870 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1871
1872 // If nothing has changed (!dirty), don't recompose.
1873 // If something changed, but we don't currently have any visible layers,
1874 // and didn't when we last did a composition, then skip it this time.
1875 // The second rule does two things:
1876 // - When all layers are removed from a display, we'll emit one black
1877 // frame, then nothing more until we get new layers.
1878 // - When a display is created with a private layer stack, we won't
1879 // emit any black frames until a layer is added to the layer stack.
1880 bool mustRecompose = dirty && !(empty && wasEmpty);
1881
1882 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1883 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1884 mustRecompose ? "doing" : "skipping",
1885 dirty ? "+" : "-",
1886 empty ? "+" : "-",
1887 wasEmpty ? "+" : "-");
1888
Dan Stoza71433162014-02-04 16:22:36 -08001889 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001890
1891 if (mustRecompose) {
1892 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1893 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001894 }
1895
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 // build the h/w work list
1897 if (CC_UNLIKELY(mGeometryInvalid)) {
1898 mGeometryInvalid = false;
1899 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1900 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1901 const auto hwcId = displayDevice->getHwcDisplayId();
1902 if (hwcId >= 0) {
1903 const Vector<sp<Layer>>& currentLayers(
1904 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001905 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001906 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001908 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001911 }
1912 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001913
Robert Carrae060832016-11-28 10:51:00 -08001914 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001915 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001917 }
1918 }
1919 }
1920 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 }
Riley Andrews03414a12014-07-01 14:22:59 -07001922
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001923
Romain Guy0147a172017-06-01 13:53:56 -07001924 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 // Set the per-frame data
1927 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1928 auto& displayDevice = mDisplays[displayId];
1929 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001930
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 if (hwcId < 0) {
1932 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001933 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001934 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001935 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001936 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1937 "display %zd: %d", displayId, result);
1938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001940 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1941 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001942 !displayDevice->getHdrSupport()) {
1943 layer->forceClientComposition(hwcId);
1944 }
1945
chaviwc9232ed2017-11-14 15:31:15 -08001946 if (layer->getForceClientComposition(hwcId)) {
1947 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1948 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1949 continue;
1950 }
1951
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 layer->setPerFrameData(displayDevice);
1953 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001954
1955 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001956 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001957 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1958
1959 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001960 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1961 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001962 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1963 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1964 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1965 }
1966 newColorMode = pickColorMode(newDataSpace);
1967
Thierry Strudel2924d012017-08-14 15:19:37 -07001968 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001969 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 }
1971
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001972 mPreviousColorMatrix = colorMatrix;
1973
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001975 auto& displayDevice = mDisplays[displayId];
1976 if (!displayDevice->isDisplayOn()) {
1977 continue;
1978 }
1979
David Sodman105b7dc2017-11-04 20:28:14 -07001980 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1982 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001983 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001984}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001985
Mathias Agopiancd60f992012-08-16 16:28:27 -07001986void SurfaceFlinger::doComposition() {
1987 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 ALOGV("doComposition");
1989
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001990 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001991 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001992 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001993 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994 // transform the dirty region into this screen's coordinate space
1995 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001996
1997 // repaint the framebuffer (if needed)
1998 doDisplayComposition(hw, dirtyRegion);
1999
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002001 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002002 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002003 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002004 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002005}
2006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007void SurfaceFlinger::postFramebuffer()
2008{
Mathias Agopian841cde52012-03-01 15:44:37 -08002009 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002011
Mathias Agopiana44b0412011-10-16 18:46:35 -07002012 const nsecs_t now = systemTime();
2013 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002014
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2016 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002017 if (!displayDevice->isDisplayOn()) {
2018 continue;
2019 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 const auto hwcId = displayDevice->getHwcDisplayId();
2021 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002022 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002023 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002024 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002025 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002027 // The layer buffer from the previous frame (if any) is released
2028 // by HWC only when the release fence from this frame (if any) is
2029 // signaled. Always get the release fence from HWC first.
2030 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002031 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002032
2033 // If the layer was client composited in the previous frame, we
2034 // need to merge with the previous client target acquire fence.
2035 // Since we do not track that, always merge with the current
2036 // client target acquire fence when it is available, even though
2037 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002039 releaseFence = Fence::merge("LayerRelease", releaseFence,
2040 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002041 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002042
David Sodmanb8af7922017-12-21 15:17:55 -08002043 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 }
Chia-I Wu83806892017-11-16 10:50:20 -08002045
2046 // We've got a list of layers needing fences, that are disjoint with
2047 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2048 // supply them with the present fence.
2049 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002050 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002051 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002052 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002053 }
2054 }
2055
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002057 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002058 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002059 }
2060
Mathias Agopiana44b0412011-10-16 18:46:35 -07002061 mLastSwapBufferTime = systemTime() - now;
2062 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002063
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002064 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002065 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2066 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2067 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2068 logFrameStats();
2069 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002070 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002071}
2072
Mathias Agopian87baae12012-07-31 12:38:26 -07002073void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074{
Mathias Agopian841cde52012-03-01 15:44:37 -08002075 ATRACE_CALL();
2076
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002077 // here we keep a copy of the drawing state (that is the state that's
2078 // going to be overwritten by handleTransactionLocked()) outside of
2079 // mStateLock so that the side-effects of the State assignment
2080 // don't happen with mStateLock held (which can cause deadlocks).
2081 State drawingState(mDrawingState);
2082
Mathias Agopianca4d3602011-05-19 15:38:14 -07002083 Mutex::Autolock _l(mStateLock);
2084 const nsecs_t now = systemTime();
2085 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086
Mathias Agopianca4d3602011-05-19 15:38:14 -07002087 // Here we're guaranteed that some transaction flags are set
2088 // so we can call handleTransactionLocked() unconditionally.
2089 // We call getTransactionFlags(), which will also clear the flags,
2090 // with mStateLock held to guarantee that mCurrentState won't change
2091 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002092
Mathias Agopiane57f2922012-08-09 16:29:12 -07002093 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002094 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002095
Mathias Agopianca4d3602011-05-19 15:38:14 -07002096 mLastTransactionTime = systemTime() - now;
2097 mDebugInTransaction = 0;
2098 invalidateHwcGeometry();
2099 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002100}
2101
Lloyd Pique715a2c12017-12-14 17:18:08 -08002102DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2103 HWC2::Connection connection) const {
2104 // Figure out whether the event is for the primary display or an
2105 // external display by matching the Hwc display id against one for a
2106 // connected display. If we did not find a match, we then check what
2107 // displays are not already connected to determine the type. If we don't
2108 // have a connected primary display, we assume the new display is meant to
2109 // be the primary display, and then if we don't have an external display,
2110 // we assume it is that.
2111 const auto primaryDisplayId =
2112 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2113 const auto externalDisplayId =
2114 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2115 if (primaryDisplayId && primaryDisplayId == display) {
2116 return DisplayDevice::DISPLAY_PRIMARY;
2117 } else if (externalDisplayId && externalDisplayId == display) {
2118 return DisplayDevice::DISPLAY_EXTERNAL;
2119 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2120 return DisplayDevice::DISPLAY_PRIMARY;
2121 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2122 return DisplayDevice::DISPLAY_EXTERNAL;
2123 }
2124
2125 return DisplayDevice::DISPLAY_ID_INVALID;
2126}
2127
Lloyd Piqueba04e622017-12-14 17:11:26 -08002128void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2129 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002130 auto displayType = determineDisplayType(event.display, event.connection);
2131 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2132 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2133 continue;
2134 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002135
2136 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2137 ALOGE("External displays are not supported by the vr hardware composer.");
2138 continue;
2139 }
2140
Lloyd Pique715a2c12017-12-14 17:18:08 -08002141 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002142
2143 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002144 ALOGV("Creating built in display %d", displayType);
2145 ALOGW_IF(mBuiltinDisplays[displayType],
2146 "Overwriting display token for display type %d", displayType);
2147 mBuiltinDisplays[displayType] = new BBinder();
2148 // All non-virtual displays are currently considered secure.
2149 DisplayDeviceState info(displayType, true);
2150 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2151 "Built-in Screen" : "External Screen";
2152 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4dccc412018-01-22 17:21:36 -08002153 mInterceptor->saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002154 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002155 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002156
Lloyd Piquefcd86612017-12-14 17:15:36 -08002157 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2158 if (idx >= 0) {
2159 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4dccc412018-01-22 17:21:36 -08002160 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002161 mCurrentState.displays.removeItemsAt(idx);
2162 }
2163 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002164 }
2165
2166 processDisplayChangesLocked();
2167 }
2168
2169 mPendingHotplugEvents.clear();
2170}
2171
Lloyd Pique347200f2017-12-14 17:00:15 -08002172void SurfaceFlinger::processDisplayChangesLocked() {
2173 // here we take advantage of Vector's copy-on-write semantics to
2174 // improve performance by skipping the transaction entirely when
2175 // know that the lists are identical
2176 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2177 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2178 if (!curr.isIdenticalTo(draw)) {
2179 mVisibleRegionsDirty = true;
2180 const size_t cc = curr.size();
2181 size_t dc = draw.size();
2182
2183 // find the displays that were removed
2184 // (ie: in drawing state but not in current state)
2185 // also handle displays that changed
2186 // (ie: displays that are in both lists)
2187 for (size_t i = 0; i < dc;) {
2188 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2189 if (j < 0) {
2190 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002191 // Call makeCurrent() on the primary display so we can
2192 // be sure that nothing associated with this display
2193 // is current.
2194 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2195 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2196 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2197 if (hw != nullptr) hw->disconnect(getHwComposer());
2198 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2199 mEventThread->onHotplugReceived(draw[i].type, false);
2200 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002201 } else {
2202 // this display is in both lists. see if something changed.
2203 const DisplayDeviceState& state(curr[j]);
2204 const wp<IBinder>& display(curr.keyAt(j));
2205 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2206 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2207 if (state_binder != draw_binder) {
2208 // changing the surface is like destroying and
2209 // recreating the DisplayDevice, so we just remove it
2210 // from the drawing state, so that it get re-added
2211 // below.
2212 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2213 if (hw != nullptr) hw->disconnect(getHwComposer());
2214 mDisplays.removeItem(display);
2215 mDrawingState.displays.removeItemsAt(i);
2216 dc--;
2217 // at this point we must loop to the next item
2218 continue;
2219 }
2220
2221 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2222 if (disp != nullptr) {
2223 if (state.layerStack != draw[i].layerStack) {
2224 disp->setLayerStack(state.layerStack);
2225 }
2226 if ((state.orientation != draw[i].orientation) ||
2227 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2228 disp->setProjection(state.orientation, state.viewport, state.frame);
2229 }
2230 if (state.width != draw[i].width || state.height != draw[i].height) {
2231 disp->setDisplaySize(state.width, state.height);
2232 }
2233 }
2234 }
2235 ++i;
2236 }
2237
2238 // find displays that were added
2239 // (ie: in current state but not in drawing state)
2240 for (size_t i = 0; i < cc; i++) {
2241 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2242 const DisplayDeviceState& state(curr[i]);
2243
2244 sp<DisplaySurface> dispSurface;
2245 sp<IGraphicBufferProducer> producer;
2246 sp<IGraphicBufferProducer> bqProducer;
2247 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002248 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002249
2250 int32_t hwcId = -1;
2251 if (state.isVirtualDisplay()) {
2252 // Virtual displays without a surface are dormant:
2253 // they have external state (layer stack, projection,
2254 // etc.) but no internal state (i.e. a DisplayDevice).
2255 if (state.surface != nullptr) {
2256 // Allow VR composer to use virtual displays.
2257 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2258 int width = 0;
2259 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2260 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2261 int height = 0;
2262 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2263 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2264 int intFormat = 0;
2265 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2266 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2267 auto format = static_cast<android_pixel_format_t>(intFormat);
2268
2269 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2270 }
2271
2272 // TODO: Plumb requested format back up to consumer
2273
2274 sp<VirtualDisplaySurface> vds =
2275 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2276 bqProducer, bqConsumer,
2277 state.displayName);
2278
2279 dispSurface = vds;
2280 producer = vds;
2281 }
2282 } else {
2283 ALOGE_IF(state.surface != nullptr,
2284 "adding a supported display, but rendering "
2285 "surface is provided (%p), ignoring it",
2286 state.surface.get());
2287
2288 hwcId = state.type;
2289 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2290 producer = bqProducer;
2291 }
2292
2293 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002294
Lloyd Pique347200f2017-12-14 17:00:15 -08002295 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002296 bool hasWideColorSupport = false;
2297 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002298 std::vector<ColorMode> modes =
Lloyd Piquefcd86612017-12-14 17:15:36 -08002299 getHwComposer().getColorModes(state.type);
Peiyong Lina52f0292018-03-14 17:26:31 -07002300 for (ColorMode colorMode : modes) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002301 switch (colorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002302 case ColorMode::DISPLAY_P3:
2303 case ColorMode::ADOBE_RGB:
2304 case ColorMode::DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002305 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306 break;
2307 default:
2308 break;
2309 }
2310 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002311 }
2312
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002313 bool hasHdrSupport = false;
2314 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2315 getHwComposer().getHdrCapabilities(state.type);
2316 if (hdrCapabilities) {
2317 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2318 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2319 hasHdrSupport = iter != types.cend();
2320 }
2321
Lloyd Pique347200f2017-12-14 17:00:15 -08002322 sp<DisplayDevice> hw =
2323 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002324 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002325 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002326
Peiyong Lina52f0292018-03-14 17:26:31 -07002327 ColorMode defaultColorMode = ColorMode::NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002328 if (hasWideColorSupport) {
Peiyong Lina52f0292018-03-14 17:26:31 -07002329 defaultColorMode = ColorMode::SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002330 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002331 setActiveColorModeInternal(hw, defaultColorMode);
2332 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002333 hw->setLayerStack(state.layerStack);
2334 hw->setProjection(state.orientation, state.viewport, state.frame);
2335 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002336
Lloyd Pique347200f2017-12-14 17:00:15 -08002337 mDisplays.add(display, hw);
2338 if (!state.isVirtualDisplay()) {
2339 mEventThread->onHotplugReceived(state.type, true);
2340 }
2341 }
2342 }
2343 }
2344 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002345
2346 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002347}
2348
Mathias Agopian87baae12012-07-31 12:38:26 -07002349void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002350{
Dan Stoza7dde5992015-05-22 09:51:44 -07002351 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002352 mCurrentState.traverseInZOrder([](Layer* layer) {
2353 layer->notifyAvailableFrames();
2354 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002355
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 /*
2357 * Traversal of the children
2358 * (perform the transaction for each of them if needed)
2359 */
2360
Mathias Agopian3559b072012-08-15 13:46:03 -07002361 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002362 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002364 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365
2366 const uint32_t flags = layer->doTransaction(0);
2367 if (flags & Layer::eVisibleRegion)
2368 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002369 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370 }
2371
2372 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002373 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374 */
2375
Mathias Agopiane57f2922012-08-09 16:29:12 -07002376 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002378 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380
Mathias Agopian84300952012-11-21 16:02:13 -08002381 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2382 // The transform hint might have changed for some layers
2383 // (either because a display has changed, or because a layer
2384 // as changed).
2385 //
2386 // Walk through all the layers in currentLayers,
2387 // and update their transform hint.
2388 //
2389 // If a layer is visible only on a single display, then that
2390 // display is used to calculate the hint, otherwise we use the
2391 // default display.
2392 //
2393 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2394 // the hint is set before we acquire a buffer from the surface texture.
2395 //
2396 // NOTE: layer transactions have taken place already, so we use their
2397 // drawing state. However, SurfaceFlinger's own transaction has not
2398 // happened yet, so we must use the current state layer list
2399 // (soon to become the drawing state list).
2400 //
2401 sp<const DisplayDevice> disp;
2402 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002403 bool first = true;
2404 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002405 // NOTE: we rely on the fact that layers are sorted by
2406 // layerStack first (so we don't have to traverse the list
2407 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002408 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002409 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002410 currentlayerStack = layerStack;
2411 // figure out if this layerstack is mirrored
2412 // (more than one display) if so, pick the default display,
2413 // if not, pick the only display it's on.
2414 disp.clear();
2415 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2416 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002417 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002418 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002419 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002420 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002421 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002422 break;
2423 }
2424 }
2425 }
2426 }
Chet Haase91d25932013-04-11 15:24:55 -07002427
Robert Carr56a0b9a2017-12-04 16:06:13 -08002428 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002429 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002430 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2431 // redraw after transform hint changes. See bug 8508397.
2432
2433 // could be null when this layer is using a layerStack
2434 // that is not visible on any display. Also can occur at
2435 // screen off/on times.
2436 disp = getDefaultDisplayDeviceLocked();
2437 }
2438 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002439 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002440 if (disp != nullptr) {
2441 layer->updateTransformHint(disp);
2442 }
Robert Carr2047fae2016-11-28 14:09:09 -08002443
2444 first = false;
2445 });
Mathias Agopian84300952012-11-21 16:02:13 -08002446 }
2447
2448
Mathias Agopian3559b072012-08-15 13:46:03 -07002449 /*
2450 * Perform our own transaction if needed
2451 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452
2453 if (mLayersAdded) {
2454 mLayersAdded = false;
2455 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002456 mVisibleRegionsDirty = true;
2457 }
2458
2459 // some layers might have been removed, so
2460 // we need to update the regions they're exposing.
2461 if (mLayersRemoved) {
2462 mLayersRemoved = false;
2463 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002464 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002465 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002466 // this layer is not visible anymore
2467 // TODO: we could traverse the tree from front to back and
2468 // compute the actual visible region
2469 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002470 Region visibleReg;
2471 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002472 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002473 }
Robert Carr2047fae2016-11-28 14:09:09 -08002474 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475 }
2476
2477 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002478
2479 updateCursorAsync();
2480}
2481
2482void SurfaceFlinger::updateCursorAsync()
2483{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2485 auto& displayDevice = mDisplays[displayId];
2486 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002487 continue;
2488 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489
2490 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2491 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002492 }
2493 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002494}
2495
2496void SurfaceFlinger::commitTransaction()
2497{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002498 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002499 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002500 for (const auto& l : mLayersPendingRemoval) {
2501 recordBufferingStats(l->getName().string(),
2502 l->getOccupancyHistory(true));
2503 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002504 }
2505 mLayersPendingRemoval.clear();
2506 }
2507
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002508 // If this transaction is part of a window animation then the next frame
2509 // we composite should be considered an animation as well.
2510 mAnimCompositionPending = mAnimTransactionPending;
2511
Mathias Agopian4fec8732012-06-29 14:12:52 -07002512 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 mDrawingState.traverseInZOrder([](Layer* layer) {
2514 layer->commitChildList();
2515 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002516 mTransactionPending = false;
2517 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002518 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519}
2520
Chia-I Wuab0c3192017-08-01 11:29:00 -07002521void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002522 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523{
Mathias Agopian841cde52012-03-01 15:44:37 -08002524 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002525 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527 Region aboveOpaqueLayers;
2528 Region aboveCoveredLayers;
2529 Region dirty;
2530
Mathias Agopian87baae12012-07-31 12:38:26 -07002531 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532
Robert Carr2047fae2016-11-28 14:09:09 -08002533 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002535 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536
Jesse Hall01e29052013-02-19 16:13:35 -08002537 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002538 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002539 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002540
Mathias Agopianab028732010-03-16 16:41:46 -07002541 /*
2542 * opaqueRegion: area of a surface that is fully opaque.
2543 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002545
2546 /*
2547 * visibleRegion: area of a surface that is visible on screen
2548 * and not fully transparent. This is essentially the layer's
2549 * footprint minus the opaque regions above it.
2550 * Areas covered by a translucent surface are considered visible.
2551 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002553
2554 /*
2555 * coveredRegion: area of a surface that is covered by all
2556 * visible regions above it (which includes the translucent areas).
2557 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002559
Jesse Halla8026d22012-09-25 13:25:04 -07002560 /*
2561 * transparentRegion: area of a surface that is hinted to be completely
2562 * transparent. This is only used to tell when the layer has no visible
2563 * non-transparent regions and can be removed from the layer list. It
2564 * does not affect the visibleRegion of this layer or any layers
2565 * beneath it. The hint may not be correct if apps don't respect the
2566 * SurfaceView restrictions (which, sadly, some don't).
2567 */
2568 Region transparentRegion;
2569
Mathias Agopianab028732010-03-16 16:41:46 -07002570
2571 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002572 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002573 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002574 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002576 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002577 if (!visibleRegion.isEmpty()) {
2578 // Remove the transparent area from the visible region
2579 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002580 if (tr.preserveRects()) {
2581 // transform the transparent region
2582 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002583 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002584 // transformation too complex, can't do the
2585 // transparent region optimization.
2586 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002587 }
Mathias Agopianab028732010-03-16 16:41:46 -07002588 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589
Mathias Agopianab028732010-03-16 16:41:46 -07002590 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002592 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002593 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2594 // the opaque region is the layer's footprint
2595 opaqueRegion = visibleRegion;
2596 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 }
2598 }
2599
Robert Carre5f4f692018-01-12 13:12:28 -08002600 if (visibleRegion.isEmpty()) {
2601 layer->clearVisibilityRegions();
2602 return;
2603 }
2604
Mathias Agopianab028732010-03-16 16:41:46 -07002605 // Clip the covered region to the visible region
2606 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2607
2608 // Update aboveCoveredLayers for next (lower) layer
2609 aboveCoveredLayers.orSelf(visibleRegion);
2610
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 // subtract the opaque region covered by the layers above us
2612 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613
2614 // compute this layer's dirty region
2615 if (layer->contentDirty) {
2616 // we need to invalidate the whole region
2617 dirty = visibleRegion;
2618 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002619 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 layer->contentDirty = false;
2621 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002622 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002623 * the exposed region consists of two components:
2624 * 1) what's VISIBLE now and was COVERED before
2625 * 2) what's EXPOSED now less what was EXPOSED before
2626 *
2627 * note that (1) is conservative, we start with the whole
2628 * visible region but only keep what used to be covered by
2629 * something -- which mean it may have been exposed.
2630 *
2631 * (2) handles areas that were not covered by anything but got
2632 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002633 */
Mathias Agopianab028732010-03-16 16:41:46 -07002634 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002635 const Region oldVisibleRegion = layer->visibleRegion;
2636 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002637 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2638 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 }
2640 dirty.subtractSelf(aboveOpaqueLayers);
2641
2642 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002643 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644
Mathias Agopianab028732010-03-16 16:41:46 -07002645 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002647
Jesse Halla8026d22012-09-25 13:25:04 -07002648 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649 layer->setVisibleRegion(visibleRegion);
2650 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002651 layer->setVisibleNonTransparentRegion(
2652 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002653 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
Mathias Agopian87baae12012-07-31 12:38:26 -07002655 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656}
2657
Chia-I Wuab0c3192017-08-01 11:29:00 -07002658void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002659 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002660 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002661 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002662 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002663 }
2664 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002665}
2666
Dan Stoza6b9454d2014-11-07 16:00:59 -08002667bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 ALOGV("handlePageFlip");
2670
Brian Andersond6927fb2016-07-23 23:37:30 -07002671 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672
Mathias Agopian4fec8732012-06-29 14:12:52 -07002673 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002674 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002675 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002676
2677 // Store the set of layers that need updates. This set must not change as
2678 // buffers are being latched, as this could result in a deadlock.
2679 // Example: Two producers share the same command stream and:
2680 // 1.) Layer 0 is latched
2681 // 2.) Layer 0 gets a new frame
2682 // 2.) Layer 1 gets a new frame
2683 // 3.) Layer 1 is latched.
2684 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2685 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002686 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002687 if (layer->hasQueuedFrame()) {
2688 frameQueued = true;
2689 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002690 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002691 } else {
2692 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002693 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002694 } else {
2695 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002696 }
Robert Carr2047fae2016-11-28 14:09:09 -08002697 });
2698
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002700 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002701 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002702 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002703 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002704 newDataLatched = true;
2705 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002707
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002708 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002709
2710 // If we will need to wake up at some time in the future to deal with a
2711 // queued frame that shouldn't be displayed during this vsync period, wake
2712 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002713 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002714 signalLayerUpdate();
2715 }
2716
2717 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002718 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719}
2720
Mathias Agopianad456f92011-01-13 17:53:01 -08002721void SurfaceFlinger::invalidateHwcGeometry()
2722{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002723 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002724}
2725
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002726
Fabien Sanglard830b8472016-11-30 16:35:58 -08002727void SurfaceFlinger::doDisplayComposition(
2728 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002729 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730{
Dan Stoza71433162014-02-04 16:22:36 -08002731 // We only need to actually compose the display if:
2732 // 1) It is being handled by hardware composer, which may need this to
2733 // keep its virtual display state machine in sync, or
2734 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002735 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002736 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002738 return;
2739 }
2740
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002742 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002743
2744 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002745 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746}
2747
Chia-I Wub02087d2017-11-09 10:19:54 -08002748bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002749{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002751
Chia-I Wub02087d2017-11-09 10:19:54 -08002752 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002753 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002755
2756 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002757 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2758 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002759 if (applyColorMatrix) {
2760 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2761 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2762 }
2763
David Sodman105b7dc2017-11-04 20:28:14 -07002764 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 if (hasClientComposition) {
2766 ALOGV("hasClientComposition");
2767
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002768 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002769 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002770 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002771 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2772 }
2773 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2774
Chia-I Wu7f402902017-11-09 12:51:10 -08002775 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002776 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002778 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002779
2780 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002781 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002782 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2783 }
2784 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002785 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002786
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002787 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002788 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002790 // when using overlays, we assume a fully transparent framebuffer
2791 // NOTE: we could reduce how much we need to clear, for instance
2792 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002793 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002794 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002795 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002796 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002797 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002798 // we're left with the letterbox region
2799 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002801
2802 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002804
Mathias Agopianb9494d52012-04-18 02:28:45 -07002805 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002806 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002807 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002809 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002810 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002811
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002813 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002814 // scissor on the main display. It should never be needed
2815 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 const Rect& bounds(displayDevice->getBounds());
2817 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002818 if (scissor != bounds) {
2819 // scissor doesn't match the screen's dimensions, so we
2820 // need to clear everything outside of it and enable
2821 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002822
Mathias Agopianf45c5102012-10-24 16:29:17 -07002823 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002824 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002825 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002826 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002827 }
2828 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002829 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002830
Mathias Agopian85d751c2012-08-29 16:59:24 -07002831 /*
2832 * and then, render the layers targeted at the framebuffer
2833 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002834
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 ALOGV("Rendering client layers");
2836 const Transform& displayTransform = displayDevice->getTransform();
2837 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002838 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 bool firstLayer = true;
2840 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002841 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 displayTransform.transform(layer->visibleRegion)));
2843 ALOGV("Layer: %s", layer->getName().string());
2844 ALOGV(" Composition type: %s",
2845 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002846 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 switch (layer->getCompositionType(hwcId)) {
2848 case HWC2::Composition::Cursor:
2849 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002850 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002851 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002852 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002853 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002854 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002856 // never clear the very first layer since we're
2857 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002858 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002859 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002860 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002861 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002862 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002863 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002864 break;
2865 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002867 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002868 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 } else {
2870 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002871 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002872 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002873 }
2874 } else {
2875 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002877 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002879 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002880 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002881 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002882 }
2883 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002884
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002885 if (applyColorMatrix) {
2886 getRenderEngine().setupColorTransform(oldColorMatrix);
2887 }
2888
Mathias Agopianf45c5102012-10-24 16:29:17 -07002889 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002890 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002891 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Fabien Sanglard830b8472016-11-30 16:35:58 -08002894void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2895 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002896 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002897 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898}
2899
Dan Stoza7d89d062015-04-30 13:29:25 -07002900status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002901 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002902 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 const sp<Layer>& lbc,
2904 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002905{
Dan Stoza7d89d062015-04-30 13:29:25 -07002906 // add this layer to the current state list
2907 {
2908 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002910 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2911 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002912 return NO_MEMORY;
2913 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 if (parent == nullptr) {
2915 mCurrentState.layersSortedByZ.add(lbc);
2916 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002917 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002918 ALOGE("addClientLayer called with a removed parent");
2919 return NAME_NOT_FOUND;
2920 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 parent->addChild(lbc);
2922 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002923
Dan Stoza101d8dc2018-02-27 15:42:25 -08002924 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002925 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2926 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2927 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2928 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2929 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 mLayersAdded = true;
2931 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002932 }
2933
Mathias Agopian96f08192010-06-02 23:28:45 -07002934 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002935 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002936
Dan Stoza7d89d062015-04-30 13:29:25 -07002937 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002938}
2939
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002940status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002941 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002942 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2943}
Robert Carr7f9b8992017-03-10 11:08:39 -08002944
chaviwca27f252018-02-06 16:46:39 -08002945status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2946 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002947 if (layer->isPendingRemoval()) {
2948 return NO_ERROR;
2949 }
2950
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002952 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002953 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002954 if (topLevelOnly) {
2955 return NO_ERROR;
2956 }
2957
Chia-I Wu98f1c102017-05-30 14:54:08 -07002958 sp<Layer> ancestor = p;
2959 while (ancestor->getParent() != nullptr) {
2960 ancestor = ancestor->getParent();
2961 }
2962 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2963 ALOGE("removeLayer called with a layer whose parent has been removed");
2964 return NAME_NOT_FOUND;
2965 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002966
2967 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002968 } else {
2969 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002970 }
2971
Robert Carr136e2f62017-02-08 17:54:29 -08002972 // As a matter of normal operation, the LayerCleaner will produce a second
2973 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2974 // so we will succeed in promoting it, but it's already been removed
2975 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2976 // otherwise something has gone wrong and we are leaking the layer.
2977 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2979 layer->getName().string(),
2980 (p != nullptr) ? p->getName().string() : "no-parent");
2981 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002982 } else if (index < 0) {
2983 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002984 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002985
Chia-I Wuc6657022017-08-15 11:18:17 -07002986 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002987 mLayersPendingRemoval.add(layer);
2988 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002989 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002990 setTransactionFlags(eTransactionNeeded);
2991 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992}
2993
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002994uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002995 return android_atomic_release_load(&mTransactionFlags);
2996}
2997
Mathias Agopian3f844832013-08-07 21:24:32 -07002998uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3000}
3001
Mathias Agopian3f844832013-08-07 21:24:32 -07003002uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3004 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003005 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006 }
3007 return old;
3008}
3009
chaviwca27f252018-02-06 16:46:39 -08003010bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3011 for (const ComposerState& state : states) {
3012 // Here we need to check that the interface we're given is indeed
3013 // one of our own. A malicious client could give us a nullptr
3014 // IInterface, or one of its own or even one of our own but a
3015 // different type. All these situations would cause us to crash.
3016 if (state.client == nullptr) {
3017 return true;
3018 }
3019
3020 sp<IBinder> binder = IInterface::asBinder(state.client);
3021 if (binder == nullptr) {
3022 return true;
3023 }
3024
3025 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3026 return true;
3027 }
3028 }
3029 return false;
3030}
3031
Mathias Agopian8b33f032012-07-24 20:43:54 -07003032void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003033 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003034 const Vector<DisplayState>& displays,
3035 uint32_t flags)
3036{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003037 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003038 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003039 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003040
chaviwca27f252018-02-06 16:46:39 -08003041 if (containsAnyInvalidClientState(states)) {
3042 return;
3043 }
3044
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003045 if (flags & eAnimation) {
3046 // For window updates that are part of an animation we must wait for
3047 // previous animation "frames" to be handled.
3048 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003049 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003050 if (CC_UNLIKELY(err != NO_ERROR)) {
3051 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003052 // caller after a few seconds.
3053 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3054 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003055 mAnimTransactionPending = false;
3056 break;
3057 }
3058 }
3059 }
3060
chaviwca27f252018-02-06 16:46:39 -08003061 for (const DisplayState& display : displays) {
3062 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003063 }
3064
chaviwca27f252018-02-06 16:46:39 -08003065 for (const ComposerState& state : states) {
3066 transactionFlags |= setClientStateLocked(state);
3067 }
3068
3069 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3070 // as destroyed should only occur after setting all other states. This is to allow for a
3071 // child re-parent to happen before marking its original parent as destroyed (which would
3072 // then mark the child as destroyed).
3073 for (const ComposerState& state : states) {
3074 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003075 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003076
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003077 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3078 // anyway. This can be used as a flush mechanism for previous async transactions.
3079 // Empty animation transaction can be used to simulate back-pressure, so also force a
3080 // transaction for empty animation transactions.
3081 if (transactionFlags == 0 &&
3082 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003083 transactionFlags = eTransactionNeeded;
3084 }
3085
Mathias Agopian386aa982011-11-07 21:58:03 -08003086 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003087 if (mInterceptor->isEnabled()) {
3088 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003089 }
Irvel468051e2016-06-13 16:44:44 -07003090
Mathias Agopian386aa982011-11-07 21:58:03 -08003091 // this triggers the transaction
3092 setTransactionFlags(transactionFlags);
3093
3094 // if this is a synchronous transaction, wait for it to take effect
3095 // before returning.
3096 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003097 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003098 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003099 if (flags & eAnimation) {
3100 mAnimTransactionPending = true;
3101 }
3102 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003103 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3104 if (CC_UNLIKELY(err != NO_ERROR)) {
3105 // just in case something goes wrong in SF, return to the
3106 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003107 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3108 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003109 break;
3110 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 }
3113}
3114
Mathias Agopiane57f2922012-08-09 16:29:12 -07003115uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3116{
Jesse Hall9a143922012-10-04 16:29:19 -07003117 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3118 if (dpyIdx < 0)
3119 return 0;
3120
Mathias Agopiane57f2922012-08-09 16:29:12 -07003121 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003122 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003123 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003124 const uint32_t what = s.what;
3125 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003126 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003127 disp.surface = s.surface;
3128 flags |= eDisplayTransactionNeeded;
3129 }
3130 }
3131 if (what & DisplayState::eLayerStackChanged) {
3132 if (disp.layerStack != s.layerStack) {
3133 disp.layerStack = s.layerStack;
3134 flags |= eDisplayTransactionNeeded;
3135 }
3136 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003137 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003138 if (disp.orientation != s.orientation) {
3139 disp.orientation = s.orientation;
3140 flags |= eDisplayTransactionNeeded;
3141 }
3142 if (disp.frame != s.frame) {
3143 disp.frame = s.frame;
3144 flags |= eDisplayTransactionNeeded;
3145 }
3146 if (disp.viewport != s.viewport) {
3147 disp.viewport = s.viewport;
3148 flags |= eDisplayTransactionNeeded;
3149 }
3150 }
Michael Lentine47e45402014-07-18 15:34:25 -07003151 if (what & DisplayState::eDisplaySizeChanged) {
3152 if (disp.width != s.width) {
3153 disp.width = s.width;
3154 flags |= eDisplayTransactionNeeded;
3155 }
3156 if (disp.height != s.height) {
3157 disp.height = s.height;
3158 flags |= eDisplayTransactionNeeded;
3159 }
3160 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003161 }
3162 return flags;
3163}
3164
chaviwca27f252018-02-06 16:46:39 -08003165uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3166 const layer_state_t& s = composerState.state;
3167 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3168
Mathias Agopian13127d82013-03-05 17:47:11 -08003169 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003170 if (layer == nullptr) {
3171 return 0;
3172 }
3173
3174 if (layer->isPendingRemoval()) {
3175 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3176 return 0;
3177 }
3178
3179 uint32_t flags = 0;
3180
3181 const uint32_t what = s.what;
3182 bool geometryAppliesWithResize =
3183 what & layer_state_t::eGeometryAppliesWithResize;
3184 if (what & layer_state_t::ePositionChanged) {
3185 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3186 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003187 }
chaviw8b3871a2017-11-01 17:41:01 -07003188 }
3189 if (what & layer_state_t::eLayerChanged) {
3190 // NOTE: index needs to be calculated before we update the state
3191 const auto& p = layer->getParent();
3192 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003193 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003194 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003195 mCurrentState.layersSortedByZ.removeAt(idx);
3196 mCurrentState.layersSortedByZ.add(layer);
3197 // we need traversal (state changed)
3198 // AND transaction (list changed)
3199 flags |= eTransactionNeeded|eTraversalNeeded;
3200 }
chaviw8b3871a2017-11-01 17:41:01 -07003201 } else {
3202 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003203 flags |= eTransactionNeeded|eTraversalNeeded;
3204 }
3205 }
chaviw8b3871a2017-11-01 17:41:01 -07003206 }
3207 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003208 // NOTE: index needs to be calculated before we update the state
3209 const auto& p = layer->getParent();
3210 if (p == nullptr) {
3211 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3212 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3213 mCurrentState.layersSortedByZ.removeAt(idx);
3214 mCurrentState.layersSortedByZ.add(layer);
3215 // we need traversal (state changed)
3216 // AND transaction (list changed)
3217 flags |= eTransactionNeeded|eTraversalNeeded;
3218 }
3219 } else {
3220 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3221 flags |= eTransactionNeeded|eTraversalNeeded;
3222 }
chaviw8b3871a2017-11-01 17:41:01 -07003223 }
3224 }
3225 if (what & layer_state_t::eSizeChanged) {
3226 if (layer->setSize(s.w, s.h)) {
3227 flags |= eTraversalNeeded;
3228 }
3229 }
3230 if (what & layer_state_t::eAlphaChanged) {
3231 if (layer->setAlpha(s.alpha))
3232 flags |= eTraversalNeeded;
3233 }
3234 if (what & layer_state_t::eColorChanged) {
3235 if (layer->setColor(s.color))
3236 flags |= eTraversalNeeded;
3237 }
3238 if (what & layer_state_t::eMatrixChanged) {
3239 if (layer->setMatrix(s.matrix))
3240 flags |= eTraversalNeeded;
3241 }
3242 if (what & layer_state_t::eTransparentRegionChanged) {
3243 if (layer->setTransparentRegionHint(s.transparentRegion))
3244 flags |= eTraversalNeeded;
3245 }
3246 if (what & layer_state_t::eFlagsChanged) {
3247 if (layer->setFlags(s.flags, s.mask))
3248 flags |= eTraversalNeeded;
3249 }
3250 if (what & layer_state_t::eCropChanged) {
3251 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3252 flags |= eTraversalNeeded;
3253 }
3254 if (what & layer_state_t::eFinalCropChanged) {
3255 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3256 flags |= eTraversalNeeded;
3257 }
3258 if (what & layer_state_t::eLayerStackChanged) {
3259 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3260 // We only allow setting layer stacks for top level layers,
3261 // everything else inherits layer stack from its parent.
3262 if (layer->hasParent()) {
3263 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3264 layer->getName().string());
3265 } else if (idx < 0) {
3266 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3267 "that also does not appear in the top level layer list. Something"
3268 " has gone wrong.", layer->getName().string());
3269 } else if (layer->setLayerStack(s.layerStack)) {
3270 mCurrentState.layersSortedByZ.removeAt(idx);
3271 mCurrentState.layersSortedByZ.add(layer);
3272 // we need traversal (state changed)
3273 // AND transaction (list changed)
3274 flags |= eTransactionNeeded|eTraversalNeeded;
3275 }
3276 }
3277 if (what & layer_state_t::eDeferTransaction) {
3278 if (s.barrierHandle != nullptr) {
3279 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3280 } else if (s.barrierGbp != nullptr) {
3281 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3282 if (authenticateSurfaceTextureLocked(gbp)) {
3283 const auto& otherLayer =
3284 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3285 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3286 } else {
3287 ALOGE("Attempt to defer transaction to to an"
3288 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003289 }
3290 }
chaviw8b3871a2017-11-01 17:41:01 -07003291 // We don't trigger a traversal here because if no other state is
3292 // changed, we don't want this to cause any more work
3293 }
3294 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003295 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003296 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003297 if (!hadParent) {
3298 mCurrentState.layersSortedByZ.remove(layer);
3299 }
chaviw8b3871a2017-11-01 17:41:01 -07003300 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 }
3303 if (what & layer_state_t::eReparentChildren) {
3304 if (layer->reparentChildren(s.reparentHandle)) {
3305 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003306 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003307 }
chaviw8b3871a2017-11-01 17:41:01 -07003308 if (what & layer_state_t::eDetachChildren) {
3309 layer->detachChildren();
3310 }
3311 if (what & layer_state_t::eOverrideScalingModeChanged) {
3312 layer->setOverrideScalingMode(s.overrideScalingMode);
3313 // We don't trigger a traversal here because if no other state is
3314 // changed, we don't want this to cause any more work
3315 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316 return flags;
3317}
3318
chaviwca27f252018-02-06 16:46:39 -08003319void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3320 const layer_state_t& state = composerState.state;
3321 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3322
3323 sp<Layer> layer(client->getLayerUser(state.surface));
3324 if (layer == nullptr) {
3325 return;
3326 }
3327
3328 if (layer->isPendingRemoval()) {
3329 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3330 return;
3331 }
3332
3333 if (state.what & layer_state_t::eDestroySurface) {
3334 removeLayerLocked(mStateLock, layer);
3335 }
3336}
3337
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003338status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003339 const String8& name,
3340 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003341 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003342 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3343 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003345 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003346 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003347 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003348 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003349 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003350
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003351 status_t result = NO_ERROR;
3352
3353 sp<Layer> layer;
3354
Cody Northropbc755282017-03-31 12:00:08 -06003355 String8 uniqueName = getUniqueLayerName(name);
3356
Mathias Agopian3165cc22012-08-08 19:42:09 -07003357 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3358 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003359 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003360 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003361 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003362
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363 break;
chaviw13fdc492017-06-27 12:40:18 -07003364 case ISurfaceComposerClient::eFXSurfaceColor:
3365 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003366 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003367 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003368 break;
3369 default:
3370 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371 break;
3372 }
3373
Dan Stoza7d89d062015-04-30 13:29:25 -07003374 if (result != NO_ERROR) {
3375 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003376 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003377
Chia-I Wuab0c3192017-08-01 11:29:00 -07003378 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3379 // TODO b/64227542
3380 if (windowType == 441731) {
3381 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3382 layer->setPrimaryDisplayOnly();
3383 }
3384
Albert Chaulk479c60c2017-01-27 14:21:34 -05003385 layer->setInfo(windowType, ownerUid);
3386
Robert Carr1f0a16a2016-10-24 16:27:39 -07003387 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003388 if (result != NO_ERROR) {
3389 return result;
3390 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003391 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003392
3393 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003394 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003395}
3396
Cody Northropbc755282017-03-31 12:00:08 -06003397String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3398{
3399 bool matchFound = true;
3400 uint32_t dupeCounter = 0;
3401
3402 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3403 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3404
3405 // Loop over layers until we're sure there is no matching name
3406 while (matchFound) {
3407 matchFound = false;
3408 mDrawingState.traverseInZOrder([&](Layer* layer) {
3409 if (layer->getName() == uniqueName) {
3410 matchFound = true;
3411 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3412 }
3413 });
3414 }
3415
3416 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3417
3418 return uniqueName;
3419}
3420
David Sodman0c69cad2017-08-21 12:12:51 -07003421status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003422 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3423 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424{
3425 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003426 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003427 case PIXEL_FORMAT_TRANSPARENT:
3428 case PIXEL_FORMAT_TRANSLUCENT:
3429 format = PIXEL_FORMAT_RGBA_8888;
3430 break;
3431 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003432 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003433 break;
3434 }
3435
David Sodman0c69cad2017-08-21 12:12:51 -07003436 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3437 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003438 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003439 *handle = layer->getHandle();
3440 *gbp = layer->getProducer();
3441 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003443
David Sodman0c69cad2017-08-21 12:12:51 -07003444 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003445 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446}
3447
chaviw13fdc492017-06-27 12:40:18 -07003448status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003449 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003450 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003451{
chaviw13fdc492017-06-27 12:40:18 -07003452 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003453 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003454 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003455}
3456
Mathias Agopianac9fa422013-02-11 16:40:36 -08003457status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003458{
Robert Carr9524cb32017-02-13 11:32:32 -08003459 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003460 status_t err = NO_ERROR;
3461 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003462 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003463 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003464 err = removeLayer(l);
3465 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3466 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003467 }
3468 return err;
3469}
3470
Mathias Agopian13127d82013-03-05 17:47:11 -08003471status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003472{
Mathias Agopian67106042013-03-14 19:18:13 -07003473 // called by ~LayerCleaner() when all references to the IBinder (handle)
3474 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003475 sp<Layer> l = layer.promote();
3476 if (l == nullptr) {
3477 // The layer has already been removed, carry on
3478 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003479 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003480 // If we have a parent, then we can continue to live as long as it does.
3481 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482}
3483
Mathias Agopianb60314a2012-04-10 22:09:54 -07003484// ---------------------------------------------------------------------------
3485
Andy McFadden13a082e2012-08-24 10:16:42 -07003486void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003487 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003488 Vector<ComposerState> state;
3489 Vector<DisplayState> displays;
3490 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003491 d.what = DisplayState::eDisplayProjectionChanged |
3492 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003493 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003494 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003495 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003496 d.frame.makeInvalid();
3497 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003498 d.width = 0;
3499 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003500 displays.add(d);
3501 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003502 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3503 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003504
David Sodman105b7dc2017-11-04 20:28:14 -07003505 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003506 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003507 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003508
Brian Andersond0010582017-03-07 13:20:31 -08003509 // Use phase of 0 since phase is not known.
3510 // Use latency of 0, which will snap to the ideal latency.
3511 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003512}
3513
3514void SurfaceFlinger::initializeDisplays() {
3515 class MessageScreenInitialized : public MessageBase {
3516 SurfaceFlinger* flinger;
3517 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003518 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003519 virtual bool handler() {
3520 flinger->onInitializeDisplays();
3521 return true;
3522 }
3523 };
3524 sp<MessageBase> msg = new MessageScreenInitialized(this);
3525 postMessageAsync(msg); // we may be called from main thread, use async message
3526}
3527
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003528void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003529 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3531 this);
3532 int32_t type = hw->getDisplayType();
3533 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003534
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003536 return;
3537 }
3538
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003539 hw->setPowerMode(mode);
3540 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3541 ALOGW("Trying to set power mode for virtual display");
3542 return;
3543 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003544
Lloyd Pique4dccc412018-01-22 17:21:36 -08003545 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003546 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003547 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3548 if (idx < 0) {
3549 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3550 return;
3551 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003552 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003553 }
3554
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003555 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003556 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003557 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003558 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3559 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003560 // FIXME: eventthread only knows about the main display right now
3561 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003562 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003563 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003565 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003566 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003567 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003568
3569 struct sched_param param = {0};
3570 param.sched_priority = 1;
3571 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3572 ALOGW("Couldn't set SCHED_FIFO on display on");
3573 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003574 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003575 // Turn off the display
3576 struct sched_param param = {0};
3577 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3578 ALOGW("Couldn't set SCHED_OTHER on display off");
3579 }
3580
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003581 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3582 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003583 disableHardwareVsync(true); // also cancels any in-progress resync
3584
Mathias Agopiancde87a32012-09-13 14:09:01 -07003585 // FIXME: eventthread only knows about the main display right now
3586 mEventThread->onScreenReleased();
3587 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003588
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003589 getHwComposer().setPowerMode(type, mode);
3590 mVisibleRegionsDirty = true;
3591 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003592 } else if (mode == HWC_POWER_MODE_DOZE ||
3593 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003594 // Update display while dozing
3595 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003596 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3597 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003598 // FIXME: eventthread only knows about the main display right now
3599 mEventThread->onScreenAcquired();
3600 resyncToHardwareVsync(true);
3601 }
3602 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3603 // Leave display going to doze
3604 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3605 disableHardwareVsync(true); // also cancels any in-progress resync
3606 // FIXME: eventthread only knows about the main display right now
3607 mEventThread->onScreenReleased();
3608 }
3609 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003610 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003611 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003612 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003613 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003614}
3615
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003616void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3617 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003618 SurfaceFlinger& mFlinger;
3619 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003620 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003621 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003622 MessageSetPowerMode(SurfaceFlinger& flinger,
3623 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3624 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003625 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003626 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003627 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003628 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003629 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003630 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003631 ALOGW("Attempt to set power mode = %d for virtual display",
3632 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003633 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003634 mFlinger.setPowerModeInternal(
3635 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003636 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003637 return true;
3638 }
3639 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003640 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003641 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003642}
3643
3644// ---------------------------------------------------------------------------
3645
Lloyd Pique755e3192018-01-31 16:46:15 -08003646status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3647 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003649
Mathias Agopianbd115332013-04-18 16:41:04 -07003650 IPCThreadState* ipc = IPCThreadState::self();
3651 const int pid = ipc->getCallingPid();
3652 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003653
Mathias Agopianbd115332013-04-18 16:41:04 -07003654 if ((uid != AID_SHELL) &&
3655 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003656 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003657 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003658 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003659 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003660 // (this would indicate SF is stuck, but we want to be able to
3661 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003662 status_t err = mStateLock.timedLock(s2ns(1));
3663 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003664 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003665 result.appendFormat(
3666 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3667 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003668 }
3669
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003670 bool dumpAll = true;
3671 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003672 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003673
3674 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003675 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003676 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3677 dumpAll = false;
3678 }
3679
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003680 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003681 if ((index < numArgs) &&
3682 (args[index] == String16("--list"))) {
3683 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003684 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003685 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003686 }
3687
3688 if ((index < numArgs) &&
3689 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003690 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003691 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003692 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003693 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003694
3695 if ((index < numArgs) &&
3696 (args[index] == String16("--latency-clear"))) {
3697 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003698 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003699 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003700 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003701
3702 if ((index < numArgs) &&
3703 (args[index] == String16("--dispsync"))) {
3704 index++;
3705 mPrimaryDispSync.dump(result);
3706 dumpAll = false;
3707 }
Dan Stozab90cf072015-03-05 11:05:59 -08003708
3709 if ((index < numArgs) &&
3710 (args[index] == String16("--static-screen"))) {
3711 index++;
3712 dumpStaticScreenStats(result);
3713 dumpAll = false;
3714 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003715
3716 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003717 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003718 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003719 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003720 dumpAll = false;
3721 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003722
3723 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3724 index++;
3725 dumpWideColorInfo(result);
3726 dumpAll = false;
3727 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003728
3729 if ((index < numArgs) &&
3730 (args[index] == String16("--enable-layer-stats"))) {
3731 index++;
3732 mLayerStats.enable();
3733 dumpAll = false;
3734 }
3735
3736 if ((index < numArgs) &&
3737 (args[index] == String16("--disable-layer-stats"))) {
3738 index++;
3739 mLayerStats.disable();
3740 dumpAll = false;
3741 }
3742
3743 if ((index < numArgs) &&
3744 (args[index] == String16("--clear-layer-stats"))) {
3745 index++;
3746 mLayerStats.clear();
3747 dumpAll = false;
3748 }
3749
3750 if ((index < numArgs) &&
3751 (args[index] == String16("--dump-layer-stats"))) {
3752 index++;
3753 mLayerStats.dump(result);
3754 dumpAll = false;
3755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003757
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003759 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003760 }
3761
Mathias Agopian9795c422009-08-26 16:36:26 -07003762 if (locked) {
3763 mStateLock.unlock();
3764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003765 }
3766 write(fd, result.string(), result.size());
3767 return NO_ERROR;
3768}
3769
Dan Stozac7014012014-02-14 15:03:43 -08003770void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3771 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003772{
Robert Carr2047fae2016-11-28 14:09:09 -08003773 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003774 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003775 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003776}
3777
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003778void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003779 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003780{
3781 String8 name;
3782 if (index < args.size()) {
3783 name = String8(args[index]);
3784 index++;
3785 }
3786
David Sodman105b7dc2017-11-04 20:28:14 -07003787 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003788 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003789 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003790
3791 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003792 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003793 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003794 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003795 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003796 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003797 }
Robert Carr2047fae2016-11-28 14:09:09 -08003798 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003799 }
3800}
3801
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003802void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003803 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003804{
3805 String8 name;
3806 if (index < args.size()) {
3807 name = String8(args[index]);
3808 index++;
3809 }
3810
Robert Carr2047fae2016-11-28 14:09:09 -08003811 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003812 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003813 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003814 }
Robert Carr2047fae2016-11-28 14:09:09 -08003815 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003816
Svetoslavd85084b2014-03-20 10:28:31 -07003817 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818}
3819
Jamie Gennis6547ff42013-07-16 20:12:42 -07003820// This should only be called from the main thread. Otherwise it would need
3821// the lock and should use mCurrentState rather than mDrawingState.
3822void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003823 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003824 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003825 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003826
3827 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3828}
3829
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003830void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003831{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003832 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003833
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003834 if (isLayerTripleBufferingDisabled())
3835 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003836
3837 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003838 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003839 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003840 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003841 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3842 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003843 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003844}
3845
Dan Stozab90cf072015-03-05 11:05:59 -08003846void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3847{
3848 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003849 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3850 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003851 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003852 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003853 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3854 b + 1, bucketTimeSec, percent);
3855 }
David Sodman4a36e932017-11-07 14:29:47 -08003856 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003857 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003858 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003859 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003860 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003861}
3862
Dan Stozae77c7662016-05-13 11:37:28 -07003863void SurfaceFlinger::recordBufferingStats(const char* layerName,
3864 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003865 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3866 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003867 for (const auto& segment : history) {
3868 if (!segment.usedThirdBuffer) {
3869 stats.twoBufferTime += segment.totalTime;
3870 }
3871 if (segment.occupancyAverage < 1.0f) {
3872 stats.doubleBufferedTime += segment.totalTime;
3873 } else if (segment.occupancyAverage < 2.0f) {
3874 stats.tripleBufferedTime += segment.totalTime;
3875 }
3876 ++stats.numSegments;
3877 stats.totalTime += segment.totalTime;
3878 }
3879}
3880
Brian Andersond6927fb2016-07-23 23:37:30 -07003881void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3882 result.appendFormat("Layer frame timestamps:\n");
3883
3884 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3885 const size_t count = currentLayers.size();
3886 for (size_t i=0 ; i<count ; i++) {
3887 currentLayers[i]->dumpFrameEvents(result);
3888 }
3889}
3890
Dan Stozae77c7662016-05-13 11:37:28 -07003891void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3892 result.append("Buffering stats:\n");
3893 result.append(" [Layer name] <Active time> <Two buffer> "
3894 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003895 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003896 typedef std::tuple<std::string, float, float, float> BufferTuple;
3897 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003898 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003899 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003900 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003901 if (stats.numSegments == 0) {
3902 continue;
3903 }
3904 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3905 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3906 stats.totalTime;
3907 float doubleBufferRatio = static_cast<float>(
3908 stats.doubleBufferedTime) / stats.totalTime;
3909 float tripleBufferRatio = static_cast<float>(
3910 stats.tripleBufferedTime) / stats.totalTime;
3911 sorted.insert({activeTime, {name, twoBufferRatio,
3912 doubleBufferRatio, tripleBufferRatio}});
3913 }
3914 for (const auto& sortedPair : sorted) {
3915 float activeTime = sortedPair.first;
3916 const BufferTuple& values = sortedPair.second;
3917 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3918 std::get<0>(values).c_str(), activeTime,
3919 std::get<1>(values), std::get<2>(values),
3920 std::get<3>(values));
3921 }
3922 result.append("\n");
3923}
3924
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003925void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3926 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003927 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003928
3929 // TODO: print out if wide-color mode is active or not
3930
3931 for (size_t d = 0; d < mDisplays.size(); d++) {
3932 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3933 int32_t hwcId = displayDevice->getHwcDisplayId();
3934 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3935 continue;
3936 }
3937
3938 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003939 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003940 for (auto&& mode : modes) {
3941 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3942 }
3943
Peiyong Lina52f0292018-03-14 17:26:31 -07003944 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003945 result.appendFormat(" Current color mode: %s (%d)\n",
3946 decodeColorMode(currentMode).c_str(), currentMode);
3947 }
3948 result.append("\n");
3949}
3950
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003951LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003952 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003953 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3954 const State& state = useDrawing ? mDrawingState : mCurrentState;
3955 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003956 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003957 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003958 });
3959
3960 return layersProto;
3961}
3962
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003963LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
3964 LayersProto layersProto;
3965
3966 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
3967 SizeProto* resolution = layersProto.mutable_resolution();
3968 resolution->set_w(displayDevice->getWidth());
3969 resolution->set_h(displayDevice->getHeight());
3970
3971 mDrawingState.traverseInZOrder([&](Layer* layer) {
3972 if (!layer->visibleRegion.isEmpty() &&
3973 layer->getBE().mHwcLayers.count(hwcId)) {
3974 LayerProto* layerProto = layersProto.add_layers();
3975 layer->writeToProto(layerProto, hwcId);
3976 }
3977 });
3978
3979 return layersProto;
3980}
3981
Mathias Agopian74d211a2013-04-22 16:55:35 +02003982void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3983 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003984{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003985 bool colorize = false;
3986 if (index < args.size()
3987 && (args[index] == String16("--color"))) {
3988 colorize = true;
3989 index++;
3990 }
3991
3992 Colorizer colorizer(colorize);
3993
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003994 // figure out if we're stuck somewhere
3995 const nsecs_t now = systemTime();
3996 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3997 const nsecs_t inTransaction(mDebugInTransaction);
3998 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3999 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4000
4001 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004002 * Dump library configuration.
4003 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004
4005 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004006 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004007 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004008 appendSfConfigString(result);
4009 appendUiConfigString(result);
4010 appendGuiConfigString(result);
4011 result.append("\n");
4012
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004013 result.append("\nWide-Color information:\n");
4014 dumpWideColorInfo(result);
4015
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004016 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004017 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004018 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004019 result.append(SyncFeatures::getInstance().toString());
4020 result.append("\n");
4021
David Sodman105b7dc2017-11-04 20:28:14 -07004022 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004023
Andy McFadden41d67d72014-04-25 16:58:34 -07004024 colorizer.bold(result);
4025 result.append("DispSync configuration: ");
4026 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004027 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004028 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004029 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004030 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004031 result.append("\n");
4032
Dan Stozab90cf072015-03-05 11:05:59 -08004033 // Dump static screen stats
4034 result.append("\n");
4035 dumpStaticScreenStats(result);
4036 result.append("\n");
4037
Dan Stozae77c7662016-05-13 11:37:28 -07004038 dumpBufferingStats(result);
4039
Andy McFadden4803b742012-09-24 19:07:20 -07004040 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004041 * Dump the visible layer list
4042 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004043 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004044 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004045 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4046 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004047 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004048
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004049 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004050 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4051 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004052
4053 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004054 * Dump Display state
4055 */
4056
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004057 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004058 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004059 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004060 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4061 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004063 }
4064
4065 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004066 * Dump SurfaceFlinger global state
4067 */
4068
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004069 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004070 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004071 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004072
Mathias Agopian888c8222012-08-04 21:10:38 -07004073 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004074 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004075
David Sodmanbc815282017-11-05 18:57:52 -08004076 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004077
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004078 if (hw) {
4079 hw->undefinedRegion.dump(result, "undefinedRegion");
4080 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4081 hw->getOrientation(), hw->isDisplayOn());
4082 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004083 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004084 " last eglSwapBuffers() time: %f us\n"
4085 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004086 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004087 " refresh-rate : %f fps\n"
4088 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004089 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004090 " gpu_to_cpu_unsupported : %d\n"
4091 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004092 mLastSwapBufferTime/1000.0,
4093 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004094 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004095 1e9 / activeConfig->getVsyncPeriod(),
4096 activeConfig->getDpiX(),
4097 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004098 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004099
Mathias Agopian74d211a2013-04-22 16:55:35 +02004100 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004101 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004102
Mathias Agopian74d211a2013-04-22 16:55:35 +02004103 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004104 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004105
4106 /*
4107 * VSYNC state
4108 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004109 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004110 result.append("\n");
4111
4112 /*
4113 * HWC layer minidump
4114 */
4115 for (size_t d = 0; d < mDisplays.size(); d++) {
4116 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4117 int32_t hwcId = displayDevice->getHwcDisplayId();
4118 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4119 continue;
4120 }
4121
4122 result.appendFormat("Display %d HWC layers:\n", hwcId);
4123 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004124 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004125 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004126 });
Dan Stozae22aec72016-08-01 13:20:59 -07004127 result.append("\n");
4128 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004129
4130 /*
4131 * Dump HWComposer state
4132 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004133 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004134 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004135 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004136 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004137 result.appendFormat(" h/w composer %s\n",
4138 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004140
4141 /*
4142 * Dump gralloc state
4143 */
4144 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4145 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004146
4147 /*
4148 * Dump VrFlinger state if in use.
4149 */
4150 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4151 result.append("VrFlinger state:\n");
4152 result.append(mVrFlinger->Dump().c_str());
4153 result.append("\n");
4154 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004155}
4156
Mathias Agopian13127d82013-03-05 17:47:11 -08004157const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004158SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004159 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004160 wp<IBinder> dpy;
4161 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4162 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4163 dpy = mDisplays.keyAt(i);
4164 break;
4165 }
4166 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004167 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004168 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4169 // Just use the primary display so we have something to return
4170 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4171 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004172 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004173}
4174
Keun young Park63f165f2012-08-31 10:53:36 -07004175bool SurfaceFlinger::startDdmConnection()
4176{
4177 void* libddmconnection_dso =
4178 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4179 if (!libddmconnection_dso) {
4180 return false;
4181 }
4182 void (*DdmConnection_start)(const char* name);
4183 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004184 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004185 if (!DdmConnection_start) {
4186 dlclose(libddmconnection_dso);
4187 return false;
4188 }
4189 (*DdmConnection_start)(getServiceName());
4190 return true;
4191}
4192
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004193status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004194 switch (code) {
4195 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004196 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004198 case CLEAR_ANIMATION_FRAME_STATS:
4199 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004200 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004201 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004202 case ENABLE_VSYNC_INJECTIONS:
4203 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004204 {
4205 // codes that require permission check
4206 IPCThreadState* ipc = IPCThreadState::self();
4207 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004208 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004209 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004210 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004211 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004212 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004213 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004214 break;
4215 }
Robert Carr1db73f62016-12-21 12:58:51 -08004216 /*
4217 * Calling setTransactionState is safe, because you need to have been
4218 * granted a reference to Client* and Handle* to do anything with it.
4219 *
4220 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4221 */
4222 case SET_TRANSACTION_STATE:
4223 case CREATE_SCOPED_CONNECTION:
4224 {
4225 return OK;
4226 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004227 case CAPTURE_SCREEN:
4228 {
4229 // codes that require permission check
4230 IPCThreadState* ipc = IPCThreadState::self();
4231 const int pid = ipc->getCallingPid();
4232 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004233 if ((uid != AID_GRAPHICS) &&
4234 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004235 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004236 return PERMISSION_DENIED;
4237 }
4238 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004239 }
chaviwa76b2712017-09-20 12:02:26 -07004240 case CAPTURE_LAYERS: {
4241 IPCThreadState* ipc = IPCThreadState::self();
4242 const int pid = ipc->getCallingPid();
4243 const int uid = ipc->getCallingUid();
4244 if ((uid != AID_GRAPHICS) &&
4245 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4246 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4247 return PERMISSION_DENIED;
4248 }
4249 break;
4250 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004252 return OK;
4253}
4254
4255status_t SurfaceFlinger::onTransact(
4256 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4257{
4258 status_t credentialCheck = CheckTransactCodeCredentials(code);
4259 if (credentialCheck != OK) {
4260 return credentialCheck;
4261 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004262
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004263 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4264 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004265 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004266 IPCThreadState* ipc = IPCThreadState::self();
4267 const int uid = ipc->getCallingUid();
4268 if (CC_UNLIKELY(uid != AID_SYSTEM
4269 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004270 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004271 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004272 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 return PERMISSION_DENIED;
4274 }
4275 int n;
4276 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004277 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004278 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004279 return NO_ERROR;
4280 case 1002: // SHOW_UPDATES
4281 n = data.readInt32();
4282 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004283 invalidateHwcGeometry();
4284 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004286 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004287 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004288 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004290 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004291 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004292 setTransactionFlags(
4293 eTransactionNeeded|
4294 eDisplayTransactionNeeded|
4295 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004296 return NO_ERROR;
4297 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004298 case 1006:{ // send empty update
4299 signalRefresh();
4300 return NO_ERROR;
4301 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004302 case 1008: // toggle use of hw composer
4303 n = data.readInt32();
4304 mDebugDisableHWC = n ? 1 : 0;
4305 invalidateHwcGeometry();
4306 repaintEverything();
4307 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004308 case 1009: // toggle use of transform hint
4309 n = data.readInt32();
4310 mDebugDisableTransformHint = n ? 1 : 0;
4311 invalidateHwcGeometry();
4312 repaintEverything();
4313 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004314 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004315 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 reply->writeInt32(0);
4317 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004318 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004319 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004320 return NO_ERROR;
4321 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004322 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004323 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004324 return NO_ERROR;
4325 }
4326 case 1014: {
4327 // daltonize
4328 n = data.readInt32();
4329 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004330 case 1:
4331 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4332 break;
4333 case 2:
4334 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4335 break;
4336 case 3:
4337 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4338 break;
4339 default:
4340 mDaltonizer.setType(ColorBlindnessType::None);
4341 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004342 }
4343 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004344 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004345 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004346 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004347 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004348 invalidateHwcGeometry();
4349 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004350 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004351 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004352 case 1015: {
4353 // apply a color matrix
4354 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004355 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004356 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004357 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004358 for (size_t j = 0; j < 4; j++) {
4359 mColorMatrix[i][j] = data.readFloat();
4360 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004361 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004362 } else {
4363 mColorMatrix = mat4();
4364 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004365
4366 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4367 // the division by w in the fragment shader
4368 float4 lastRow(transpose(mColorMatrix)[3]);
4369 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4370 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4371 }
4372
Alan Viverette9c5a3332013-09-12 20:04:35 -07004373 invalidateHwcGeometry();
4374 repaintEverything();
4375 return NO_ERROR;
4376 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004377 // This is an experimental interface
4378 // Needs to be shifted to proper binder interface when we productize
4379 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004380 n = data.readInt32();
4381 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004382 return NO_ERROR;
4383 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004384 case 1017: {
4385 n = data.readInt32();
4386 mForceFullDamage = static_cast<bool>(n);
4387 return NO_ERROR;
4388 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004389 case 1018: { // Modify Choreographer's phase offset
4390 n = data.readInt32();
4391 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4392 return NO_ERROR;
4393 }
4394 case 1019: { // Modify SurfaceFlinger's phase offset
4395 n = data.readInt32();
4396 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4397 return NO_ERROR;
4398 }
Irvel468051e2016-06-13 16:44:44 -07004399 case 1020: { // Layer updates interceptor
4400 n = data.readInt32();
4401 if (n) {
4402 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004403 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004404 }
4405 else{
4406 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004407 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004408 }
4409 return NO_ERROR;
4410 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004411 case 1021: { // Disable HWC virtual displays
4412 n = data.readInt32();
4413 mUseHwcVirtualDisplays = !n;
4414 return NO_ERROR;
4415 }
Romain Guy0147a172017-06-01 13:53:56 -07004416 case 1022: { // Set saturation boost
4417 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4418
4419 invalidateHwcGeometry();
4420 repaintEverything();
4421 return NO_ERROR;
4422 }
Romain Guy54f154a2017-10-24 21:40:32 +01004423 case 1023: { // Set native mode
4424 mForceNativeColorMode = data.readInt32() == 1;
4425
4426 invalidateHwcGeometry();
4427 repaintEverything();
4428 return NO_ERROR;
4429 }
4430 case 1024: { // Is wide color gamut rendering/color management supported?
4431 reply->writeBool(hasWideColorDisplay);
4432 return NO_ERROR;
4433 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004434 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004435 n = data.readInt32();
4436 if (n) {
4437 ALOGV("LayerTracing enabled");
4438 mTracing.enable();
4439 doTracing("tracing.enable");
4440 reply->writeInt32(NO_ERROR);
4441 } else {
4442 ALOGV("LayerTracing disabled");
4443 status_t err = mTracing.disable();
4444 reply->writeInt32(err);
4445 }
4446 return NO_ERROR;
4447 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004448 case 1026: { // Get layer tracing status
4449 reply->writeBool(mTracing.isEnabled());
4450 return NO_ERROR;
4451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 }
4453 }
4454 return err;
4455}
4456
Steven Thomas6d8110b2017-08-31 18:24:21 -07004457void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004458 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004459 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004460}
4461
Steven Thomas6d8110b2017-08-31 18:24:21 -07004462void SurfaceFlinger::repaintEverything() {
4463 ConditionalLock _l(mStateLock,
4464 std::this_thread::get_id() != mMainThreadId);
4465 repaintEverythingLocked();
4466}
4467
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004468// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4469class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004470public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004471 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4472 ~WindowDisconnector() {
4473 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004474 }
4475
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004476private:
4477 ANativeWindow* mWindow;
4478 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004479};
4480
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004481status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4482 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4483 int32_t minLayerZ, int32_t maxLayerZ,
4484 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004485 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004486 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004487
chaviwa76b2712017-09-20 12:02:26 -07004488 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4489
4490 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004491 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4492
chaviwa76b2712017-09-20 12:02:26 -07004493 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4494
4495 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4496 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004497 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004498}
4499
4500status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004501 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004502 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004503 ATRACE_CALL();
4504
4505 class LayerRenderArea : public RenderArea {
4506 public:
Robert Carr578038f2018-03-09 12:25:24 -08004507 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4508 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4509 : RenderArea(reqHeight, reqWidth),
4510 mLayer(layer),
4511 mCrop(crop),
4512 mFlinger(flinger),
4513 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004514 Rect getBounds() const override {
4515 const Layer::State& layerState(mLayer->getDrawingState());
4516 return Rect(layerState.active.w, layerState.active.h);
4517 }
4518 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4519 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4520 bool isSecure() const override { return false; }
4521 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004522 const Transform& getTransform() const { return mTransform; }
4523
4524 class ReparentForDrawing {
4525 public:
4526 const sp<Layer>& oldParent;
4527 const sp<Layer>& newParent;
4528
4529 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4530 : oldParent(oldParent), newParent(newParent) {
4531 oldParent->reparentChildrenForDrawing(newParent);
4532 }
4533 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4534 };
4535
4536 void render(std::function<void()> drawLayers) override {
4537 if (!mChildrenOnly) {
4538 mTransform = mLayer->getTransform().inverse();
4539 drawLayers();
4540 } else {
4541 Rect bounds = getBounds();
4542 screenshotParentLayer =
4543 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4544 bounds.getWidth(), bounds.getHeight(), 0);
4545
4546 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4547 drawLayers();
4548 }
4549 }
chaviwa76b2712017-09-20 12:02:26 -07004550
chaviw7206d492017-11-10 16:16:12 -08004551 Rect getSourceCrop() const override {
4552 if (mCrop.isEmpty()) {
4553 return getBounds();
4554 } else {
4555 return mCrop;
4556 }
4557 }
chaviwa76b2712017-09-20 12:02:26 -07004558 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004559 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004560
4561 private:
chaviw7206d492017-11-10 16:16:12 -08004562 const sp<Layer> mLayer;
4563 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004564
4565 // In the "childrenOnly" case we reparent the children to a screenshot
4566 // layer which has no properties set and which does not draw.
4567 sp<ContainerLayer> screenshotParentLayer;
4568 Transform mTransform;
4569
4570 SurfaceFlinger* mFlinger;
4571 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004572 };
4573
4574 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4575 auto parent = layerHandle->owner.promote();
4576
chaviw7206d492017-11-10 16:16:12 -08004577 if (parent == nullptr || parent->isPendingRemoval()) {
4578 ALOGE("captureLayers called with a removed parent");
4579 return NAME_NOT_FOUND;
4580 }
4581
Robert Carr578038f2018-03-09 12:25:24 -08004582 const int uid = IPCThreadState::self()->getCallingUid();
4583 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4584 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4585 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4586 return PERMISSION_DENIED;
4587 }
4588
chaviw7206d492017-11-10 16:16:12 -08004589 Rect crop(sourceCrop);
4590 if (sourceCrop.width() <= 0) {
4591 crop.left = 0;
4592 crop.right = parent->getCurrentState().active.w;
4593 }
4594
4595 if (sourceCrop.height() <= 0) {
4596 crop.top = 0;
4597 crop.bottom = parent->getCurrentState().active.h;
4598 }
4599
4600 int32_t reqWidth = crop.width() * frameScale;
4601 int32_t reqHeight = crop.height() * frameScale;
4602
Robert Carr578038f2018-03-09 12:25:24 -08004603 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004604
Robert Carr578038f2018-03-09 12:25:24 -08004605 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004606 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4607 if (!layer->isVisible()) {
4608 return;
Robert Carr578038f2018-03-09 12:25:24 -08004609 } else if (childrenOnly && layer == parent.get()) {
4610 return;
chaviwa76b2712017-09-20 12:02:26 -07004611 }
4612 visitor(layer);
4613 });
4614 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004615 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004616}
4617
4618status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4619 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004620 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004621 bool useIdentityTransform) {
4622 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004623
chaviwa76b2712017-09-20 12:02:26 -07004624 renderArea.updateDimensions();
4625
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004626 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4627 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4628 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4629 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004630
4631 // This mutex protects syncFd and captureResult for communication of the return values from the
4632 // main thread back to this Binder thread
4633 std::mutex captureMutex;
4634 std::condition_variable captureCondition;
4635 std::unique_lock<std::mutex> captureLock(captureMutex);
4636 int syncFd = -1;
4637 std::optional<status_t> captureResult;
4638
Robert Carr03480e22018-01-04 16:02:06 -08004639 const int uid = IPCThreadState::self()->getCallingUid();
4640 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4641
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004642 sp<LambdaMessage> message = new LambdaMessage([&]() {
4643 // If there is a refresh pending, bug out early and tell the binder thread to try again
4644 // after the refresh.
4645 if (mRefreshPending) {
4646 ATRACE_NAME("Skipping screenshot for now");
4647 std::unique_lock<std::mutex> captureLock(captureMutex);
4648 captureResult = std::make_optional<status_t>(EAGAIN);
4649 captureCondition.notify_one();
4650 return;
4651 }
4652
4653 status_t result = NO_ERROR;
4654 int fd = -1;
4655 {
4656 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004657 renderArea.render([&]() {
4658 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4659 useIdentityTransform, forSystem, &fd);
4660 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004661 }
4662
4663 {
4664 std::unique_lock<std::mutex> captureLock(captureMutex);
4665 syncFd = fd;
4666 captureResult = std::make_optional<status_t>(result);
4667 captureCondition.notify_one();
4668 }
4669 });
4670
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004671 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004672 if (result == NO_ERROR) {
4673 captureCondition.wait(captureLock, [&]() { return captureResult; });
4674 while (*captureResult == EAGAIN) {
4675 captureResult.reset();
4676 result = postMessageAsync(message);
4677 if (result != NO_ERROR) {
4678 return result;
4679 }
4680 captureCondition.wait(captureLock, [&]() { return captureResult; });
4681 }
4682 result = *captureResult;
4683 }
4684
4685 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004686 sync_wait(syncFd, -1);
4687 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004688 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004689
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004690 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004691}
4692
chaviwa76b2712017-09-20 12:02:26 -07004693void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4694 TraverseLayersFunction traverseLayers, bool yswap,
4695 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004696 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004697
Lloyd Pique144e1162017-12-20 16:44:52 -08004698 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004699
4700 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004701 const auto raWidth = renderArea.getWidth();
4702 const auto raHeight = renderArea.getHeight();
4703
4704 const auto reqWidth = renderArea.getReqWidth();
4705 const auto reqHeight = renderArea.getReqHeight();
4706 Rect sourceCrop = renderArea.getSourceCrop();
4707
4708 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4709 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004710
Dan Stozac1879002014-05-22 15:59:05 -07004711 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004712 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004713 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004714 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004715 }
4716
4717 // ensure that sourceCrop is inside screen
4718 if (sourceCrop.left < 0) {
4719 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4720 }
chaviwa76b2712017-09-20 12:02:26 -07004721 if (sourceCrop.right > raWidth) {
4722 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004723 }
4724 if (sourceCrop.top < 0) {
4725 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4726 }
chaviwa76b2712017-09-20 12:02:26 -07004727 if (sourceCrop.bottom > raHeight) {
4728 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004729 }
4730
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004731 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004732 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004733 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004734 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4735 }
4736 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004737
Mathias Agopian180f10d2013-04-10 22:55:41 -07004738 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004739 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004740
4741 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004742 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4743 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004744 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004745
4746 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004747 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004748
chaviwa76b2712017-09-20 12:02:26 -07004749 traverseLayers([&](Layer* layer) {
4750 if (filtering) layer->setFiltering(true);
4751 layer->draw(renderArea, useIdentityTransform);
4752 if (filtering) layer->setFiltering(false);
4753 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004754}
4755
chaviwa76b2712017-09-20 12:02:26 -07004756status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4757 TraverseLayersFunction traverseLayers,
4758 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004759 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004760 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004761 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004762 ATRACE_CALL();
4763
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004764 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004765
4766 traverseLayers([&](Layer* layer) {
4767 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4768 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004769
Robert Carr03480e22018-01-04 16:02:06 -08004770 // We allow the system server to take screenshots of secure layers for
4771 // use in situations like the Screen-rotation animation and place
4772 // the impetus on WindowManager to not persist them.
4773 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004774 ALOGW("FB is protected: PERMISSION_DENIED");
4775 return PERMISSION_DENIED;
4776 }
4777
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004778 // this binds the given EGLImage as a framebuffer for the
4779 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004780 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004781 if (bufferBond.getStatus() != NO_ERROR) {
4782 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004783 return INVALID_OPERATION;
4784 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004785
Dan Stozaabcda352017-06-01 14:37:39 -07004786 // this will in fact render into our dequeued buffer
4787 // via an FBO, which means we didn't have to create
4788 // an EGLSurface and therefore we're not
4789 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004790 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004791
Dan Stozaabcda352017-06-01 14:37:39 -07004792 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004793 getRenderEngine().finish();
4794 *outSyncFd = -1;
4795
chaviwa76b2712017-09-20 12:02:26 -07004796 const auto reqWidth = renderArea.getReqWidth();
4797 const auto reqHeight = renderArea.getReqHeight();
4798
Dan Stozaabcda352017-06-01 14:37:39 -07004799 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4800 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004801 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004802 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004803 } else {
4804 base::unique_fd syncFd = getRenderEngine().flush();
4805 if (syncFd < 0) {
4806 getRenderEngine().finish();
4807 }
4808 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004809 }
4810
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004811 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004812}
4813
Mathias Agopiand5556842013-09-19 17:08:37 -07004814void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004815 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004816 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004817 for (size_t y = 0; y < h; y++) {
4818 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4819 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004820 if (p[x] != 0xFF000000) return;
4821 }
4822 }
chaviwa76b2712017-09-20 12:02:26 -07004823 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004824
Robert Carr2047fae2016-11-28 14:09:09 -08004825 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004826 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004827 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004828 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4829 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4830 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4831 static_cast<float>(state.color.a));
4832 i++;
4833 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004834 }
4835}
4836
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004837// ---------------------------------------------------------------------------
4838
Dan Stoza412903f2017-04-27 13:42:17 -07004839void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4840 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004841}
4842
Dan Stoza412903f2017-04-27 13:42:17 -07004843void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4844 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004845}
4846
chaviwa76b2712017-09-20 12:02:26 -07004847void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4848 int32_t maxLayerZ,
4849 const LayerVector::Visitor& visitor) {
4850 // We loop through the first level of layers without traversing,
4851 // as we need to interpret min/max layer Z in the top level Z space.
4852 for (const auto& layer : mDrawingState.layersSortedByZ) {
4853 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4854 continue;
4855 }
4856 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004857 // relative layers are traversed in Layer::traverseInZOrder
4858 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004859 continue;
4860 }
4861 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004862 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4863 return;
4864 }
chaviwa76b2712017-09-20 12:02:26 -07004865 if (!layer->isVisible()) {
4866 return;
4867 }
4868 visitor(layer);
4869 });
4870 }
4871}
4872
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004873}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004874
4875
4876#if defined(__gl_h_)
4877#error "don't include gl/gl.h in this file"
4878#endif
4879
4880#if defined(__gl2_h_)
4881#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004882#endif