blob: d19fa2620c012e3ff54827248b6fe52360a33919 [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"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090092#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093
chaviw1d044282017-09-27 12:19:28 -070094#include <layerproto/LayerProtoParser.h>
95
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096#define DISPLAY_COUNT 1
97
Mathias Agopianfee2b462013-07-03 12:34:01 -070098/*
99 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
100 * black pixels.
101 */
102#define DEBUG_SCREENSHOTS false
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700105
Jaesoo Lee43518572017-01-23 19:03:16 +0900106using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700108using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700109using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700110using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700111using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112
Steven Thomasb02664d2017-07-26 18:48:28 -0700113namespace {
114class ConditionalLock {
115public:
116 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
117 if (lock) {
118 mMutex.lock();
119 }
120 }
121 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
122private:
123 Mutex& mMutex;
124 bool mLocked;
125};
126} // namespace anonymous
127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128// ---------------------------------------------------------------------------
129
Mathias Agopian99b49842011-06-27 16:05:52 -0700130const String16 sHardwareTest("android.permission.HARDWARE_TEST");
131const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
132const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
133const String16 sDump("android.permission.DUMP");
134
135// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800136int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
137int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700138int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700139bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800140uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800141bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800142bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800143int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800144// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600145bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700146
Kalle Raitaa099a242017-01-11 11:17:29 -0800147
148std::string getHwcServiceName() {
149 char value[PROPERTY_VALUE_MAX] = {};
150 property_get("debug.sf.hwc_service_name", value, "default");
151 ALOGI("Using HWComposer service: '%s'", value);
152 return std::string(value);
153}
154
155bool useTrebleTestingOverride() {
156 char value[PROPERTY_VALUE_MAX] = {};
157 property_get("debug.sf.treble_testing_override", value, "false");
158 ALOGI("Treble testing override: '%s'", value);
159 return std::string(value) == "true";
160}
161
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800162DisplayColorSetting toDisplayColorSetting(int value) {
163 switch(value) {
164 case 0:
165 return DisplayColorSetting::MANAGED;
166 case 1:
167 return DisplayColorSetting::UNMANAGED;
168 case 2:
169 return DisplayColorSetting::ENHANCED;
170 default:
171 return DisplayColorSetting::MANAGED;
172 }
173}
174
175std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
176 switch(displayColorSetting) {
177 case DisplayColorSetting::MANAGED:
178 return std::string("Natural Mode");
179 case DisplayColorSetting::UNMANAGED:
180 return std::string("Saturated Mode");
181 case DisplayColorSetting::ENHANCED:
182 return std::string("Auto Color Mode");
183 }
184 return std::string("Unknown Display Color Setting");
185}
186
Lloyd Pique99d3da52018-01-22 17:48:03 -0800187NativeWindowSurface::~NativeWindowSurface() = default;
188
189namespace impl {
190
191class NativeWindowSurface final : public android::NativeWindowSurface {
192public:
193 static std::unique_ptr<android::NativeWindowSurface> create(
194 const sp<IGraphicBufferProducer>& producer) {
195 return std::make_unique<NativeWindowSurface>(producer);
196 }
197
198 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
199 : surface(new Surface(producer, false)) {}
200
201 ~NativeWindowSurface() override = default;
202
203private:
204 sp<ANativeWindow> getNativeWindow() const override { return surface; }
205
206 void preallocateBuffers() override { surface->allocateBuffers(); }
207
208 sp<Surface> surface;
209};
210
211} // namespace impl
212
David Sodmanbc815282017-11-05 18:57:52 -0800213SurfaceFlingerBE::SurfaceFlingerBE()
214 : mHwcServiceName(getHwcServiceName()),
215 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800216 mFrameBuckets(),
217 mTotalTime(0),
218 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800219 mComposerSequenceId(0) {
220}
221
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800222SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800223 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700225 mTransactionPending(false),
226 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700227 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700228 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700229 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800231 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800233 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800234 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700236 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700237 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700238 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700239 mDebugInSwapBuffers(0),
240 mLastSwapBufferTime(0),
241 mDebugInTransaction(0),
242 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700243 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700244 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000245 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700246 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700247 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700248 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800249 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800250 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700251 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800252 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800253 mCreateBufferQueue(&BufferQueue::createBufferQueue),
254 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800255
256SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800257 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800258
259 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
260 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
261
262 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
263 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
264
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
266 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700268 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
270
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700271 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
273
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
276
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 // Vr flinger is only enabled on Daydream ready devices.
278 useVrFlinger = getBool< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::useVrFlinger>(false);
280
Fabien Sanglard1971b632017-03-10 14:50:03 -0800281 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
283
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600284 hasWideColorDisplay =
285 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
286
David Sodman99974d22017-11-28 12:04:33 -0800287 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289 // debugging stuff...
290 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700291
Mathias Agopianb4b17302013-03-20 18:36:41 -0700292 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700293 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700294
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800295 property_get("debug.sf.showupdates", value, "0");
296 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700297
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700298 property_get("debug.sf.ddms", value, "0");
299 mDebugDDMS = atoi(value);
300 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700301 if (!startDdmConnection()) {
302 // start failed, and DDMS debugging not enabled
303 mDebugDDMS = 0;
304 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700305 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700306 ALOGI_IF(mDebugRegion, "showupdates enabled");
307 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700308
309 property_get("debug.sf.disable_backpressure", value, "0");
310 mPropagateBackpressure = !atoi(value);
311 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700312
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800313 property_get("debug.sf.enable_hwc_vds", value, "0");
314 mUseHwcVirtualDisplays = atoi(value);
315 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800316
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800317 property_get("ro.sf.disable_triple_buffer", value, "1");
318 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800319 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700320
Dan Stoza0a0158c2018-03-16 13:38:54 -0700321 // TODO (b/74616334): Reduce the default value once we isolate the leak
322 const size_t defaultListSize = 4 * MAX_LAYERS;
323 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
324 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
325
Dan Stoza84d619e2018-03-28 17:07:36 -0700326 property_get("debug.sf.early_phase_offset_ns", value, "0");
327 const int earlyWakeupOffsetOffsetNs = atoi(value);
328 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
329 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
330 sfVsyncPhaseOffsetNs);
331
Romain Guy11d63f42017-07-20 12:47:14 -0700332 // We should be reading 'persist.sys.sf.color_saturation' here
333 // but since /data may be encrypted, we need to wait until after vold
334 // comes online to attempt to read the property. The property is
335 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800336
337 if (useTrebleTestingOverride()) {
338 // Without the override SurfaceFlinger cannot connect to HIDL
339 // services that are not listed in the manifests. Considered
340 // deriving the setting from the set service name, but it
341 // would be brittle if the name that's not 'default' is used
342 // for production purposes later on.
343 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
344 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345}
346
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800347void SurfaceFlinger::onFirstRef()
348{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800349 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800350}
351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352SurfaceFlinger::~SurfaceFlinger()
353{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354}
355
Dan Stozac7014012014-02-14 15:03:43 -0800356void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800357{
358 // the window manager died on us. prepare its eulogy.
359
Andy McFadden13a082e2012-08-24 10:16:42 -0700360 // restore initial conditions (default device unblank, etc)
361 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800362
363 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700364 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800365}
366
Robert Carr1db73f62016-12-21 12:58:51 -0800367static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700368 status_t err = client->initCheck();
369 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800370 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371 }
Robert Carr1db73f62016-12-21 12:58:51 -0800372 return nullptr;
373}
374
375sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
376 return initClient(new Client(this));
377}
378
379sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
380 const sp<IGraphicBufferProducer>& gbp) {
381 if (authenticateSurfaceTexture(gbp) == false) {
382 return nullptr;
383 }
384 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
385 if (layer == nullptr) {
386 return nullptr;
387 }
388
389 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390}
391
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700392sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
393 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700394{
395 class DisplayToken : public BBinder {
396 sp<SurfaceFlinger> flinger;
397 virtual ~DisplayToken() {
398 // no more references, this display must be terminated
399 Mutex::Autolock _l(flinger->mStateLock);
400 flinger->mCurrentState.displays.removeItem(this);
401 flinger->setTransactionFlags(eDisplayTransactionNeeded);
402 }
403 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700404 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700405 : flinger(flinger) {
406 }
407 };
408
409 sp<BBinder> token = new DisplayToken(this);
410
411 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700412 DisplayDeviceState info;
413 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700414 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700415 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700416 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800417 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700418 return token;
419}
420
Jesse Hall6c913be2013-08-08 12:15:49 -0700421void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
422 Mutex::Autolock _l(mStateLock);
423
424 ssize_t idx = mCurrentState.displays.indexOfKey(display);
425 if (idx < 0) {
426 ALOGW("destroyDisplay: invalid display token");
427 return;
428 }
429
430 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700431 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700432 ALOGE("destroyDisplay called for non-virtual display");
433 return;
434 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700435 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700436 mCurrentState.displays.removeItemsAt(idx);
437 setTransactionFlags(eDisplayTransactionNeeded);
438}
439
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700441 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800443 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700444 }
Jesse Hall692c7232012-11-08 15:41:56 -0800445 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446}
447
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448void SurfaceFlinger::bootFinished()
449{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700450 if (mStartPropertySetThread->join() != NO_ERROR) {
451 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800452 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453 const nsecs_t now = systemTime();
454 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000455 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700456
457 // wait patiently for the window manager death
458 const String16 name("window");
459 sp<IBinder> window(defaultServiceManager()->getService(name));
460 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700461 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700462 }
463
Steven Thomas050b2c82017-03-06 11:45:16 -0800464 if (mVrFlinger) {
465 mVrFlinger->OnBootFinished();
466 }
467
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700468 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700469 // formerly we would just kill the process, but we now ask it to exit so it
470 // can choose where to stop the animation.
471 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700472
473 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
474 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
475 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700476
Thierry Strudel2924d012017-08-14 15:19:37 -0700477 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700478 readPersistentProperties();
479 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700480 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800481}
482
Mathias Agopian3f844832013-08-07 21:24:32 -0700483void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700484 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800485 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700486 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700487 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800488 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
489 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700490 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700491 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700492 return true;
493 }
494 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700495 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700496}
497
Lloyd Piquee83f9312018-02-01 12:53:17 -0800498class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700500 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000501 const char* name) :
502 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700504 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000505 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
506 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700507 mDispSync(dispSync),
508 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700509 mVsyncMutex(),
510 mPhaseOffset(phaseOffset),
511 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700512
Lloyd Piquee83f9312018-02-01 12:53:17 -0800513 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514
Lloyd Piquee83f9312018-02-01 12:53:17 -0800515 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700516 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000518 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519 static_cast<DispSync::Callback*>(this));
520 if (err != NO_ERROR) {
521 ALOGE("error registering vsync callback: %s (%d)",
522 strerror(-err), err);
523 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700524 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 } else {
526 status_t err = mDispSync->removeEventListener(
527 static_cast<DispSync::Callback*>(this));
528 if (err != NO_ERROR) {
529 ALOGE("error unregistering vsync callback: %s (%d)",
530 strerror(-err), err);
531 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700532 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 }
536
Lloyd Piquee83f9312018-02-01 12:53:17 -0800537 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539 mCallback = callback;
540 }
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 Mutex::Autolock lock(mVsyncMutex);
544
545 // Normalize phaseOffset to [0, period)
546 auto period = mDispSync->getPeriod();
547 phaseOffset %= period;
548 if (phaseOffset < 0) {
549 // If we're here, then phaseOffset is in (-period, 0). After this
550 // operation, it will be in (0, period)
551 phaseOffset += period;
552 }
553 mPhaseOffset = phaseOffset;
554
555 // If we're not enabled, we don't need to mess with the listeners
556 if (!mEnabled) {
557 return;
558 }
559
Dan Stoza84d619e2018-03-28 17:07:36 -0700560 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
561 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700562 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700563 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700564 strerror(-err), err);
565 }
566 }
567
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568private:
569 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800570 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573 callback = mCallback;
574
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700575 if (mTraceVsync) {
576 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700577 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700578 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 }
580
Peiyong Lin566a3b42018-01-09 18:22:43 -0800581 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 callback->onVSyncEvent(when);
583 }
584 }
585
Tim Murray4a4e4a22016-04-19 16:29:23 +0000586 const char* const mName;
587
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 int mValue;
589
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700590 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700591 const String8 mVsyncOnLabel;
592 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700593
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700595
596 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800597 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700598
599 Mutex mVsyncMutex; // Protects the following
600 nsecs_t mPhaseOffset;
601 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602};
603
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 InjectVSyncSource() = default;
607 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700608
Lloyd Piquee83f9312018-02-01 12:53:17 -0800609 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700610 std::lock_guard<std::mutex> lock(mCallbackMutex);
611 mCallback = callback;
612 }
613
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700615 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700616 if (mCallback) {
617 mCallback->onVSyncEvent(when);
618 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700619 }
620
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621 void setVSyncEnabled(bool) override {}
622 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700623
624private:
625 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800626 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700627};
628
Wei Wangf9b05ee2017-07-19 20:59:39 -0700629// Do not call property_set on main thread which will be blocked by init
630// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700632 ALOGI( "SurfaceFlinger's main thread ready to run. "
633 "Initializing graphics H/W...");
634
Thierry Strudel2924d012017-08-14 15:19:37 -0700635 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900636
Steven Thomasb02664d2017-07-26 18:48:28 -0700637 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800638
Steven Thomasb02664d2017-07-26 18:48:28 -0700639 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800640 mEventThreadSource =
641 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
642 true, "app");
643 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
644 "appEventThread");
645 mSfEventThreadSource =
646 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
647 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800648
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800649 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
650 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800651 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700652 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653
Steven Thomasb02664d2017-07-26 18:48:28 -0700654 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800655 getBE().mRenderEngine =
656 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
657 hasWideColorDisplay
658 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
659 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800660 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700661
662 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
663 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800664 getBE().mHwc.reset(
665 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700666 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800667 // Process any initial hotplug and resulting display changes.
668 processDisplayHotplugEventsLocked();
669 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
670 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800671
Lloyd Piquefcd86612017-12-14 17:15:36 -0800672 // make the default display GLContext current so that we can create textures
673 // when creating Layers (which may happens before we render something)
674 getDefaultDisplayDeviceLocked()->makeCurrent();
675
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (useVrFlinger) {
677 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 // This callback is called from the vr flinger dispatch thread. We
679 // need to call signalTransaction(), which requires holding
680 // mStateLock when we're not on the main thread. Acquiring
681 // mStateLock from the vr flinger dispatch thread might trigger a
682 // deadlock in surface flinger (see b/66916578), so post a message
683 // to be handled on the main thread instead.
684 sp<LambdaMessage> message = new LambdaMessage([=]() {
685 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
686 mVrFlingerRequestsDisplay = requestDisplay;
687 signalTransaction();
688 });
689 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 };
David Sodman105b7dc2017-11-04 20:28:14 -0700691 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
692 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800693 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800694 if (!mVrFlinger) {
695 ALOGE("Failed to start vrflinger");
696 }
697 }
698
Lloyd Pique379adc12018-01-22 17:31:47 -0800699 mEventControlThread = std::make_unique<impl::EventControlThread>(
700 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700701
Mathias Agopian92a979a2012-08-02 18:32:23 -0700702 // initialize our drawing state
703 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700704
Andy McFadden13a082e2012-08-24 10:16:42 -0700705 // set initial conditions (e.g. unblank default device)
706 initializeDisplays();
707
David Sodmanbc815282017-11-05 18:57:52 -0800708 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700709
Wei Wangf9b05ee2017-07-19 20:59:39 -0700710 // Inform native graphics APIs whether the present timestamp is supported:
711 if (getHwComposer().hasCapability(
712 HWC2::Capability::PresentFenceIsNotReliable)) {
713 mStartPropertySetThread = new StartPropertySetThread(false);
714 } else {
715 mStartPropertySetThread = new StartPropertySetThread(true);
716 }
717
718 if (mStartPropertySetThread->Start() != NO_ERROR) {
719 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800722 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
723 Dataspace::SRGB_LINEAR);
724
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700726}
727
Romain Guy11d63f42017-07-20 12:47:14 -0700728void SurfaceFlinger::readPersistentProperties() {
729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
733 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100734
735 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800736 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
737 ALOGV("Display Color Setting is set to %s.",
738 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700739}
740
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Start boot animation service by setting a property mailbox
743 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 if (mStartPropertySetThread->join() != NO_ERROR) {
747 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800752 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800756 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760
Jamie Gennis582270d2011-08-17 18:19:00 -0700761bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800763 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800764 return authenticateSurfaceTextureLocked(bufferProducer);
765}
766
767bool SurfaceFlinger::authenticateSurfaceTextureLocked(
768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800769 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800770 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800771}
772
Brian Anderson6b376712017-04-04 10:51:39 -0700773status_t SurfaceFlinger::getSupportedFrameTimestamps(
774 std::vector<FrameEvent>* outSupported) const {
775 *outSupported = {
776 FrameEvent::REQUESTED_PRESENT,
777 FrameEvent::ACQUIRE,
778 FrameEvent::LATCH,
779 FrameEvent::FIRST_REFRESH_START,
780 FrameEvent::LAST_REFRESH_START,
781 FrameEvent::GPU_COMPOSITION_DONE,
782 FrameEvent::DEQUEUE_READY,
783 FrameEvent::RELEASE,
784 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700787 if (!getHwComposer().hasCapability(
788 HWC2::Capability::PresentFenceIsNotReliable)) {
789 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
790 }
791 return NO_ERROR;
792}
793
Dan Stoza7f7da322014-05-02 15:26:25 -0700794status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
795 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800796 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 return BAD_VALUE;
798 }
799
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500800 if (!display.get())
801 return NAME_NOT_FOUND;
802
Jesse Hall692c7232012-11-08 15:41:56 -0800803 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700804 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800805 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700806 type = i;
807 break;
808 }
809 }
810
811 if (type < 0) {
812 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700813 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 // TODO: Not sure if display density should handled by SF any longer
816 class Density {
817 static int getDensityFromProperty(char const* propName) {
818 char property[PROPERTY_VALUE_MAX];
819 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800820 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 density = atoi(property);
822 }
823 return density;
824 }
825 public:
826 static int getEmuDensity() {
827 return getDensityFromProperty("qemu.sf.lcd_density"); }
828 static int getBuildDensity() {
829 return getDensityFromProperty("ro.sf.lcd_density"); }
830 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Steven Thomas6d8110b2017-08-31 18:24:21 -0700834 ConditionalLock _l(mStateLock,
835 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 DisplayInfo info = DisplayInfo();
838
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 float xdpi = hwConfig->getDpiX();
840 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700841
842 if (type == DisplayDevice::DISPLAY_PRIMARY) {
843 // The density of the device is provided by a build property
844 float density = Density::getBuildDensity() / 160.0f;
845 if (density == 0) {
846 // the build doesn't provide a density -- this is wrong!
847 // use xdpi instead
848 ALOGE("ro.sf.lcd_density must be defined as a build property");
849 density = xdpi / 160.0f;
850 }
851 if (Density::getEmuDensity()) {
852 // if "qemu.sf.lcd_density" is specified, it overrides everything
853 xdpi = ydpi = density = Density::getEmuDensity();
854 density /= 160.0f;
855 }
856 info.density = density;
857
858 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700859 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800860 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 } else {
862 // TODO: where should this value come from?
863 static const int TV_DENSITY = 213;
864 info.density = TV_DENSITY / 160.0f;
865 info.orientation = 0;
866 }
867
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868 info.w = hwConfig->getWidth();
869 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 info.xdpi = xdpi;
871 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900873 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874
Andy McFadden91b2ca82014-06-13 14:04:23 -0700875 // This is how far in advance a buffer must be queued for
876 // presentation at a given time. If you want a buffer to appear
877 // on the screen at time N, you must submit the buffer before
878 // (N - presentationDeadline).
879 //
880 // Normally it's one full refresh period (to give SF a chance to
881 // latch the buffer), but this can be reduced by configuring a
882 // DispSync offset. Any additional delays introduced by the hardware
883 // composer or panel must be accounted for here.
884 //
885 // We add an additional 1ms to allow for processing time and
886 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800888 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700889
890 // All non-virtual displays are currently considered secure.
891 info.secure = true;
892
Michael Wright28f24d02016-07-12 13:30:53 -0700893 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700894 }
895
Dan Stoza7f7da322014-05-02 15:26:25 -0700896 return NO_ERROR;
897}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700898
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800899status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700900 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800901 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700902 return BAD_VALUE;
903 }
904
905 // FIXME for now we always return stats for the primary display
906 memset(stats, 0, sizeof(*stats));
907 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
908 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
909 return NO_ERROR;
910}
911
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700912int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800913 if (display == nullptr) {
914 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800915 return BAD_VALUE;
916 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700917
918 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800919 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700920 return device->getActiveConfig();
921 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700922
Dan Stoza24a42e92015-03-09 10:04:11 -0700923 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700926void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
927 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
928 this);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700929 int currentMode = hw->getActiveConfig();
930
931 if (mode == currentMode) {
932 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
933 return;
934 }
935
Dominik Laskowski281644e2018-04-19 15:47:35 -0700936 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 ALOGW("Trying to set config for virtual display");
938 return;
939 }
940
941 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700942 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
946 class MessageSetActiveConfig: public MessageBase {
947 SurfaceFlinger& mFlinger;
948 sp<IBinder> mDisplay;
949 int mMode;
950 public:
951 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
952 int mode) :
953 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
954 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700955 Vector<DisplayInfo> configs;
956 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700957 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700958 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700959 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700960 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700961 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800963 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700966 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 ALOGW("Attempt to set active config = %d for virtual display",
968 mMode);
969 } else {
970 mFlinger.setActiveConfigInternal(hw, mMode);
971 }
972 return true;
973 }
974 };
975 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
976 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700977 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978}
Michael Wright28f24d02016-07-12 13:30:53 -0700979status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
982 return BAD_VALUE;
983 }
984
985 if (!display.get()) {
986 return NAME_NOT_FOUND;
987 }
988
989 int32_t type = NAME_NOT_FOUND;
990 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
991 if (display == mBuiltinDisplays[i]) {
992 type = i;
993 break;
994 }
995 }
996
997 if (type < 0) {
998 return type;
999 }
1000
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 {
1003 ConditionalLock _l(mStateLock,
1004 std::this_thread::get_id() != mMainThreadId);
1005 modes = getHwComposer().getColorModes(type);
1006 }
Michael Wright28f24d02016-07-12 13:30:53 -07001007 outColorModes->clear();
1008 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1009
1010 return NO_ERROR;
1011}
1012
Peiyong Lina52f0292018-03-14 17:26:31 -07001013ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001015 if (device != nullptr) {
1016 return device->getActiveColorMode();
1017 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
1021void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001022 ColorMode mode, Dataspace dataSpace) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001023 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001024 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001025 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001026
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001027 // Natural Mode means it's color managed and the color must be right,
1028 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1029 // Native Mode means the display is not color managed, and whichever
1030 // render intent is picked doesn't matter, thus return
1031 // RenderIntent::COLORIMETRIC as default here.
1032 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1033
1034 // In Auto Color Mode, we want to strech to panel color space, right now
1035 // only the built-in display supports it.
Dominik Laskowski281644e2018-04-19 15:47:35 -07001036 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED && mBuiltinDisplaySupportsEnhance &&
1037 hw->isPrimary()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001038 renderIntent = RenderIntent::ENHANCE;
1039 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001040
1041 if (mode == currentMode && dataSpace == currentDataSpace &&
1042 renderIntent == currentRenderIntent) {
1043 return;
1044 }
1045
Dominik Laskowski281644e2018-04-19 15:47:35 -07001046 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001047 ALOGW("Trying to set config for virtual display");
1048 return;
1049 }
1050
1051 hw->setActiveColorMode(mode);
1052 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001053 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001054 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001055
1056 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1057 decodeColorMode(mode).c_str(), mode,
1058 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1059 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001060}
1061
1062
1063status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001064 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001065 class MessageSetActiveColorMode: public MessageBase {
1066 SurfaceFlinger& mFlinger;
1067 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 public:
1070 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001071 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001072 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1073 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001075 mFlinger.getDisplayColorModes(mDisplay, &modes);
1076 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001078 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1079 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001080 return true;
1081 }
1082 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1083 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001084 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1085 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001086 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001087 ALOGW("Attempt to set active color mode %s %d for virtual display",
1088 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001089 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001090 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 }
1092 return true;
1093 }
1094 };
1095 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1096 postMessageSync(msg);
1097 return NO_ERROR;
1098}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001099
Svetoslavd85084b2014-03-20 10:28:31 -07001100status_t SurfaceFlinger::clearAnimationFrameStats() {
1101 Mutex::Autolock _l(mStateLock);
1102 mAnimFrameTracker.clearStats();
1103 return NO_ERROR;
1104}
1105
1106status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1107 Mutex::Autolock _l(mStateLock);
1108 mAnimFrameTracker.getStats(outStats);
1109 return NO_ERROR;
1110}
1111
Dan Stozac4f471e2016-03-24 09:31:08 -07001112status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1113 HdrCapabilities* outCapabilities) const {
1114 Mutex::Autolock _l(mStateLock);
1115
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001116 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001117 if (displayDevice == nullptr) {
1118 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1119 return BAD_VALUE;
1120 }
1121
Peiyong Lin62665892018-04-16 11:07:44 -07001122 HdrCapabilities capabilities;
1123 int status = getBE().mHwc->getHdrCapabilities(
1124 displayDevice->getHwcDisplayId(), &capabilities);
1125 if (status == NO_ERROR) {
Peiyong Linf59a7192018-04-25 11:19:31 -07001126 if (displayDevice->hasWideColorGamut()) {
Peiyong Lin62665892018-04-16 11:07:44 -07001127 std::vector<Hdr> types = capabilities.getSupportedHdrTypes();
Peiyong Linf59a7192018-04-25 11:19:31 -07001128 // insert HDR10/HLG as we will force client composition for HDR10/HLG
1129 // layers
1130 if (!displayDevice->hasHDR10Support()) {
1131 types.push_back(Hdr::HDR10);
1132 }
1133 if (!displayDevice->hasHLGSupport()) {
1134 types.push_back(Hdr::HLG);
1135 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001136
1137 *outCapabilities = HdrCapabilities(types,
Peiyong Lin62665892018-04-16 11:07:44 -07001138 capabilities.getDesiredMaxLuminance(),
1139 capabilities.getDesiredMaxAverageLuminance(),
1140 capabilities.getDesiredMinLuminance());
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001141 } else {
Peiyong Lin62665892018-04-16 11:07:44 -07001142 *outCapabilities = std::move(capabilities);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001143 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001144 } else {
1145 return BAD_VALUE;
1146 }
1147
1148 return NO_ERROR;
1149}
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1153 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 if (mInjectVSyncs == enable) {
1156 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001157 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158
1159 if (enable) {
1160 ALOGV("VSync Injections enabled");
1161 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001162 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001163 mInjectorEventThread =
1164 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1165 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001167 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 } else {
1169 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001170 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001171 }
1172
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001173 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 });
1175 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176 return NO_ERROR;
1177}
1178
1179status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 Mutex::Autolock _l(mStateLock);
1181
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182 if (!mInjectVSyncs) {
1183 ALOGE("VSync Injections not enabled");
1184 return BAD_VALUE;
1185 }
1186 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1187 ALOGV("Injecting VSync inside SurfaceFlinger");
1188 mVSyncInjector->onInjectSyncEvent(when);
1189 }
1190 return NO_ERROR;
1191}
1192
Lloyd Pique755e3192018-01-31 16:46:15 -08001193status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1194 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001195 IPCThreadState* ipc = IPCThreadState::self();
1196 const int pid = ipc->getCallingPid();
1197 const int uid = ipc->getCallingUid();
1198 if ((uid != AID_SHELL) &&
1199 !PermissionCache::checkPermission(sDump, pid, uid)) {
1200 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1201 return PERMISSION_DENIED;
1202 }
1203
1204 // Try to acquire a lock for 1s, fail gracefully
1205 const status_t err = mStateLock.timedLock(s2ns(1));
1206 const bool locked = (err == NO_ERROR);
1207 if (!locked) {
1208 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1209 return TIMED_OUT;
1210 }
1211
1212 outLayers->clear();
1213 mCurrentState.traverseInZOrder([&](Layer* layer) {
1214 outLayers->push_back(layer->getLayerDebugInfo());
1215 });
1216
1217 mStateLock.unlock();
1218 return NO_ERROR;
1219}
1220
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001221// ----------------------------------------------------------------------------
1222
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001223sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1224 ISurfaceComposer::VsyncSource vsyncSource) {
1225 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1226 return mSFEventThread->createEventConnection();
1227 } else {
1228 return mEventThread->createEventConnection();
1229 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001230}
1231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001232// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001233
1234void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001235 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001236}
1237
1238void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001239 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001240}
1241
1242void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001243 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244}
1245
1246void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001247 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001248 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249}
1250
1251status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001252 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001253 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001254}
1255
1256status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001257 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001258 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259 if (res == NO_ERROR) {
1260 msg->wait();
1261 }
1262 return res;
1263}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001264
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001265void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001266 do {
1267 waitForEvent();
1268 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001269}
1270
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271void SurfaceFlinger::enableHardwareVsync() {
1272 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001275 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1276 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001278 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279}
1280
Jesse Hall948fe0c2013-10-14 12:56:09 -07001281void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 Mutex::Autolock _l(mHWVsyncLock);
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 if (makeAvailable) {
1285 mHWVsyncAvailable = true;
1286 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001287 // Hardware vsync is not currently available, so abort the resync
1288 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001289 return;
1290 }
1291
David Sodman105b7dc2017-11-04 20:28:14 -07001292 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001293 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294
1295 mPrimaryDispSync.reset();
1296 mPrimaryDispSync.setPeriod(period);
1297
1298 if (!mPrimaryHWVsyncEnabled) {
1299 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001300 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1301 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302 mPrimaryHWVsyncEnabled = true;
1303 }
1304}
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 Mutex::Autolock _l(mHWVsyncLock);
1308 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001309 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1310 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 mPrimaryDispSync.endResync();
1312 mPrimaryHWVsyncEnabled = false;
1313 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001314 if (makeUnavailable) {
1315 mHWVsyncAvailable = false;
1316 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317}
1318
Tim Murray4a4e4a22016-04-19 16:29:23 +00001319void SurfaceFlinger::resyncWithRateLimit() {
1320 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001321
1322 // No explicit locking is needed here since EventThread holds a lock while calling this method
1323 static nsecs_t sLastResyncAttempted = 0;
1324 const nsecs_t now = systemTime();
1325 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001326 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001327 }
Dan Stoza57164302017-05-08 14:03:54 -07001328 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001329}
1330
Steven Thomasb02664d2017-07-26 18:48:28 -07001331void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1332 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001333 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001335 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001336 return;
1337 }
1338
1339 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001340 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001341 return;
1342 }
1343
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345
Jamie Gennisd1700752013-10-14 12:22:52 -07001346 { // Scope for the lock
1347 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001349 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001350 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001351 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001352
1353 if (needsHwVsync) {
1354 enableHardwareVsync();
1355 } else {
1356 disableHardwareVsync(false);
1357 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001358}
1359
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001360void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001361 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1362 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001363}
1364
Lloyd Pique715a2c12017-12-14 17:18:08 -08001365void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1366 HWC2::Connection connection) {
1367 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1368 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
Lloyd Piqueba04e622017-12-14 17:11:26 -08001370 // Ignore events that do not have the right sequenceId.
1371 if (sequenceId != getBE().mComposerSequenceId) {
1372 return;
1373 }
1374
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 // Only lock if we're not on the main thread. This function is normally
1376 // called on a hwbinder thread, but for the primary display it's called on
1377 // the main thread with the state lock already held, so don't attempt to
1378 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001379 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001380
Lloyd Pique715a2c12017-12-14 17:18:08 -08001381 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001382
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001383 if (std::this_thread::get_id() == mMainThreadId) {
1384 // Process all pending hot plug events immediately if we are on the main thread.
1385 processDisplayHotplugEventsLocked();
1386 }
1387
Lloyd Piqueba04e622017-12-14 17:11:26 -08001388 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001389}
1390
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::onRefreshReceived(int sequenceId,
1392 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001393 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001396 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001397 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001398}
1399
Dan Stoza9e56aa02015-11-02 13:00:03 -08001400void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001403 getHwComposer().setVsyncEnabled(disp,
1404 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001405}
1406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001408void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410 // Clear the drawing state so that the logic inside of
1411 // handleTransactionLocked will fire. It will determine the delta between
1412 // mCurrentState and mDrawingState and re-apply all changes when we make the
1413 // transition.
1414 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001415 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416 mDisplays.clear();
1417}
1418
Steven Thomas050b2c82017-03-06 11:45:16 -08001419void SurfaceFlinger::updateVrFlinger() {
1420 if (!mVrFlinger)
1421 return;
1422 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001423 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001424 return;
1425 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
David Sodman105b7dc2017-11-04 20:28:14 -07001427 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 ALOGE("Vr flinger is only supported for remote hardware composer"
1429 " service connections. Ignoring request to transition to vr"
1430 " flinger.");
1431 mVrFlingerRequestsDisplay = false;
1432 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001433 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 int currentDisplayPowerMode = getDisplayDeviceLocked(
1438 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001445 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001446 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1447 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001448 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449
David Sodman105b7dc2017-11-04 20:28:14 -07001450 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1451 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001452
1453 if (vrFlingerRequestsDisplay) {
1454 mVrFlinger->GrantDisplayOwnership();
1455 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
1459 mVisibleRegionsDirty = true;
1460 invalidateHwcGeometry();
1461
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1464 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1465 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001468 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 const nsecs_t period = activeConfig->getVsyncPeriod();
1470 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001471
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 // Use phase of 0 since phase is not known.
1473 // Use latency of 0, which will snap to the ideal latency.
1474 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001475
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001476 android_atomic_or(1, &mRepaintEverything);
1477 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478}
1479
Mathias Agopian4fec8732012-06-29 14:12:52 -07001480void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001481 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001482 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001484 bool frameMissed = !mHadClientComposition &&
1485 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001486 (mPreviousPresentFence->getSignalTime() ==
1487 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001488 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001489 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001490 signalLayerUpdate();
1491 break;
1492 }
1493
Steven Thomas050b2c82017-03-06 11:45:16 -08001494 // Now that we're going to make it to the handleMessageTransaction()
1495 // call below it's safe to call updateVrFlinger(), which will
1496 // potentially trigger a display handoff.
1497 updateVrFlinger();
1498
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 bool refreshNeeded = handleMessageTransaction();
1500 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001501 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001503 // Signal a refresh if a transaction modified the window state,
1504 // a new buffer was latched, or if HWC has requested a full
1505 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 signalRefresh();
1507 }
1508 break;
1509 }
1510 case MessageQueue::REFRESH: {
1511 handleMessageRefresh();
1512 break;
1513 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001514 }
1515}
1516
Dan Stoza6b9454d2014-11-07 16:00:59 -08001517bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001518 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001520 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524}
1525
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
1531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
Chia-I Wu30505fb2018-03-26 16:20:31 -07001536 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001537
Chia-I Wu30505fb2018-03-26 16:20:31 -07001538 preComposition(refreshStartTime);
1539 rebuildLayerStacks();
1540 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001541 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001542 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001543 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001544 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001545 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001546
David Sodman105b7dc2017-11-04 20:28:14 -07001547 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001548
1549 mHadClientComposition = false;
1550 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1551 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1552 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001553 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001554 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001555 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001556
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001559
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560void SurfaceFlinger::doDebugFlashRegions()
1561{
1562 // is debugging enabled
1563 if (CC_LIKELY(!mDebugRegion))
1564 return;
1565
1566 const bool repaintEverything = mRepaintEverything;
1567 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1568 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001569 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 // transform the dirty region into this screen's coordinate space
1571 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1572 if (!dirtyRegion.isEmpty()) {
1573 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001574 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575
1576 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001578 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001579 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1580
Mathias Agopianda27af92012-09-13 18:17:13 -07001581 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 }
1583 }
1584 }
1585
1586 postFramebuffer();
1587
1588 if (mDebugRegion > 1) {
1589 usleep(mDebugRegion * 1000);
1590 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001591
Dan Stoza9e56aa02015-11-02 13:00:03 -08001592 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001593 auto& displayDevice = mDisplays[displayId];
1594 if (!displayDevice->isDisplayOn()) {
1595 continue;
1596 }
1597
David Sodman105b7dc2017-11-04 20:28:14 -07001598 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1599 ALOGE_IF(result != NO_ERROR,
1600 "prepareFrame for display %zd failed:"
1601 " %d (%s)",
1602 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001603 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604}
1605
Adrian Roos1e1a1282017-11-01 19:05:31 +01001606void SurfaceFlinger::doTracing(const char* where) {
1607 ATRACE_CALL();
1608 ATRACE_NAME(where);
1609 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001610 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001611 }
1612}
1613
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001614void SurfaceFlinger::logLayerStats() {
1615 ATRACE_CALL();
1616 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1617 int32_t hwcId = -1;
1618 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1619 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1620 if (displayDevice->isPrimary()) {
1621 hwcId = displayDevice->getHwcDisplayId();
1622 break;
1623 }
1624 }
1625 if (hwcId < 0) {
1626 ALOGE("LayerStats: Hmmm, no primary display?");
1627 return;
1628 }
1629 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1630 }
1631}
1632
Chia-I Wu30505fb2018-03-26 16:20:31 -07001633void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001635 ATRACE_CALL();
1636 ALOGV("preComposition");
1637
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001639 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001640 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641 needExtraInvalidate = true;
1642 }
Robert Carr2047fae2016-11-28 14:09:09 -08001643 });
1644
Mathias Agopiancd60f992012-08-16 16:28:27 -07001645 if (needExtraInvalidate) {
1646 signalLayerUpdate();
1647 }
1648}
1649
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650void SurfaceFlinger::updateCompositorTiming(
1651 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1652 std::shared_ptr<FenceTime>& presentFenceTime) {
1653 // Update queue of past composite+present times and determine the
1654 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001655 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001657 while (!getBE().mCompositePresentTimes.empty()) {
1658 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 // Cached values should have been updated before calling this method,
1660 // which helps avoid duplicate syscalls.
1661 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1662 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1663 break;
1664 }
1665 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001666 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 }
1668
1669 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001670 while (getBE().mCompositePresentTimes.size() > 16) {
1671 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 }
1673
Brian Andersond0010582017-03-07 13:20:31 -08001674 setCompositorTimingSnapped(
1675 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1676}
1677
1678void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1679 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 // Integer division and modulo round toward 0 not -inf, so we need to
1681 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001682 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1684 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1685
Brian Andersond0010582017-03-07 13:20:31 -08001686 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1687 if (idealLatency <= 0) {
1688 idealLatency = vsyncInterval;
1689 }
1690
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691 // Snap the latency to a value that removes scheduling jitter from the
1692 // composition and present times, which often have >1ms of jitter.
1693 // Reducing jitter is important if an app attempts to extrapolate
1694 // something (such as user input) to an accurate diasplay time.
1695 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1696 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001697 nsecs_t bias = vsyncInterval / 2;
1698 int64_t extraVsyncs =
1699 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1700 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1701 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702
David Sodman99974d22017-11-28 12:04:33 -08001703 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1704 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1705 getBE().mCompositorTiming.interval = vsyncInterval;
1706 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001707}
1708
Chia-I Wu30505fb2018-03-26 16:20:31 -07001709void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001711 ATRACE_CALL();
1712 ALOGV("postComposition");
1713
Brian Anderson3546a3f2016-07-14 11:51:14 -07001714 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001715 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001716 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001717 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001718 }
1719
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720 // |mStateLock| not needed as we are on the main thread
1721 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001725 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 glCompositionDoneFenceTime =
1727 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001728 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729 } else {
1730 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1731 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001732
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001734 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001735 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001736 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001737
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1739 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1740
Chia-I Wu30505fb2018-03-26 16:20:31 -07001741 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001742 // when we started doing work for this frame, but that should be okay
1743 // since updateCompositorTiming has snapping logic.
1744 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001745 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001746 CompositorTiming compositorTiming;
1747 {
David Sodman99974d22017-11-28 12:04:33 -08001748 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1749 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001750 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001751
Robert Carr2047fae2016-11-28 14:09:09 -08001752 mDrawingState.traverseInZOrder([&](Layer* layer) {
1753 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001754 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001755 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001756 recordBufferingStats(layer->getName().string(),
1757 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001758 }
Robert Carr2047fae2016-11-28 14:09:09 -08001759 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001760
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001761 if (presentFenceTime->isValid()) {
1762 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001763 enableHardwareVsync();
1764 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001765 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001766 }
1767 }
1768
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001769 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001770 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001771 enableHardwareVsync();
1772 }
1773 }
1774
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775 if (mAnimCompositionPending) {
1776 mAnimCompositionPending = false;
1777
Brian Anderson4e606e32017-03-16 15:34:57 -07001778 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001779 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001780 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001781 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001782 // The HWC doesn't support present fences, so use the refresh
1783 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001785 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001786 mAnimFrameTracker.setActualPresentTime(presentTime);
1787 }
1788 mAnimFrameTracker.advanceFrame();
1789 }
Dan Stozab90cf072015-03-05 11:05:59 -08001790
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001791 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1792 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001793 return;
1794 }
1795
1796 nsecs_t currentTime = systemTime();
1797 if (mHasPoweredOff) {
1798 mHasPoweredOff = false;
1799 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001800 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001802 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1803 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001804 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001805 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 }
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 }
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810}
1811
1812void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001813 ATRACE_CALL();
1814 ALOGV("rebuildLayerStacks");
1815
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001818 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 mVisibleRegionsDirty = false;
1820 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1823 Region opaqueRegion;
1824 Region dirtyRegion;
1825 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001826 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1828 const Transform& tr(displayDevice->getTransform());
1829 const Rect bounds(displayDevice->getBounds());
1830 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001831 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001832
Jeff Sharkey76488112017-02-27 14:15:18 -07001833 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001834 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001835 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1836 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 Region drawRegion(tr.transform(
1838 layer->visibleNonTransparentRegion));
1839 drawRegion.andSelf(bounds);
1840 if (!drawRegion.isEmpty()) {
1841 layersSortedByZ.add(layer);
1842 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001843 // Clear out the HWC layer if this layer was
1844 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001845 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001846 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001848 } else {
1849 // WM changes displayDevice->layerStack upon sleep/awake.
1850 // Here we make sure we delete the HWC layers even if
1851 // WM changed their layer stack.
1852 hwcLayerDestroyed = layer->destroyHwcLayer(
1853 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001854 }
1855
1856 // If a layer is not going to get a release fence because
1857 // it is invisible, but it is also going to release its
1858 // old buffer, add it to the list of layers needing
1859 // fences.
1860 if (hwcLayerDestroyed) {
1861 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1862 mLayersWithQueuedFrames.cend(), layer);
1863 if (found != mLayersWithQueuedFrames.cend()) {
1864 layersNeedingFences.add(layer);
1865 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 });
1868 }
1869 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001870 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 displayDevice->undefinedRegion.set(bounds);
1872 displayDevice->undefinedRegion.subtractSelf(
1873 tr.transform(opaqueRegion));
1874 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001875 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001876 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001878
Romain Guy0147a172017-06-01 13:53:56 -07001879mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001881 return mat4();
1882 }
1883
1884 // Rec.709 luma coefficients
1885 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001887 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001888 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1889 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1890 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001891 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1892 );
1893}
1894
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895// Returns a dataspace that fits all visible layers. The returned dataspace
1896// can only be one of
1897//
1898// - Dataspace::V0_SRGB
1899// - Dataspace::DISPLAY_P3
1900// - Dataspace::V0_SCRGB_LINEAR
1901// TODO(b/73825729) Add BT2020 data space.
1902ui::Dataspace SurfaceFlinger::getBestDataspace(
1903 const sp<const DisplayDevice>& displayDevice) const {
1904 Dataspace bestDataspace = Dataspace::V0_SRGB;
1905 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 switch (layer->getDataSpace()) {
1907 case Dataspace::V0_SCRGB:
1908 case Dataspace::V0_SCRGB_LINEAR:
1909 // return immediately
1910 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001911 case Dataspace::DISPLAY_P3:
1912 bestDataspace = Dataspace::DISPLAY_P3;
1913 break;
1914 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1915 // since SurfaceFlinger simulates HDR support now, it should honor
1916 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917 case Dataspace::BT2020_PQ:
1918 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001919 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 return Dataspace::V0_SCRGB_LINEAR;
1921 }
1922 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001923 case Dataspace::BT2020_HLG:
1924 case Dataspace::BT2020_ITU_HLG:
1925 if (!displayDevice->hasHLGSupport()) {
1926 return Dataspace::V0_SCRGB_LINEAR;
1927 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928 break;
1929 default:
1930 break;
1931 }
Romain Guy54f154a2017-10-24 21:40:32 +01001932 }
1933
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001935}
1936
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937// Pick the ColorMode / Dataspace for the display device.
1938// TODO(b/73825729) Add BT2020 color mode.
1939void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1940 ColorMode* outMode, Dataspace* outDataSpace) const {
1941 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1942 *outMode = ColorMode::NATIVE;
1943 *outDataSpace = Dataspace::UNKNOWN;
1944 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001945 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001946
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001947 switch (getBestDataspace(displayDevice)) {
1948 case Dataspace::DISPLAY_P3:
1949 case Dataspace::V0_SCRGB_LINEAR:
1950 *outMode = ColorMode::DISPLAY_P3;
1951 *outDataSpace = Dataspace::DISPLAY_P3;
1952 break;
1953 default:
1954 *outMode = ColorMode::SRGB;
1955 *outDataSpace = Dataspace::V0_SRGB;
1956 break;
1957 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001958}
1959
Chia-I Wu30505fb2018-03-26 16:20:31 -07001960void SurfaceFlinger::setUpHWComposer() {
1961 ATRACE_CALL();
1962 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963
Jesse Hall028dc8f2013-08-20 16:35:32 -07001964 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001965 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001966 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1967 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1968
1969 // If nothing has changed (!dirty), don't recompose.
1970 // If something changed, but we don't currently have any visible layers,
1971 // and didn't when we last did a composition, then skip it this time.
1972 // The second rule does two things:
1973 // - When all layers are removed from a display, we'll emit one black
1974 // frame, then nothing more until we get new layers.
1975 // - When a display is created with a private layer stack, we won't
1976 // emit any black frames until a layer is added to the layer stack.
1977 bool mustRecompose = dirty && !(empty && wasEmpty);
1978
Dominik Laskowski281644e2018-04-19 15:47:35 -07001979 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001980 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1981 mustRecompose ? "doing" : "skipping",
1982 dirty ? "+" : "-",
1983 empty ? "+" : "-",
1984 wasEmpty ? "+" : "-");
1985
Dan Stoza71433162014-02-04 16:22:36 -08001986 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001987
1988 if (mustRecompose) {
1989 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1990 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001991 }
1992
Chia-I Wu30505fb2018-03-26 16:20:31 -07001993 // build the h/w work list
1994 if (CC_UNLIKELY(mGeometryInvalid)) {
1995 mGeometryInvalid = false;
1996 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1997 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1998 const auto hwcId = displayDevice->getHwcDisplayId();
1999 if (hwcId >= 0) {
2000 const Vector<sp<Layer>>& currentLayers(
2001 displayDevice->getVisibleLayersSortedByZ());
2002 for (size_t i = 0; i < currentLayers.size(); i++) {
2003 const auto& layer = currentLayers[i];
2004 if (!layer->hasHwcLayer(hwcId)) {
2005 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
2006 layer->forceClientComposition(hwcId);
2007 continue;
2008 }
2009 }
2010
2011 layer->setGeometry(displayDevice, i);
2012 if (mDebugDisableHWC || mDebugRegion) {
2013 layer->forceClientComposition(hwcId);
2014 }
2015 }
2016 }
2017 }
2018 }
2019
2020
2021 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
2022
2023 // Set the per-frame data
2024 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2025 auto& displayDevice = mDisplays[displayId];
2026 const auto hwcId = displayDevice->getHwcDisplayId();
2027
2028 if (hwcId < 0) {
2029 continue;
2030 }
2031 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08002032 displayDevice->setColorTransform(colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002033 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
2034 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2035 "display %zd: %d", displayId, result);
2036 }
2037 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002038 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2039 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002040 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002041 layer->forceClientComposition(hwcId);
2042 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002043 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2044 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2045 !displayDevice->hasHLGSupport()) {
2046 layer->forceClientComposition(hwcId);
2047 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002048
2049 if (layer->getForceClientComposition(hwcId)) {
2050 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2051 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2052 continue;
2053 }
2054
2055 layer->setPerFrameData(displayDevice);
2056 }
2057
2058 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002059 ColorMode colorMode;
2060 Dataspace dataSpace;
2061 pickColorMode(displayDevice, &colorMode, &dataSpace);
2062 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002063 }
2064 }
2065
2066 mPreviousColorMatrix = colorMatrix;
2067
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002069 auto& displayDevice = mDisplays[displayId];
2070 if (!displayDevice->isDisplayOn()) {
2071 continue;
2072 }
2073
David Sodman105b7dc2017-11-04 20:28:14 -07002074 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2076 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002077 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002078}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002079
Mathias Agopiancd60f992012-08-16 16:28:27 -07002080void SurfaceFlinger::doComposition() {
2081 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 ALOGV("doComposition");
2083
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002084 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002085 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002086 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002087 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002088 // transform the dirty region into this screen's coordinate space
2089 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002090
2091 // repaint the framebuffer (if needed)
2092 doDisplayComposition(hw, dirtyRegion);
2093
Mathias Agopiancd60f992012-08-16 16:28:27 -07002094 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002095 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002096 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002098 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002099}
2100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101void SurfaceFlinger::postFramebuffer()
2102{
Mathias Agopian841cde52012-03-01 15:44:37 -08002103 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002105
Mathias Agopiana44b0412011-10-16 18:46:35 -07002106 const nsecs_t now = systemTime();
2107 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002108
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2110 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002111 if (!displayDevice->isDisplayOn()) {
2112 continue;
2113 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 const auto hwcId = displayDevice->getHwcDisplayId();
2115 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002116 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002117 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002118 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002119 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002121 // The layer buffer from the previous frame (if any) is released
2122 // by HWC only when the release fence from this frame (if any) is
2123 // signaled. Always get the release fence from HWC first.
2124 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002125 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002126
2127 // If the layer was client composited in the previous frame, we
2128 // need to merge with the previous client target acquire fence.
2129 // Since we do not track that, always merge with the current
2130 // client target acquire fence when it is available, even though
2131 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002133 releaseFence = Fence::merge("LayerRelease", releaseFence,
2134 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002135 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002136
David Sodmanb8af7922017-12-21 15:17:55 -08002137 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 }
Chia-I Wu83806892017-11-16 10:50:20 -08002139
2140 // We've got a list of layers needing fences, that are disjoint with
2141 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2142 // supply them with the present fence.
2143 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002144 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002145 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002146 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002147 }
2148 }
2149
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002151 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002152 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002153 }
2154
Mathias Agopiana44b0412011-10-16 18:46:35 -07002155 mLastSwapBufferTime = systemTime() - now;
2156 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002157
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002158 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002159 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2160 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2161 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2162 logFrameStats();
2163 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002164 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165}
2166
Mathias Agopian87baae12012-07-31 12:38:26 -07002167void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002168{
Mathias Agopian841cde52012-03-01 15:44:37 -08002169 ATRACE_CALL();
2170
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002171 // here we keep a copy of the drawing state (that is the state that's
2172 // going to be overwritten by handleTransactionLocked()) outside of
2173 // mStateLock so that the side-effects of the State assignment
2174 // don't happen with mStateLock held (which can cause deadlocks).
2175 State drawingState(mDrawingState);
2176
Mathias Agopianca4d3602011-05-19 15:38:14 -07002177 Mutex::Autolock _l(mStateLock);
2178 const nsecs_t now = systemTime();
2179 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180
Mathias Agopianca4d3602011-05-19 15:38:14 -07002181 // Here we're guaranteed that some transaction flags are set
2182 // so we can call handleTransactionLocked() unconditionally.
2183 // We call getTransactionFlags(), which will also clear the flags,
2184 // with mStateLock held to guarantee that mCurrentState won't change
2185 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002186
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002187 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002188 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002189 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002190
Mathias Agopianca4d3602011-05-19 15:38:14 -07002191 mLastTransactionTime = systemTime() - now;
2192 mDebugInTransaction = 0;
2193 invalidateHwcGeometry();
2194 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002195}
2196
Lloyd Pique715a2c12017-12-14 17:18:08 -08002197DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002198 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002199 // Figure out whether the event is for the primary display or an
2200 // external display by matching the Hwc display id against one for a
2201 // connected display. If we did not find a match, we then check what
2202 // displays are not already connected to determine the type. If we don't
2203 // have a connected primary display, we assume the new display is meant to
2204 // be the primary display, and then if we don't have an external display,
2205 // we assume it is that.
2206 const auto primaryDisplayId =
2207 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2208 const auto externalDisplayId =
2209 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2210 if (primaryDisplayId && primaryDisplayId == display) {
2211 return DisplayDevice::DISPLAY_PRIMARY;
2212 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002213 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002214 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2215 return DisplayDevice::DISPLAY_PRIMARY;
2216 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2217 return DisplayDevice::DISPLAY_EXTERNAL;
2218 }
2219
2220 return DisplayDevice::DISPLAY_ID_INVALID;
2221}
2222
Lloyd Piqueba04e622017-12-14 17:11:26 -08002223void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2224 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002225 auto displayType = determineDisplayType(event.display, event.connection);
2226 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2227 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2228 continue;
2229 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002230
2231 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2232 ALOGE("External displays are not supported by the vr hardware composer.");
2233 continue;
2234 }
2235
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002236 const auto displayId =
2237 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2238 if (displayId) {
2239 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2240 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002241
2242 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002243 if (!mBuiltinDisplays[displayType].get()) {
2244 ALOGV("Creating built in display %d", displayType);
2245 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002246 DisplayDeviceState info;
2247 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002248 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2249 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002250 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002251 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2252 mInterceptor->saveDisplayCreation(info);
2253 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002254 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002255 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002256
Lloyd Piquefcd86612017-12-14 17:15:36 -08002257 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2258 if (idx >= 0) {
2259 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002260 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002261 mCurrentState.displays.removeItemsAt(idx);
2262 }
2263 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002264 }
2265
2266 processDisplayChangesLocked();
2267 }
2268
2269 mPendingHotplugEvents.clear();
2270}
2271
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2273 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2274 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002275 bool hasWideColorGamut = false;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 for (ColorMode colorMode : modes) {
2279 switch (colorMode) {
2280 case ColorMode::DISPLAY_P3:
2281 case ColorMode::ADOBE_RGB:
2282 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 default:
2287 break;
2288 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289
2290 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2291 colorMode);
2292 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2293 for (auto intent : renderIntents) {
2294 if (intent == RenderIntent::ENHANCE) {
2295 mBuiltinDisplaySupportsEnhance = true;
2296 break;
2297 }
2298 }
2299 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300 }
2301 }
2302
Peiyong Lin62665892018-04-16 11:07:44 -07002303 HdrCapabilities hdrCapabilities;
2304 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305
2306 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2307 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2308
2309 /*
2310 * Create our display's surface
2311 */
2312 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2313 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002314 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 renderSurface->setNativeWindow(nativeWindow.get());
2316 const int displayWidth = renderSurface->queryWidth();
2317 const int displayHeight = renderSurface->queryHeight();
2318
2319 // Make sure that composition can never be stalled by a virtual display
2320 // consumer that isn't processing buffers fast enough. We have to do this
2321 // in two places:
2322 // * Here, in case the display is composed entirely by HWC.
2323 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2324 // window's swap interval in eglMakeCurrent, so they'll override the
2325 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002326 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2328 }
2329
2330 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002331 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
2333 sp<DisplayDevice> hw =
2334 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2335 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002336 hasWideColorGamut, hdrCapabilities,
2337 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2338 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339
2340 if (maxFrameBufferAcquiredBuffers >= 3) {
2341 nativeWindowSurface->preallocateBuffers();
2342 }
2343
2344 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2346 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351 hw->setLayerStack(state.layerStack);
2352 hw->setProjection(state.orientation, state.viewport, state.frame);
2353 hw->setDisplayName(state.displayName);
2354
2355 return hw;
2356}
2357
Lloyd Pique347200f2017-12-14 17:00:15 -08002358void SurfaceFlinger::processDisplayChangesLocked() {
2359 // here we take advantage of Vector's copy-on-write semantics to
2360 // improve performance by skipping the transaction entirely when
2361 // know that the lists are identical
2362 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2363 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2364 if (!curr.isIdenticalTo(draw)) {
2365 mVisibleRegionsDirty = true;
2366 const size_t cc = curr.size();
2367 size_t dc = draw.size();
2368
2369 // find the displays that were removed
2370 // (ie: in drawing state but not in current state)
2371 // also handle displays that changed
2372 // (ie: displays that are in both lists)
2373 for (size_t i = 0; i < dc;) {
2374 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2375 if (j < 0) {
2376 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002377 // Call makeCurrent() on the primary display so we can
2378 // be sure that nothing associated with this display
2379 // is current.
2380 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2381 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2382 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2383 if (hw != nullptr) hw->disconnect(getHwComposer());
2384 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2385 mEventThread->onHotplugReceived(draw[i].type, false);
2386 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002387 } else {
2388 // this display is in both lists. see if something changed.
2389 const DisplayDeviceState& state(curr[j]);
2390 const wp<IBinder>& display(curr.keyAt(j));
2391 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2392 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2393 if (state_binder != draw_binder) {
2394 // changing the surface is like destroying and
2395 // recreating the DisplayDevice, so we just remove it
2396 // from the drawing state, so that it get re-added
2397 // below.
2398 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2399 if (hw != nullptr) hw->disconnect(getHwComposer());
2400 mDisplays.removeItem(display);
2401 mDrawingState.displays.removeItemsAt(i);
2402 dc--;
2403 // at this point we must loop to the next item
2404 continue;
2405 }
2406
2407 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2408 if (disp != nullptr) {
2409 if (state.layerStack != draw[i].layerStack) {
2410 disp->setLayerStack(state.layerStack);
2411 }
2412 if ((state.orientation != draw[i].orientation) ||
2413 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2414 disp->setProjection(state.orientation, state.viewport, state.frame);
2415 }
2416 if (state.width != draw[i].width || state.height != draw[i].height) {
2417 disp->setDisplaySize(state.width, state.height);
2418 }
2419 }
2420 }
2421 ++i;
2422 }
2423
2424 // find displays that were added
2425 // (ie: in current state but not in drawing state)
2426 for (size_t i = 0; i < cc; i++) {
2427 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2428 const DisplayDeviceState& state(curr[i]);
2429
2430 sp<DisplaySurface> dispSurface;
2431 sp<IGraphicBufferProducer> producer;
2432 sp<IGraphicBufferProducer> bqProducer;
2433 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002434 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002435
2436 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002437 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 // Virtual displays without a surface are dormant:
2439 // they have external state (layer stack, projection,
2440 // etc.) but no internal state (i.e. a DisplayDevice).
2441 if (state.surface != nullptr) {
2442 // Allow VR composer to use virtual displays.
2443 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2444 int width = 0;
2445 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2446 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2447 int height = 0;
2448 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2449 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2450 int intFormat = 0;
2451 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2452 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002453 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002454
2455 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2456 }
2457
2458 // TODO: Plumb requested format back up to consumer
2459
2460 sp<VirtualDisplaySurface> vds =
2461 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2462 bqProducer, bqConsumer,
2463 state.displayName);
2464
2465 dispSurface = vds;
2466 producer = vds;
2467 }
2468 } else {
2469 ALOGE_IF(state.surface != nullptr,
2470 "adding a supported display, but rendering "
2471 "surface is provided (%p), ignoring it",
2472 state.surface.get());
2473
2474 hwcId = state.type;
2475 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2476 producer = bqProducer;
2477 }
2478
2479 const wp<IBinder>& display(curr.keyAt(i));
2480 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002481 mDisplays.add(display,
2482 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2483 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002484 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 mEventThread->onHotplugReceived(state.type, true);
2486 }
2487 }
2488 }
2489 }
2490 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002491
2492 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002493}
2494
Mathias Agopian87baae12012-07-31 12:38:26 -07002495void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002496{
Dan Stoza7dde5992015-05-22 09:51:44 -07002497 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002498 mCurrentState.traverseInZOrder([](Layer* layer) {
2499 layer->notifyAvailableFrames();
2500 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 /*
2503 * Traversal of the children
2504 * (perform the transaction for each of them if needed)
2505 */
2506
Mathias Agopian3559b072012-08-15 13:46:03 -07002507 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002508 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002510 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
2512 const uint32_t flags = layer->doTransaction(0);
2513 if (flags & Layer::eVisibleRegion)
2514 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002515 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 }
2517
2518 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002519 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 */
2521
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002527 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002528 // The transform hint might have changed for some layers
2529 // (either because a display has changed, or because a layer
2530 // as changed).
2531 //
2532 // Walk through all the layers in currentLayers,
2533 // and update their transform hint.
2534 //
2535 // If a layer is visible only on a single display, then that
2536 // display is used to calculate the hint, otherwise we use the
2537 // default display.
2538 //
2539 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2540 // the hint is set before we acquire a buffer from the surface texture.
2541 //
2542 // NOTE: layer transactions have taken place already, so we use their
2543 // drawing state. However, SurfaceFlinger's own transaction has not
2544 // happened yet, so we must use the current state layer list
2545 // (soon to become the drawing state list).
2546 //
2547 sp<const DisplayDevice> disp;
2548 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002549 bool first = true;
2550 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002551 // NOTE: we rely on the fact that layers are sorted by
2552 // layerStack first (so we don't have to traverse the list
2553 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002555 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002556 currentlayerStack = layerStack;
2557 // figure out if this layerstack is mirrored
2558 // (more than one display) if so, pick the default display,
2559 // if not, pick the only display it's on.
2560 disp.clear();
2561 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2562 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002563 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002564 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002565 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002566 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002567 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002568 break;
2569 }
2570 }
2571 }
2572 }
Chet Haase91d25932013-04-11 15:24:55 -07002573
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002574 if (disp == nullptr) {
2575 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2576 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002577
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002578 // could be null when this layer is using a layerStack
2579 // that is not visible on any display. Also can occur at
2580 // screen off/on times.
2581 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002582 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002583
2584 // disp can be null if there is no display available at all to get
2585 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002586 if (disp != nullptr) {
2587 layer->updateTransformHint(disp);
2588 }
Robert Carr2047fae2016-11-28 14:09:09 -08002589
2590 first = false;
2591 });
Mathias Agopian84300952012-11-21 16:02:13 -08002592 }
2593
2594
Mathias Agopian3559b072012-08-15 13:46:03 -07002595 /*
2596 * Perform our own transaction if needed
2597 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002598
2599 if (mLayersAdded) {
2600 mLayersAdded = false;
2601 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002602 mVisibleRegionsDirty = true;
2603 }
2604
2605 // some layers might have been removed, so
2606 // we need to update the regions they're exposing.
2607 if (mLayersRemoved) {
2608 mLayersRemoved = false;
2609 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002610 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002611 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002612 // this layer is not visible anymore
2613 // TODO: we could traverse the tree from front to back and
2614 // compute the actual visible region
2615 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002616 Region visibleReg;
2617 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002618 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002619 }
Robert Carr2047fae2016-11-28 14:09:09 -08002620 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 }
2622
2623 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002624
2625 updateCursorAsync();
2626}
2627
2628void SurfaceFlinger::updateCursorAsync()
2629{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2631 auto& displayDevice = mDisplays[displayId];
2632 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002633 continue;
2634 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635
2636 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2637 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002638 }
2639 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002640}
2641
2642void SurfaceFlinger::commitTransaction()
2643{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002644 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002645 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 for (const auto& l : mLayersPendingRemoval) {
2647 recordBufferingStats(l->getName().string(),
2648 l->getOccupancyHistory(true));
2649 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650 }
2651 mLayersPendingRemoval.clear();
2652 }
2653
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002654 // If this transaction is part of a window animation then the next frame
2655 // we composite should be considered an animation as well.
2656 mAnimCompositionPending = mAnimTransactionPending;
2657
Mathias Agopian4fec8732012-06-29 14:12:52 -07002658 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 mDrawingState.traverseInZOrder([](Layer* layer) {
2660 layer->commitChildList();
2661 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002662 mTransactionPending = false;
2663 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002664 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665}
2666
Chia-I Wuab0c3192017-08-01 11:29:00 -07002667void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002668 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669{
Mathias Agopian841cde52012-03-01 15:44:37 -08002670 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002672
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 Region aboveOpaqueLayers;
2674 Region aboveCoveredLayers;
2675 Region dirty;
2676
Mathias Agopian87baae12012-07-31 12:38:26 -07002677 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
Robert Carr2047fae2016-11-28 14:09:09 -08002679 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002681 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
Jesse Hall01e29052013-02-19 16:13:35 -08002683 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002684 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002685 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002686
Mathias Agopianab028732010-03-16 16:41:46 -07002687 /*
2688 * opaqueRegion: area of a surface that is fully opaque.
2689 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002691
2692 /*
2693 * visibleRegion: area of a surface that is visible on screen
2694 * and not fully transparent. This is essentially the layer's
2695 * footprint minus the opaque regions above it.
2696 * Areas covered by a translucent surface are considered visible.
2697 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002699
2700 /*
2701 * coveredRegion: area of a surface that is covered by all
2702 * visible regions above it (which includes the translucent areas).
2703 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002705
Jesse Halla8026d22012-09-25 13:25:04 -07002706 /*
2707 * transparentRegion: area of a surface that is hinted to be completely
2708 * transparent. This is only used to tell when the layer has no visible
2709 * non-transparent regions and can be removed from the layer list. It
2710 * does not affect the visibleRegion of this layer or any layers
2711 * beneath it. The hint may not be correct if apps don't respect the
2712 * SurfaceView restrictions (which, sadly, some don't).
2713 */
2714 Region transparentRegion;
2715
Mathias Agopianab028732010-03-16 16:41:46 -07002716
2717 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002718 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002719 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002722 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002723 if (!visibleRegion.isEmpty()) {
2724 // Remove the transparent area from the visible region
2725 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002726 if (tr.preserveRects()) {
2727 // transform the transparent region
2728 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002730 // transformation too complex, can't do the
2731 // transparent region optimization.
2732 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002733 }
Mathias Agopianab028732010-03-16 16:41:46 -07002734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735
Mathias Agopianab028732010-03-16 16:41:46 -07002736 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002738 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002739 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2740 // the opaque region is the layer's footprint
2741 opaqueRegion = visibleRegion;
2742 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 }
2744 }
2745
Robert Carre5f4f692018-01-12 13:12:28 -08002746 if (visibleRegion.isEmpty()) {
2747 layer->clearVisibilityRegions();
2748 return;
2749 }
2750
Mathias Agopianab028732010-03-16 16:41:46 -07002751 // Clip the covered region to the visible region
2752 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2753
2754 // Update aboveCoveredLayers for next (lower) layer
2755 aboveCoveredLayers.orSelf(visibleRegion);
2756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 // subtract the opaque region covered by the layers above us
2758 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
2760 // compute this layer's dirty region
2761 if (layer->contentDirty) {
2762 // we need to invalidate the whole region
2763 dirty = visibleRegion;
2764 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002765 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 layer->contentDirty = false;
2767 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002768 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002769 * the exposed region consists of two components:
2770 * 1) what's VISIBLE now and was COVERED before
2771 * 2) what's EXPOSED now less what was EXPOSED before
2772 *
2773 * note that (1) is conservative, we start with the whole
2774 * visible region but only keep what used to be covered by
2775 * something -- which mean it may have been exposed.
2776 *
2777 * (2) handles areas that were not covered by anything but got
2778 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002779 */
Mathias Agopianab028732010-03-16 16:41:46 -07002780 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002781 const Region oldVisibleRegion = layer->visibleRegion;
2782 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002783 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2784 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 }
2786 dirty.subtractSelf(aboveOpaqueLayers);
2787
2788 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002789 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790
Mathias Agopianab028732010-03-16 16:41:46 -07002791 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002793
Jesse Halla8026d22012-09-25 13:25:04 -07002794 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 layer->setVisibleRegion(visibleRegion);
2796 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002797 layer->setVisibleNonTransparentRegion(
2798 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002799 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
Mathias Agopian87baae12012-07-31 12:38:26 -07002801 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802}
2803
Chia-I Wuab0c3192017-08-01 11:29:00 -07002804void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002805 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002806 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002807 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002808 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002809 }
2810 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002811}
2812
Dan Stoza6b9454d2014-11-07 16:00:59 -08002813bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("handlePageFlip");
2816
Brian Andersond6927fb2016-07-23 23:37:30 -07002817 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002821 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002822
2823 // Store the set of layers that need updates. This set must not change as
2824 // buffers are being latched, as this could result in a deadlock.
2825 // Example: Two producers share the same command stream and:
2826 // 1.) Layer 0 is latched
2827 // 2.) Layer 0 gets a new frame
2828 // 2.) Layer 1 gets a new frame
2829 // 3.) Layer 1 is latched.
2830 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2831 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 if (layer->hasQueuedFrame()) {
2834 frameQueued = true;
2835 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002836 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002837 } else {
2838 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002840 } else {
2841 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002842 }
Robert Carr2047fae2016-11-28 14:09:09 -08002843 });
2844
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002846 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002847 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002848 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002849 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002850 newDataLatched = true;
2851 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002852 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002853
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002854 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002855
2856 // If we will need to wake up at some time in the future to deal with a
2857 // queued frame that shouldn't be displayed during this vsync period, wake
2858 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002859 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 signalLayerUpdate();
2861 }
2862
2863 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002864 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Mathias Agopianad456f92011-01-13 17:53:01 -08002867void SurfaceFlinger::invalidateHwcGeometry()
2868{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002870}
2871
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002872
Fabien Sanglard830b8472016-11-30 16:35:58 -08002873void SurfaceFlinger::doDisplayComposition(
2874 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002875 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876{
Dan Stoza71433162014-02-04 16:22:36 -08002877 // We only need to actually compose the display if:
2878 // 1) It is being handled by hardware composer, which may need this to
2879 // keep its virtual display state machine in sync, or
2880 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002881 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002882 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002884 return;
2885 }
2886
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002888 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002889
2890 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002891 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Chia-I Wub02087d2017-11-09 10:19:54 -08002894bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002895{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002897
Chia-I Wub02087d2017-11-09 10:19:54 -08002898 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002899 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002900 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002901 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2902 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2903 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2904 HWC2::Capability::SkipClientColorTransform);
2905 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002906
2907 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002908 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2909 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002910 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002911 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002912 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002913 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002914 }
2915
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 if (hasClientComposition) {
2917 ALOGV("hasClientComposition");
2918
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002919 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002920 if (displayDevice->hasWideColorGamut()) {
2921 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002922 }
2923 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2924
Chia-I Wu7f402902017-11-09 12:51:10 -08002925 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002926 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002927 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002928 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002929
2930 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002931 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002932 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2933 }
2934 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002935 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002936
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002937 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 // when using overlays, we assume a fully transparent framebuffer
2940 // NOTE: we could reduce how much we need to clear, for instance
2941 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002942 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002943 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002944 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002945 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002946 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002947 // we're left with the letterbox region
2948 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002950
2951 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002953
Mathias Agopianb9494d52012-04-18 02:28:45 -07002954 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002955 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002956 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002958 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002959 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002960
Dominik Laskowski281644e2018-04-19 15:47:35 -07002961 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002962 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002963 // scissor on the main display. It should never be needed
2964 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 const Rect& bounds(displayDevice->getBounds());
2966 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002967 if (scissor != bounds) {
2968 // scissor doesn't match the screen's dimensions, so we
2969 // need to clear everything outside of it and enable
2970 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002971
Mathias Agopianf45c5102012-10-24 16:29:17 -07002972 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002974 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002975 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002976 }
2977 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002978 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002979
Mathias Agopian85d751c2012-08-29 16:59:24 -07002980 /*
2981 * and then, render the layers targeted at the framebuffer
2982 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002983
Dan Stoza9e56aa02015-11-02 13:00:03 -08002984 ALOGV("Rendering client layers");
2985 const Transform& displayTransform = displayDevice->getTransform();
2986 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002987 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002988 bool firstLayer = true;
2989 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002990 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 displayTransform.transform(layer->visibleRegion)));
2992 ALOGV("Layer: %s", layer->getName().string());
2993 ALOGV(" Composition type: %s",
2994 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002995 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 switch (layer->getCompositionType(hwcId)) {
2997 case HWC2::Composition::Cursor:
2998 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002999 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08003000 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07003001 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07003003 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003004 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07003005 // never clear the very first layer since we're
3006 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07003007 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003008 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003009 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003010 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003011 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003012 // Only apply saturation matrix layer that is legacy SRGB dataspace
3013 // when auto color mode is on.
3014 bool restore = false;
3015 mat4 savedMatrix;
3016 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3017 layer->isLegacySrgbDataSpace()) {
3018 savedMatrix =
3019 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3020 restore = true;
3021 }
chaviwa76b2712017-09-20 12:02:26 -07003022 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003023 if (restore) {
3024 getRenderEngine().setupColorTransform(savedMatrix);
3025 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003026 break;
3027 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003029 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003030 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003031 } else {
3032 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003033 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003035 }
3036 } else {
3037 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003039 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003041 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003042 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003043 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003044 }
3045 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003046
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003047 if (applyColorMatrix) {
3048 getRenderEngine().setupColorTransform(oldColorMatrix);
3049 }
3050
Mathias Agopianf45c5102012-10-24 16:29:17 -07003051 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003052 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003053 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054}
3055
Fabien Sanglard830b8472016-11-30 16:35:58 -08003056void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3057 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003058 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003059 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060}
3061
Dan Stoza7d89d062015-04-30 13:29:25 -07003062status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003063 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003064 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065 const sp<Layer>& lbc,
3066 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003067{
Dan Stoza7d89d062015-04-30 13:29:25 -07003068 // add this layer to the current state list
3069 {
3070 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003072 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3073 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003074 return NO_MEMORY;
3075 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 if (parent == nullptr) {
3077 mCurrentState.layersSortedByZ.add(lbc);
3078 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003079 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003080 ALOGE("addClientLayer called with a removed parent");
3081 return NAME_NOT_FOUND;
3082 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003083 parent->addChild(lbc);
3084 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003085
Dan Stoza101d8dc2018-02-27 15:42:25 -08003086 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003087 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3088 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3089 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3090 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3091 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003092 mLayersAdded = true;
3093 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003094 }
3095
Mathias Agopian96f08192010-06-02 23:28:45 -07003096 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003097 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003098
Dan Stoza7d89d062015-04-30 13:29:25 -07003099 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003100}
3101
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003102status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003103 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003104 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3105}
Robert Carr7f9b8992017-03-10 11:08:39 -08003106
chaviwca27f252018-02-06 16:46:39 -08003107status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3108 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003109 if (layer->isPendingRemoval()) {
3110 return NO_ERROR;
3111 }
3112
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003114 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003115 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003116 if (topLevelOnly) {
3117 return NO_ERROR;
3118 }
3119
Chia-I Wu98f1c102017-05-30 14:54:08 -07003120 sp<Layer> ancestor = p;
3121 while (ancestor->getParent() != nullptr) {
3122 ancestor = ancestor->getParent();
3123 }
3124 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3125 ALOGE("removeLayer called with a layer whose parent has been removed");
3126 return NAME_NOT_FOUND;
3127 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003128
3129 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003130 } else {
3131 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003132 }
3133
Robert Carr136e2f62017-02-08 17:54:29 -08003134 // As a matter of normal operation, the LayerCleaner will produce a second
3135 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3136 // so we will succeed in promoting it, but it's already been removed
3137 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3138 // otherwise something has gone wrong and we are leaking the layer.
3139 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003140 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3141 layer->getName().string(),
3142 (p != nullptr) ? p->getName().string() : "no-parent");
3143 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003144 } else if (index < 0) {
3145 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003146 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147
Chia-I Wuc6657022017-08-15 11:18:17 -07003148 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003149 mLayersPendingRemoval.add(layer);
3150 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003151 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003152 setTransactionFlags(eTransactionNeeded);
3153 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154}
3155
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003156uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003157 return android_atomic_release_load(&mTransactionFlags);
3158}
3159
Mathias Agopian3f844832013-08-07 21:24:32 -07003160uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3162}
3163
Mathias Agopian3f844832013-08-07 21:24:32 -07003164uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003165 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3166}
3167
3168uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3169 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003171 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003173 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174 }
3175 return old;
3176}
3177
chaviwca27f252018-02-06 16:46:39 -08003178bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3179 for (const ComposerState& state : states) {
3180 // Here we need to check that the interface we're given is indeed
3181 // one of our own. A malicious client could give us a nullptr
3182 // IInterface, or one of its own or even one of our own but a
3183 // different type. All these situations would cause us to crash.
3184 if (state.client == nullptr) {
3185 return true;
3186 }
3187
3188 sp<IBinder> binder = IInterface::asBinder(state.client);
3189 if (binder == nullptr) {
3190 return true;
3191 }
3192
3193 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3194 return true;
3195 }
3196 }
3197 return false;
3198}
3199
Mathias Agopian8b33f032012-07-24 20:43:54 -07003200void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003201 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003202 const Vector<DisplayState>& displays,
3203 uint32_t flags)
3204{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003205 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003206 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003207 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003208
chaviwca27f252018-02-06 16:46:39 -08003209 if (containsAnyInvalidClientState(states)) {
3210 return;
3211 }
3212
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003213 if (flags & eAnimation) {
3214 // For window updates that are part of an animation we must wait for
3215 // previous animation "frames" to be handled.
3216 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003217 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003218 if (CC_UNLIKELY(err != NO_ERROR)) {
3219 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003220 // caller after a few seconds.
3221 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3222 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003223 mAnimTransactionPending = false;
3224 break;
3225 }
3226 }
3227 }
3228
chaviwca27f252018-02-06 16:46:39 -08003229 for (const DisplayState& display : displays) {
3230 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003231 }
3232
chaviwca27f252018-02-06 16:46:39 -08003233 for (const ComposerState& state : states) {
3234 transactionFlags |= setClientStateLocked(state);
3235 }
3236
3237 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3238 // as destroyed should only occur after setting all other states. This is to allow for a
3239 // child re-parent to happen before marking its original parent as destroyed (which would
3240 // then mark the child as destroyed).
3241 for (const ComposerState& state : states) {
3242 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003243 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003244
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003245 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3246 // anyway. This can be used as a flush mechanism for previous async transactions.
3247 // Empty animation transaction can be used to simulate back-pressure, so also force a
3248 // transaction for empty animation transactions.
3249 if (transactionFlags == 0 &&
3250 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003251 transactionFlags = eTransactionNeeded;
3252 }
3253
Mathias Agopian386aa982011-11-07 21:58:03 -08003254 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003255 if (mInterceptor->isEnabled()) {
3256 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003257 }
Irvel468051e2016-06-13 16:44:44 -07003258
Mathias Agopian386aa982011-11-07 21:58:03 -08003259 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003260 const auto start = (flags & eEarlyWakeup)
3261 ? VSyncModulator::TransactionStart::EARLY
3262 : VSyncModulator::TransactionStart::NORMAL;
3263 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003264
3265 // if this is a synchronous transaction, wait for it to take effect
3266 // before returning.
3267 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003268 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003269 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003270 if (flags & eAnimation) {
3271 mAnimTransactionPending = true;
3272 }
3273 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003274 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3275 if (CC_UNLIKELY(err != NO_ERROR)) {
3276 // just in case something goes wrong in SF, return to the
3277 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003278 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3279 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003280 break;
3281 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003282 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 }
3284}
3285
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3287{
Jesse Hall9a143922012-10-04 16:29:19 -07003288 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3289 if (dpyIdx < 0)
3290 return 0;
3291
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003293 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003294 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295 const uint32_t what = s.what;
3296 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003297 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 disp.surface = s.surface;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 }
3302 if (what & DisplayState::eLayerStackChanged) {
3303 if (disp.layerStack != s.layerStack) {
3304 disp.layerStack = s.layerStack;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003308 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003309 if (disp.orientation != s.orientation) {
3310 disp.orientation = s.orientation;
3311 flags |= eDisplayTransactionNeeded;
3312 }
3313 if (disp.frame != s.frame) {
3314 disp.frame = s.frame;
3315 flags |= eDisplayTransactionNeeded;
3316 }
3317 if (disp.viewport != s.viewport) {
3318 disp.viewport = s.viewport;
3319 flags |= eDisplayTransactionNeeded;
3320 }
3321 }
Michael Lentine47e45402014-07-18 15:34:25 -07003322 if (what & DisplayState::eDisplaySizeChanged) {
3323 if (disp.width != s.width) {
3324 disp.width = s.width;
3325 flags |= eDisplayTransactionNeeded;
3326 }
3327 if (disp.height != s.height) {
3328 disp.height = s.height;
3329 flags |= eDisplayTransactionNeeded;
3330 }
3331 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 }
3333 return flags;
3334}
3335
chaviwca27f252018-02-06 16:46:39 -08003336uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3337 const layer_state_t& s = composerState.state;
3338 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3339
Mathias Agopian13127d82013-03-05 17:47:11 -08003340 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003341 if (layer == nullptr) {
3342 return 0;
3343 }
3344
3345 if (layer->isPendingRemoval()) {
3346 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3347 return 0;
3348 }
3349
3350 uint32_t flags = 0;
3351
3352 const uint32_t what = s.what;
3353 bool geometryAppliesWithResize =
3354 what & layer_state_t::eGeometryAppliesWithResize;
3355 if (what & layer_state_t::ePositionChanged) {
3356 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3357 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003358 }
chaviw8b3871a2017-11-01 17:41:01 -07003359 }
3360 if (what & layer_state_t::eLayerChanged) {
3361 // NOTE: index needs to be calculated before we update the state
3362 const auto& p = layer->getParent();
3363 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003364 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003365 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003366 mCurrentState.layersSortedByZ.removeAt(idx);
3367 mCurrentState.layersSortedByZ.add(layer);
3368 // we need traversal (state changed)
3369 // AND transaction (list changed)
3370 flags |= eTransactionNeeded|eTraversalNeeded;
3371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 } else {
3373 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003374 flags |= eTransactionNeeded|eTraversalNeeded;
3375 }
3376 }
chaviw8b3871a2017-11-01 17:41:01 -07003377 }
3378 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003379 // NOTE: index needs to be calculated before we update the state
3380 const auto& p = layer->getParent();
3381 if (p == nullptr) {
3382 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3383 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3384 mCurrentState.layersSortedByZ.removeAt(idx);
3385 mCurrentState.layersSortedByZ.add(layer);
3386 // we need traversal (state changed)
3387 // AND transaction (list changed)
3388 flags |= eTransactionNeeded|eTraversalNeeded;
3389 }
3390 } else {
3391 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3392 flags |= eTransactionNeeded|eTraversalNeeded;
3393 }
chaviw8b3871a2017-11-01 17:41:01 -07003394 }
3395 }
3396 if (what & layer_state_t::eSizeChanged) {
3397 if (layer->setSize(s.w, s.h)) {
3398 flags |= eTraversalNeeded;
3399 }
3400 }
3401 if (what & layer_state_t::eAlphaChanged) {
3402 if (layer->setAlpha(s.alpha))
3403 flags |= eTraversalNeeded;
3404 }
3405 if (what & layer_state_t::eColorChanged) {
3406 if (layer->setColor(s.color))
3407 flags |= eTraversalNeeded;
3408 }
3409 if (what & layer_state_t::eMatrixChanged) {
3410 if (layer->setMatrix(s.matrix))
3411 flags |= eTraversalNeeded;
3412 }
3413 if (what & layer_state_t::eTransparentRegionChanged) {
3414 if (layer->setTransparentRegionHint(s.transparentRegion))
3415 flags |= eTraversalNeeded;
3416 }
3417 if (what & layer_state_t::eFlagsChanged) {
3418 if (layer->setFlags(s.flags, s.mask))
3419 flags |= eTraversalNeeded;
3420 }
3421 if (what & layer_state_t::eCropChanged) {
3422 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3423 flags |= eTraversalNeeded;
3424 }
3425 if (what & layer_state_t::eFinalCropChanged) {
3426 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3427 flags |= eTraversalNeeded;
3428 }
3429 if (what & layer_state_t::eLayerStackChanged) {
3430 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3431 // We only allow setting layer stacks for top level layers,
3432 // everything else inherits layer stack from its parent.
3433 if (layer->hasParent()) {
3434 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3435 layer->getName().string());
3436 } else if (idx < 0) {
3437 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3438 "that also does not appear in the top level layer list. Something"
3439 " has gone wrong.", layer->getName().string());
3440 } else if (layer->setLayerStack(s.layerStack)) {
3441 mCurrentState.layersSortedByZ.removeAt(idx);
3442 mCurrentState.layersSortedByZ.add(layer);
3443 // we need traversal (state changed)
3444 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003445 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003446 }
3447 }
3448 if (what & layer_state_t::eDeferTransaction) {
3449 if (s.barrierHandle != nullptr) {
3450 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3451 } else if (s.barrierGbp != nullptr) {
3452 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3453 if (authenticateSurfaceTextureLocked(gbp)) {
3454 const auto& otherLayer =
3455 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3456 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3457 } else {
3458 ALOGE("Attempt to defer transaction to to an"
3459 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003460 }
3461 }
chaviw8b3871a2017-11-01 17:41:01 -07003462 // We don't trigger a traversal here because if no other state is
3463 // changed, we don't want this to cause any more work
3464 }
3465 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003466 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003467 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003468 if (!hadParent) {
3469 mCurrentState.layersSortedByZ.remove(layer);
3470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003472 }
chaviw8b3871a2017-11-01 17:41:01 -07003473 }
3474 if (what & layer_state_t::eReparentChildren) {
3475 if (layer->reparentChildren(s.reparentHandle)) {
3476 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003477 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003478 }
chaviw8b3871a2017-11-01 17:41:01 -07003479 if (what & layer_state_t::eDetachChildren) {
3480 layer->detachChildren();
3481 }
3482 if (what & layer_state_t::eOverrideScalingModeChanged) {
3483 layer->setOverrideScalingMode(s.overrideScalingMode);
3484 // We don't trigger a traversal here because if no other state is
3485 // changed, we don't want this to cause any more work
3486 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003487 return flags;
3488}
3489
chaviwca27f252018-02-06 16:46:39 -08003490void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3491 const layer_state_t& state = composerState.state;
3492 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3493
3494 sp<Layer> layer(client->getLayerUser(state.surface));
3495 if (layer == nullptr) {
3496 return;
3497 }
3498
3499 if (layer->isPendingRemoval()) {
3500 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3501 return;
3502 }
3503
3504 if (state.what & layer_state_t::eDestroySurface) {
3505 removeLayerLocked(mStateLock, layer);
3506 }
3507}
3508
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003509status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003510 const String8& name,
3511 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003512 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003513 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003514 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003516 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003517 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003518 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003520 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003521
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522 status_t result = NO_ERROR;
3523
3524 sp<Layer> layer;
3525
Cody Northropbc755282017-03-31 12:00:08 -06003526 String8 uniqueName = getUniqueLayerName(name);
3527
Mathias Agopian3165cc22012-08-08 19:42:09 -07003528 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3529 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003530 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003531 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 break;
chaviw13fdc492017-06-27 12:40:18 -07003535 case ISurfaceComposerClient::eFXSurfaceColor:
3536 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003537 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003538 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 break;
3540 default:
3541 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 break;
3543 }
3544
Dan Stoza7d89d062015-04-30 13:29:25 -07003545 if (result != NO_ERROR) {
3546 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003548
Chia-I Wuab0c3192017-08-01 11:29:00 -07003549 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3550 // TODO b/64227542
3551 if (windowType == 441731) {
3552 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3553 layer->setPrimaryDisplayOnly();
3554 }
3555
Albert Chaulk479c60c2017-01-27 14:21:34 -05003556 layer->setInfo(windowType, ownerUid);
3557
Robert Carr1f0a16a2016-10-24 16:27:39 -07003558 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003559 if (result != NO_ERROR) {
3560 return result;
3561 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003562 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003563
3564 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003565 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566}
3567
Cody Northropbc755282017-03-31 12:00:08 -06003568String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3569{
3570 bool matchFound = true;
3571 uint32_t dupeCounter = 0;
3572
3573 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3574 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3575
3576 // Loop over layers until we're sure there is no matching name
3577 while (matchFound) {
3578 matchFound = false;
3579 mDrawingState.traverseInZOrder([&](Layer* layer) {
3580 if (layer->getName() == uniqueName) {
3581 matchFound = true;
3582 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3583 }
3584 });
3585 }
3586
3587 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3588
3589 return uniqueName;
3590}
3591
David Sodman0c69cad2017-08-21 12:12:51 -07003592status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595{
3596 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003597 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 case PIXEL_FORMAT_TRANSPARENT:
3599 case PIXEL_FORMAT_TRANSLUCENT:
3600 format = PIXEL_FORMAT_RGBA_8888;
3601 break;
3602 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003603 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 break;
3605 }
3606
David Sodman0c69cad2017-08-21 12:12:51 -07003607 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3608 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003610 *handle = layer->getHandle();
3611 *gbp = layer->getProducer();
3612 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614
David Sodman0c69cad2017-08-21 12:12:51 -07003615 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617}
3618
chaviw13fdc492017-06-27 12:40:18 -07003619status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003621 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622{
chaviw13fdc492017-06-27 12:40:18 -07003623 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003626}
3627
Mathias Agopianac9fa422013-02-11 16:40:36 -08003628status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629{
Robert Carr9524cb32017-02-13 11:32:32 -08003630 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003631 status_t err = NO_ERROR;
3632 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003633 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003634 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003635 err = removeLayer(l);
3636 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3637 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003638 }
3639 return err;
3640}
3641
Mathias Agopian13127d82013-03-05 17:47:11 -08003642status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003643{
Mathias Agopian67106042013-03-14 19:18:13 -07003644 // called by ~LayerCleaner() when all references to the IBinder (handle)
3645 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003646 sp<Layer> l = layer.promote();
3647 if (l == nullptr) {
3648 // The layer has already been removed, carry on
3649 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003650 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003651 // If we have a parent, then we can continue to live as long as it does.
3652 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653}
3654
Mathias Agopianb60314a2012-04-10 22:09:54 -07003655// ---------------------------------------------------------------------------
3656
Andy McFadden13a082e2012-08-24 10:16:42 -07003657void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003658 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003659 Vector<ComposerState> state;
3660 Vector<DisplayState> displays;
3661 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003662 d.what = DisplayState::eDisplayProjectionChanged |
3663 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003664 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003665 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003666 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003667 d.frame.makeInvalid();
3668 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003669 d.width = 0;
3670 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 displays.add(d);
3672 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003673 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3674 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003675
David Sodman105b7dc2017-11-04 20:28:14 -07003676 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003677 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003678 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003679
Brian Andersond0010582017-03-07 13:20:31 -08003680 // Use phase of 0 since phase is not known.
3681 // Use latency of 0, which will snap to the ideal latency.
3682 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003683}
3684
3685void SurfaceFlinger::initializeDisplays() {
3686 class MessageScreenInitialized : public MessageBase {
3687 SurfaceFlinger* flinger;
3688 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003689 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 virtual bool handler() {
3691 flinger->onInitializeDisplays();
3692 return true;
3693 }
3694 };
3695 sp<MessageBase> msg = new MessageScreenInitialized(this);
3696 postMessageAsync(msg); // we may be called from main thread, use async message
3697}
3698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003700 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3702 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003703 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003704
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 return;
3707 }
3708
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003709 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003710 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 ALOGW("Trying to set power mode for virtual display");
3712 return;
3713 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003714
Lloyd Pique4dccc412018-01-22 17:21:36 -08003715 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003716 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003717 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3718 if (idx < 0) {
3719 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3720 return;
3721 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003722 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003723 }
3724
Dominik Laskowski281644e2018-04-19 15:47:35 -07003725 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003727 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003728 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003729 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003730 // FIXME: eventthread only knows about the main display right now
3731 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003732 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003733 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003734
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003735 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003736 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003737 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003738
3739 struct sched_param param = {0};
3740 param.sched_priority = 1;
3741 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3742 ALOGW("Couldn't set SCHED_FIFO on display on");
3743 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003744 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003745 // Turn off the display
3746 struct sched_param param = {0};
3747 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3748 ALOGW("Couldn't set SCHED_OTHER on display off");
3749 }
3750
Dominik Laskowski281644e2018-04-19 15:47:35 -07003751 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003752 disableHardwareVsync(true); // also cancels any in-progress resync
3753
Mathias Agopiancde87a32012-09-13 14:09:01 -07003754 // FIXME: eventthread only knows about the main display right now
3755 mEventThread->onScreenReleased();
3756 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003757
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 getHwComposer().setPowerMode(type, mode);
3759 mVisibleRegionsDirty = true;
3760 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003761 } else if (mode == HWC_POWER_MODE_DOZE ||
3762 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003763 // Update display while dozing
3764 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003765 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003766 // FIXME: eventthread only knows about the main display right now
3767 mEventThread->onScreenAcquired();
3768 resyncToHardwareVsync(true);
3769 }
3770 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3771 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003772 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003773 disableHardwareVsync(true); // also cancels any in-progress resync
3774 // FIXME: eventthread only knows about the main display right now
3775 mEventThread->onScreenReleased();
3776 }
3777 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003779 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003781 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003782 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783}
3784
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3786 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003787 SurfaceFlinger& mFlinger;
3788 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003789 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003791 MessageSetPowerMode(SurfaceFlinger& flinger,
3792 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3793 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003794 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003796 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003798 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003799 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003800 ALOGW("Attempt to set power mode = %d for virtual display",
3801 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003802 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003803 mFlinger.setPowerModeInternal(
3804 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003805 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003806 return true;
3807 }
3808 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003809 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003810 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003811}
3812
3813// ---------------------------------------------------------------------------
3814
Lloyd Pique755e3192018-01-31 16:46:15 -08003815status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3816 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003818
Mathias Agopianbd115332013-04-18 16:41:04 -07003819 IPCThreadState* ipc = IPCThreadState::self();
3820 const int pid = ipc->getCallingPid();
3821 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003822
Mathias Agopianbd115332013-04-18 16:41:04 -07003823 if ((uid != AID_SHELL) &&
3824 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003826 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003828 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 // (this would indicate SF is stuck, but we want to be able to
3830 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003831 status_t err = mStateLock.timedLock(s2ns(1));
3832 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003833 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003834 result.appendFormat(
3835 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3836 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003837 }
3838
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839 bool dumpAll = true;
3840 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003842
3843 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003844 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003845 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3846 dumpAll = false;
3847 }
3848
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 if ((index < numArgs) &&
3851 (args[index] == String16("--list"))) {
3852 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003854 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003855 }
3856
3857 if ((index < numArgs) &&
3858 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003860 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003861 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863
3864 if ((index < numArgs) &&
3865 (args[index] == String16("--latency-clear"))) {
3866 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003867 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003868 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003869 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--dispsync"))) {
3873 index++;
3874 mPrimaryDispSync.dump(result);
3875 dumpAll = false;
3876 }
Dan Stozab90cf072015-03-05 11:05:59 -08003877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--static-screen"))) {
3880 index++;
3881 dumpStaticScreenStats(result);
3882 dumpAll = false;
3883 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003884
3885 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003886 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003887 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003888 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003889 dumpAll = false;
3890 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003891
3892 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3893 index++;
3894 dumpWideColorInfo(result);
3895 dumpAll = false;
3896 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003897
3898 if ((index < numArgs) &&
3899 (args[index] == String16("--enable-layer-stats"))) {
3900 index++;
3901 mLayerStats.enable();
3902 dumpAll = false;
3903 }
3904
3905 if ((index < numArgs) &&
3906 (args[index] == String16("--disable-layer-stats"))) {
3907 index++;
3908 mLayerStats.disable();
3909 dumpAll = false;
3910 }
3911
3912 if ((index < numArgs) &&
3913 (args[index] == String16("--clear-layer-stats"))) {
3914 index++;
3915 mLayerStats.clear();
3916 dumpAll = false;
3917 }
3918
3919 if ((index < numArgs) &&
3920 (args[index] == String16("--dump-layer-stats"))) {
3921 index++;
3922 mLayerStats.dump(result);
3923 dumpAll = false;
3924 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003925
3926 if ((index < numArgs) &&
3927 (args[index] == String16("--display-identification"))) {
3928 index++;
3929 dumpDisplayIdentificationData(result);
3930 dumpAll = false;
3931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003933
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003935 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003936 }
3937
Mathias Agopian9795c422009-08-26 16:36:26 -07003938 if (locked) {
3939 mStateLock.unlock();
3940 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941 }
3942 write(fd, result.string(), result.size());
3943 return NO_ERROR;
3944}
3945
Dan Stozac7014012014-02-14 15:03:43 -08003946void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3947 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003948{
Robert Carr2047fae2016-11-28 14:09:09 -08003949 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003950 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003951 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003952}
3953
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003954void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003955 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003956{
3957 String8 name;
3958 if (index < args.size()) {
3959 name = String8(args[index]);
3960 index++;
3961 }
3962
David Sodman105b7dc2017-11-04 20:28:14 -07003963 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003964 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003965 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003966
3967 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003968 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003969 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003970 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003971 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003972 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003973 }
Robert Carr2047fae2016-11-28 14:09:09 -08003974 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975 }
3976}
3977
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003978void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003979 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003980{
3981 String8 name;
3982 if (index < args.size()) {
3983 name = String8(args[index]);
3984 index++;
3985 }
3986
Robert Carr2047fae2016-11-28 14:09:09 -08003987 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003988 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003989 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003990 }
Robert Carr2047fae2016-11-28 14:09:09 -08003991 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003992
Svetoslavd85084b2014-03-20 10:28:31 -07003993 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003994}
3995
Jamie Gennis6547ff42013-07-16 20:12:42 -07003996// This should only be called from the main thread. Otherwise it would need
3997// the lock and should use mCurrentState rather than mDrawingState.
3998void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003999 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004000 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004001 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004002
4003 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4004}
4005
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004006void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004007{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004008 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004009
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004010 if (isLayerTripleBufferingDisabled())
4011 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004012
4013 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004014 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004015 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004016 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004017 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4018 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004019 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004020}
4021
Dan Stozab90cf072015-03-05 11:05:59 -08004022void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4023{
4024 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004025 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4026 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004027 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004028 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004029 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4030 b + 1, bucketTimeSec, percent);
4031 }
David Sodman4a36e932017-11-07 14:29:47 -08004032 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004033 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004034 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004035 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004036 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004037}
4038
Dan Stozae77c7662016-05-13 11:37:28 -07004039void SurfaceFlinger::recordBufferingStats(const char* layerName,
4040 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004041 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4042 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004043 for (const auto& segment : history) {
4044 if (!segment.usedThirdBuffer) {
4045 stats.twoBufferTime += segment.totalTime;
4046 }
4047 if (segment.occupancyAverage < 1.0f) {
4048 stats.doubleBufferedTime += segment.totalTime;
4049 } else if (segment.occupancyAverage < 2.0f) {
4050 stats.tripleBufferedTime += segment.totalTime;
4051 }
4052 ++stats.numSegments;
4053 stats.totalTime += segment.totalTime;
4054 }
4055}
4056
Brian Andersond6927fb2016-07-23 23:37:30 -07004057void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4058 result.appendFormat("Layer frame timestamps:\n");
4059
4060 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4061 const size_t count = currentLayers.size();
4062 for (size_t i=0 ; i<count ; i++) {
4063 currentLayers[i]->dumpFrameEvents(result);
4064 }
4065}
4066
Dan Stozae77c7662016-05-13 11:37:28 -07004067void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4068 result.append("Buffering stats:\n");
4069 result.append(" [Layer name] <Active time> <Two buffer> "
4070 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004071 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004072 typedef std::tuple<std::string, float, float, float> BufferTuple;
4073 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004074 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004075 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004076 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004077 if (stats.numSegments == 0) {
4078 continue;
4079 }
4080 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4081 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4082 stats.totalTime;
4083 float doubleBufferRatio = static_cast<float>(
4084 stats.doubleBufferedTime) / stats.totalTime;
4085 float tripleBufferRatio = static_cast<float>(
4086 stats.tripleBufferedTime) / stats.totalTime;
4087 sorted.insert({activeTime, {name, twoBufferRatio,
4088 doubleBufferRatio, tripleBufferRatio}});
4089 }
4090 for (const auto& sortedPair : sorted) {
4091 float activeTime = sortedPair.first;
4092 const BufferTuple& values = sortedPair.second;
4093 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4094 std::get<0>(values).c_str(), activeTime,
4095 std::get<1>(values), std::get<2>(values),
4096 std::get<3>(values));
4097 }
4098 result.append("\n");
4099}
4100
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004101void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4102 for (size_t d = 0; d < mDisplays.size(); d++) {
4103 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4104 const int32_t hwcId = displayDevice->getHwcDisplayId();
4105 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4106 if (!displayId) {
4107 continue;
4108 }
4109
4110 result.appendFormat("Display %d: ", hwcId);
4111 uint8_t port;
4112 DisplayIdentificationData data;
4113 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4114 result.append("no identification data\n");
4115 continue;
4116 }
4117
4118 if (!isEdid(data)) {
4119 result.append("unknown identification data: ");
4120 for (uint8_t byte : data) {
4121 result.appendFormat("%x ", byte);
4122 }
4123 result.append("\n");
4124 continue;
4125 }
4126
4127 const auto edid = parseEdid(data);
4128 if (!edid) {
4129 result.append("invalid EDID: ");
4130 for (uint8_t byte : data) {
4131 result.appendFormat("%x ", byte);
4132 }
4133 result.append("\n");
4134 continue;
4135 }
4136
4137 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4138 result.append(edid->displayName.data(), edid->displayName.length());
4139 result.append("\"\n");
4140 }
4141 result.append("\n");
4142}
4143
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004144void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4145 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004146 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004147
4148 // TODO: print out if wide-color mode is active or not
4149
4150 for (size_t d = 0; d < mDisplays.size(); d++) {
4151 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4152 int32_t hwcId = displayDevice->getHwcDisplayId();
4153 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4154 continue;
4155 }
4156
4157 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004158 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004159 for (auto&& mode : modes) {
4160 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4161 }
4162
Peiyong Lina52f0292018-03-14 17:26:31 -07004163 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004164 result.appendFormat(" Current color mode: %s (%d)\n",
4165 decodeColorMode(currentMode).c_str(), currentMode);
4166 }
4167 result.append("\n");
4168}
4169
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004170LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004171 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004172 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4173 const State& state = useDrawing ? mDrawingState : mCurrentState;
4174 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004175 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004176 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004177 });
4178
4179 return layersProto;
4180}
4181
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004182LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4183 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004184 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004185
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004186 SizeProto* resolution = layersProto.mutable_resolution();
4187 resolution->set_w(displayDevice->getWidth());
4188 resolution->set_h(displayDevice->getHeight());
4189
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004190 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4191 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4192 layersProto.set_global_transform(
4193 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4194
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004195 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004196 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004197 LayerProto* layerProto = layersProto.add_layers();
4198 layer->writeToProto(layerProto, hwcId);
4199 }
4200 });
4201
4202 return layersProto;
4203}
4204
Mathias Agopian74d211a2013-04-22 16:55:35 +02004205void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4206 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004207{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004208 bool colorize = false;
4209 if (index < args.size()
4210 && (args[index] == String16("--color"))) {
4211 colorize = true;
4212 index++;
4213 }
4214
4215 Colorizer colorizer(colorize);
4216
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004217 // figure out if we're stuck somewhere
4218 const nsecs_t now = systemTime();
4219 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4220 const nsecs_t inTransaction(mDebugInTransaction);
4221 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4222 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4223
4224 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004225 * Dump library configuration.
4226 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004227
4228 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004229 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004231 appendSfConfigString(result);
4232 appendUiConfigString(result);
4233 appendGuiConfigString(result);
4234 result.append("\n");
4235
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004236 result.append("\nDisplay identification data:\n");
4237 dumpDisplayIdentificationData(result);
4238
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004239 result.append("\nWide-Color information:\n");
4240 dumpWideColorInfo(result);
4241
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004242 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004243 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004244 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004245 result.append(SyncFeatures::getInstance().toString());
4246 result.append("\n");
4247
David Sodman105b7dc2017-11-04 20:28:14 -07004248 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004249
Andy McFadden41d67d72014-04-25 16:58:34 -07004250 colorizer.bold(result);
4251 result.append("DispSync configuration: ");
4252 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004253 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4254 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4255 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004256 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004257 result.append("\n");
4258
Dan Stozab90cf072015-03-05 11:05:59 -08004259 // Dump static screen stats
4260 result.append("\n");
4261 dumpStaticScreenStats(result);
4262 result.append("\n");
4263
Dan Stozae77c7662016-05-13 11:37:28 -07004264 dumpBufferingStats(result);
4265
Andy McFadden4803b742012-09-24 19:07:20 -07004266 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267 * Dump the visible layer list
4268 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004269 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004270 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004271 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4272 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004274
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004275 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004276 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004277 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004278 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279
4280 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004281 * Dump Display state
4282 */
4283
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004285 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004286 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004287 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4288 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004289 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004290 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004291 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004292
4293 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004294 * Dump SurfaceFlinger global state
4295 */
4296
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004298 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004300
Mathias Agopian888c8222012-08-04 21:10:38 -07004301 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004302 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004303
David Sodmanbc815282017-11-05 18:57:52 -08004304 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004306 if (hw) {
4307 hw->undefinedRegion.dump(result, "undefinedRegion");
4308 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4309 hw->getOrientation(), hw->isDisplayOn());
4310 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004311 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312 " last eglSwapBuffers() time: %f us\n"
4313 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004314 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315 " refresh-rate : %f fps\n"
4316 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004317 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004318 " gpu_to_cpu_unsupported : %d\n"
4319 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004320 mLastSwapBufferTime/1000.0,
4321 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004322 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004323 1e9 / activeConfig->getVsyncPeriod(),
4324 activeConfig->getDpiX(),
4325 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004326 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004327
Mathias Agopian74d211a2013-04-22 16:55:35 +02004328 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
4334 /*
4335 * VSYNC state
4336 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004337 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004338 result.append("\n");
4339
4340 /*
4341 * HWC layer minidump
4342 */
4343 for (size_t d = 0; d < mDisplays.size(); d++) {
4344 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4345 int32_t hwcId = displayDevice->getHwcDisplayId();
4346 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4347 continue;
4348 }
4349
4350 result.appendFormat("Display %d HWC layers:\n", hwcId);
4351 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004352 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004353 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004354 });
Dan Stozae22aec72016-08-01 13:20:59 -07004355 result.append("\n");
4356 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357
4358 /*
4359 * Dump HWComposer state
4360 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004361 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004362 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004363 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004364 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004365 result.appendFormat(" h/w composer %s\n",
4366 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004367 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368
4369 /*
4370 * Dump gralloc state
4371 */
4372 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4373 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004374
4375 /*
4376 * Dump VrFlinger state if in use.
4377 */
4378 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4379 result.append("VrFlinger state:\n");
4380 result.append(mVrFlinger->Dump().c_str());
4381 result.append("\n");
4382 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004383}
4384
Mathias Agopian13127d82013-03-05 17:47:11 -08004385const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004386SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004387 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004388 wp<IBinder> dpy;
4389 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4390 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4391 dpy = mDisplays.keyAt(i);
4392 break;
4393 }
4394 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004395 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004396 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4397 // Just use the primary display so we have something to return
4398 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4399 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004400 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004401}
4402
Keun young Park63f165f2012-08-31 10:53:36 -07004403bool SurfaceFlinger::startDdmConnection()
4404{
4405 void* libddmconnection_dso =
4406 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4407 if (!libddmconnection_dso) {
4408 return false;
4409 }
4410 void (*DdmConnection_start)(const char* name);
4411 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004412 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004413 if (!DdmConnection_start) {
4414 dlclose(libddmconnection_dso);
4415 return false;
4416 }
4417 (*DdmConnection_start)(getServiceName());
4418 return true;
4419}
4420
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004421status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004422 switch (code) {
4423 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004424 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004425 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004426 case CLEAR_ANIMATION_FRAME_STATS:
4427 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004428 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004429 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004430 case ENABLE_VSYNC_INJECTIONS:
4431 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 {
4433 // codes that require permission check
4434 IPCThreadState* ipc = IPCThreadState::self();
4435 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004436 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004437 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004438 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004439 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004440 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004442 break;
4443 }
Robert Carr1db73f62016-12-21 12:58:51 -08004444 /*
4445 * Calling setTransactionState is safe, because you need to have been
4446 * granted a reference to Client* and Handle* to do anything with it.
4447 *
4448 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4449 */
4450 case SET_TRANSACTION_STATE:
4451 case CREATE_SCOPED_CONNECTION:
4452 {
4453 return OK;
4454 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004455 case CAPTURE_SCREEN:
4456 {
4457 // codes that require permission check
4458 IPCThreadState* ipc = IPCThreadState::self();
4459 const int pid = ipc->getCallingPid();
4460 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004461 if ((uid != AID_GRAPHICS) &&
4462 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004463 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004464 return PERMISSION_DENIED;
4465 }
4466 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004467 }
chaviwa76b2712017-09-20 12:02:26 -07004468 case CAPTURE_LAYERS: {
4469 IPCThreadState* ipc = IPCThreadState::self();
4470 const int pid = ipc->getCallingPid();
4471 const int uid = ipc->getCallingUid();
4472 if ((uid != AID_GRAPHICS) &&
4473 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4474 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4475 return PERMISSION_DENIED;
4476 }
4477 break;
4478 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004480 return OK;
4481}
4482
4483status_t SurfaceFlinger::onTransact(
4484 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4485{
4486 status_t credentialCheck = CheckTransactCodeCredentials(code);
4487 if (credentialCheck != OK) {
4488 return credentialCheck;
4489 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004490
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004491 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4492 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004493 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004494 IPCThreadState* ipc = IPCThreadState::self();
4495 const int uid = ipc->getCallingUid();
4496 if (CC_UNLIKELY(uid != AID_SYSTEM
4497 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004498 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004499 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004500 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004501 return PERMISSION_DENIED;
4502 }
4503 int n;
4504 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004505 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004506 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004507 return NO_ERROR;
4508 case 1002: // SHOW_UPDATES
4509 n = data.readInt32();
4510 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004511 invalidateHwcGeometry();
4512 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004514 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004515 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004516 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004517 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004518 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004519 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004520 setTransactionFlags(
4521 eTransactionNeeded|
4522 eDisplayTransactionNeeded|
4523 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004524 return NO_ERROR;
4525 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004526 case 1006:{ // send empty update
4527 signalRefresh();
4528 return NO_ERROR;
4529 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004530 case 1008: // toggle use of hw composer
4531 n = data.readInt32();
4532 mDebugDisableHWC = n ? 1 : 0;
4533 invalidateHwcGeometry();
4534 repaintEverything();
4535 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004536 case 1009: // toggle use of transform hint
4537 n = data.readInt32();
4538 mDebugDisableTransformHint = n ? 1 : 0;
4539 invalidateHwcGeometry();
4540 repaintEverything();
4541 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004542 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004543 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 reply->writeInt32(0);
4545 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004546 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004547 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 return NO_ERROR;
4549 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004550 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004551 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004552 return NO_ERROR;
4553 }
4554 case 1014: {
4555 // daltonize
4556 n = data.readInt32();
4557 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004558 case 1:
4559 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4560 break;
4561 case 2:
4562 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4563 break;
4564 case 3:
4565 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4566 break;
4567 default:
4568 mDaltonizer.setType(ColorBlindnessType::None);
4569 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004570 }
4571 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004572 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004573 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004574 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004575 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004576 invalidateHwcGeometry();
4577 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004578 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004580 case 1015: {
4581 // apply a color matrix
4582 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004583 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004584 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004585 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004586 for (size_t j = 0; j < 4; j++) {
4587 mColorMatrix[i][j] = data.readFloat();
4588 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004589 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004590 } else {
4591 mColorMatrix = mat4();
4592 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004593
4594 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4595 // the division by w in the fragment shader
4596 float4 lastRow(transpose(mColorMatrix)[3]);
4597 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4598 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4599 }
4600
Alan Viverette9c5a3332013-09-12 20:04:35 -07004601 invalidateHwcGeometry();
4602 repaintEverything();
4603 return NO_ERROR;
4604 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004605 // This is an experimental interface
4606 // Needs to be shifted to proper binder interface when we productize
4607 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004608 n = data.readInt32();
4609 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004610 return NO_ERROR;
4611 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004612 case 1017: {
4613 n = data.readInt32();
4614 mForceFullDamage = static_cast<bool>(n);
4615 return NO_ERROR;
4616 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004617 case 1018: { // Modify Choreographer's phase offset
4618 n = data.readInt32();
4619 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4620 return NO_ERROR;
4621 }
4622 case 1019: { // Modify SurfaceFlinger's phase offset
4623 n = data.readInt32();
4624 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4625 return NO_ERROR;
4626 }
Irvel468051e2016-06-13 16:44:44 -07004627 case 1020: { // Layer updates interceptor
4628 n = data.readInt32();
4629 if (n) {
4630 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004631 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004632 }
4633 else{
4634 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004635 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004636 }
4637 return NO_ERROR;
4638 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004639 case 1021: { // Disable HWC virtual displays
4640 n = data.readInt32();
4641 mUseHwcVirtualDisplays = !n;
4642 return NO_ERROR;
4643 }
Romain Guy0147a172017-06-01 13:53:56 -07004644 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004645 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004646
4647 invalidateHwcGeometry();
4648 repaintEverything();
4649 return NO_ERROR;
4650 }
Romain Guy54f154a2017-10-24 21:40:32 +01004651 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004652 int32_t value = data.readInt32();
4653 if (value > 2) {
4654 return BAD_VALUE;
4655 }
4656 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4657 return BAD_VALUE;
4658 }
Romain Guy54f154a2017-10-24 21:40:32 +01004659
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004660 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004661 invalidateHwcGeometry();
4662 repaintEverything();
4663 return NO_ERROR;
4664 }
4665 case 1024: { // Is wide color gamut rendering/color management supported?
4666 reply->writeBool(hasWideColorDisplay);
4667 return NO_ERROR;
4668 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004669 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004670 n = data.readInt32();
4671 if (n) {
4672 ALOGV("LayerTracing enabled");
4673 mTracing.enable();
4674 doTracing("tracing.enable");
4675 reply->writeInt32(NO_ERROR);
4676 } else {
4677 ALOGV("LayerTracing disabled");
4678 status_t err = mTracing.disable();
4679 reply->writeInt32(err);
4680 }
4681 return NO_ERROR;
4682 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004683 case 1026: { // Get layer tracing status
4684 reply->writeBool(mTracing.isEnabled());
4685 return NO_ERROR;
4686 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004687 // Is a DisplayColorSetting supported?
4688 case 1027: {
4689 int32_t value = data.readInt32();
4690 switch (value) {
4691 case 0:
4692 reply->writeBool(hasWideColorDisplay);
4693 return NO_ERROR;
4694 case 1:
4695 reply->writeBool(true);
4696 return NO_ERROR;
4697 case 2:
4698 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4699 return NO_ERROR;
4700 default:
4701 return BAD_VALUE;
4702 }
4703 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004704 }
4705 }
4706 return err;
4707}
4708
Steven Thomas6d8110b2017-08-31 18:24:21 -07004709void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004710 android_atomic_or(1, &mRepaintEverything);
4711 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004712}
4713
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004714// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4715class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004716public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004717 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4718 ~WindowDisconnector() {
4719 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004720 }
4721
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004722private:
4723 ANativeWindow* mWindow;
4724 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004725};
4726
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004727status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4728 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4729 int32_t minLayerZ, int32_t maxLayerZ,
4730 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004731 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004732 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004733
chaviwa76b2712017-09-20 12:02:26 -07004734 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4735
4736 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004737 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4738
chaviwa76b2712017-09-20 12:02:26 -07004739 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4740
4741 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4742 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004743 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004744}
4745
4746status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004747 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004748 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004749 ATRACE_CALL();
4750
4751 class LayerRenderArea : public RenderArea {
4752 public:
Robert Carr578038f2018-03-09 12:25:24 -08004753 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4754 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004755 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004756 mLayer(layer),
4757 mCrop(crop),
4758 mFlinger(flinger),
4759 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004760 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004761 Rect getBounds() const override {
4762 const Layer::State& layerState(mLayer->getDrawingState());
4763 return Rect(layerState.active.w, layerState.active.h);
4764 }
4765 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4766 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4767 bool isSecure() const override { return false; }
4768 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004769 Rect getSourceCrop() const override {
4770 if (mCrop.isEmpty()) {
4771 return getBounds();
4772 } else {
4773 return mCrop;
4774 }
4775 }
4776 bool getWideColorSupport() const override { return false; }
4777 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004778
4779 class ReparentForDrawing {
4780 public:
4781 const sp<Layer>& oldParent;
4782 const sp<Layer>& newParent;
4783
4784 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4785 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004786 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004787 }
Robert Carr15eae092018-03-23 13:43:53 -07004788 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004789 };
4790
4791 void render(std::function<void()> drawLayers) override {
4792 if (!mChildrenOnly) {
4793 mTransform = mLayer->getTransform().inverse();
4794 drawLayers();
4795 } else {
4796 Rect bounds = getBounds();
4797 screenshotParentLayer =
4798 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4799 bounds.getWidth(), bounds.getHeight(), 0);
4800
4801 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4802 drawLayers();
4803 }
4804 }
chaviwa76b2712017-09-20 12:02:26 -07004805
chaviwa76b2712017-09-20 12:02:26 -07004806 private:
chaviw7206d492017-11-10 16:16:12 -08004807 const sp<Layer> mLayer;
4808 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004809
4810 // In the "childrenOnly" case we reparent the children to a screenshot
4811 // layer which has no properties set and which does not draw.
4812 sp<ContainerLayer> screenshotParentLayer;
4813 Transform mTransform;
4814
4815 SurfaceFlinger* mFlinger;
4816 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004817 };
4818
4819 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4820 auto parent = layerHandle->owner.promote();
4821
chaviw7206d492017-11-10 16:16:12 -08004822 if (parent == nullptr || parent->isPendingRemoval()) {
4823 ALOGE("captureLayers called with a removed parent");
4824 return NAME_NOT_FOUND;
4825 }
4826
Robert Carr578038f2018-03-09 12:25:24 -08004827 const int uid = IPCThreadState::self()->getCallingUid();
4828 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4829 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4830 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4831 return PERMISSION_DENIED;
4832 }
4833
chaviw7206d492017-11-10 16:16:12 -08004834 Rect crop(sourceCrop);
4835 if (sourceCrop.width() <= 0) {
4836 crop.left = 0;
4837 crop.right = parent->getCurrentState().active.w;
4838 }
4839
4840 if (sourceCrop.height() <= 0) {
4841 crop.top = 0;
4842 crop.bottom = parent->getCurrentState().active.h;
4843 }
4844
4845 int32_t reqWidth = crop.width() * frameScale;
4846 int32_t reqHeight = crop.height() * frameScale;
4847
Robert Carr578038f2018-03-09 12:25:24 -08004848 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004849
Robert Carr578038f2018-03-09 12:25:24 -08004850 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004851 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4852 if (!layer->isVisible()) {
4853 return;
Robert Carr578038f2018-03-09 12:25:24 -08004854 } else if (childrenOnly && layer == parent.get()) {
4855 return;
chaviwa76b2712017-09-20 12:02:26 -07004856 }
4857 visitor(layer);
4858 });
4859 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004860 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004861}
4862
4863status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4864 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004865 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004866 bool useIdentityTransform) {
4867 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004868
chaviwa76b2712017-09-20 12:02:26 -07004869 renderArea.updateDimensions();
4870
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004871 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4872 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4873 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4874 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004875
4876 // This mutex protects syncFd and captureResult for communication of the return values from the
4877 // main thread back to this Binder thread
4878 std::mutex captureMutex;
4879 std::condition_variable captureCondition;
4880 std::unique_lock<std::mutex> captureLock(captureMutex);
4881 int syncFd = -1;
4882 std::optional<status_t> captureResult;
4883
Robert Carr03480e22018-01-04 16:02:06 -08004884 const int uid = IPCThreadState::self()->getCallingUid();
4885 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4886
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004887 sp<LambdaMessage> message = new LambdaMessage([&]() {
4888 // If there is a refresh pending, bug out early and tell the binder thread to try again
4889 // after the refresh.
4890 if (mRefreshPending) {
4891 ATRACE_NAME("Skipping screenshot for now");
4892 std::unique_lock<std::mutex> captureLock(captureMutex);
4893 captureResult = std::make_optional<status_t>(EAGAIN);
4894 captureCondition.notify_one();
4895 return;
4896 }
4897
4898 status_t result = NO_ERROR;
4899 int fd = -1;
4900 {
4901 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004902 renderArea.render([&]() {
4903 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4904 useIdentityTransform, forSystem, &fd);
4905 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004906 }
4907
4908 {
4909 std::unique_lock<std::mutex> captureLock(captureMutex);
4910 syncFd = fd;
4911 captureResult = std::make_optional<status_t>(result);
4912 captureCondition.notify_one();
4913 }
4914 });
4915
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004916 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004917 if (result == NO_ERROR) {
4918 captureCondition.wait(captureLock, [&]() { return captureResult; });
4919 while (*captureResult == EAGAIN) {
4920 captureResult.reset();
4921 result = postMessageAsync(message);
4922 if (result != NO_ERROR) {
4923 return result;
4924 }
4925 captureCondition.wait(captureLock, [&]() { return captureResult; });
4926 }
4927 result = *captureResult;
4928 }
4929
4930 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004931 sync_wait(syncFd, -1);
4932 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004933 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004934
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004935 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004936}
4937
chaviwa76b2712017-09-20 12:02:26 -07004938void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4939 TraverseLayersFunction traverseLayers, bool yswap,
4940 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004941 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004942
Lloyd Pique144e1162017-12-20 16:44:52 -08004943 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004944
4945 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004946 const auto raWidth = renderArea.getWidth();
4947 const auto raHeight = renderArea.getHeight();
4948
4949 const auto reqWidth = renderArea.getReqWidth();
4950 const auto reqHeight = renderArea.getReqHeight();
4951 Rect sourceCrop = renderArea.getSourceCrop();
4952
4953 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4954 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004955
Dan Stozac1879002014-05-22 15:59:05 -07004956 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004957 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004958 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004959 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004960 }
4961
4962 // ensure that sourceCrop is inside screen
4963 if (sourceCrop.left < 0) {
4964 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4965 }
chaviwa76b2712017-09-20 12:02:26 -07004966 if (sourceCrop.right > raWidth) {
4967 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004968 }
4969 if (sourceCrop.top < 0) {
4970 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4971 }
chaviwa76b2712017-09-20 12:02:26 -07004972 if (sourceCrop.bottom > raHeight) {
4973 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004974 }
4975
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004976 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004977 if (renderArea.getWideColorSupport()) {
4978 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004979 }
4980 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004981
Mathias Agopian180f10d2013-04-10 22:55:41 -07004982 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004983 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004984
4985 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004986 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4987 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004988 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004989
chaviw50da5042018-04-09 13:49:37 -07004990 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004991 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004992 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004993
chaviwa76b2712017-09-20 12:02:26 -07004994 traverseLayers([&](Layer* layer) {
4995 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004996 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004997 if (filtering) layer->setFiltering(false);
4998 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004999}
5000
chaviwa76b2712017-09-20 12:02:26 -07005001status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5002 TraverseLayersFunction traverseLayers,
5003 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005004 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005005 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005006 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005007 ATRACE_CALL();
5008
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005009 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005010
5011 traverseLayers([&](Layer* layer) {
5012 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5013 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005014
Robert Carr03480e22018-01-04 16:02:06 -08005015 // We allow the system server to take screenshots of secure layers for
5016 // use in situations like the Screen-rotation animation and place
5017 // the impetus on WindowManager to not persist them.
5018 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005019 ALOGW("FB is protected: PERMISSION_DENIED");
5020 return PERMISSION_DENIED;
5021 }
5022
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005023 // this binds the given EGLImage as a framebuffer for the
5024 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005025 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005026 if (bufferBond.getStatus() != NO_ERROR) {
5027 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005028 return INVALID_OPERATION;
5029 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005030
Dan Stozaabcda352017-06-01 14:37:39 -07005031 // this will in fact render into our dequeued buffer
5032 // via an FBO, which means we didn't have to create
5033 // an EGLSurface and therefore we're not
5034 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005035 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005036
Dan Stozaabcda352017-06-01 14:37:39 -07005037 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005038 getRenderEngine().finish();
5039 *outSyncFd = -1;
5040
chaviwa76b2712017-09-20 12:02:26 -07005041 const auto reqWidth = renderArea.getReqWidth();
5042 const auto reqHeight = renderArea.getReqHeight();
5043
Dan Stozaabcda352017-06-01 14:37:39 -07005044 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5045 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005046 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005047 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005048 } else {
5049 base::unique_fd syncFd = getRenderEngine().flush();
5050 if (syncFd < 0) {
5051 getRenderEngine().finish();
5052 }
5053 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005054 }
5055
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005056 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005057}
5058
Mathias Agopiand5556842013-09-19 17:08:37 -07005059void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005060 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005061 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005062 for (size_t y = 0; y < h; y++) {
5063 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5064 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005065 if (p[x] != 0xFF000000) return;
5066 }
5067 }
chaviwa76b2712017-09-20 12:02:26 -07005068 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005069
Robert Carr2047fae2016-11-28 14:09:09 -08005070 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005071 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005072 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005073 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5074 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5075 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5076 static_cast<float>(state.color.a));
5077 i++;
5078 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005079 }
5080}
5081
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005082// ---------------------------------------------------------------------------
5083
Dan Stoza412903f2017-04-27 13:42:17 -07005084void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5085 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005086}
5087
Dan Stoza412903f2017-04-27 13:42:17 -07005088void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5089 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005090}
5091
chaviwa76b2712017-09-20 12:02:26 -07005092void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5093 int32_t maxLayerZ,
5094 const LayerVector::Visitor& visitor) {
5095 // We loop through the first level of layers without traversing,
5096 // as we need to interpret min/max layer Z in the top level Z space.
5097 for (const auto& layer : mDrawingState.layersSortedByZ) {
5098 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5099 continue;
5100 }
5101 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005102 // relative layers are traversed in Layer::traverseInZOrder
5103 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005104 continue;
5105 }
5106 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005107 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5108 return;
5109 }
chaviwa76b2712017-09-20 12:02:26 -07005110 if (!layer->isVisible()) {
5111 return;
5112 }
5113 visitor(layer);
5114 });
5115 }
5116}
5117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005118}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005119
Chia-I Wu30505fb2018-03-26 16:20:31 -07005120
Mathias Agopian3f844832013-08-07 21:24:32 -07005121#if defined(__gl_h_)
5122#error "don't include gl/gl.h in this file"
5123#endif
5124
5125#if defined(__gl2_h_)
5126#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005127#endif