blob: 46a1918a3fb1ee8660c2b9d5085eac92299a2e75 [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 Linfb069302018-04-25 14:34:31 -07001122 // At this point the DisplayDeivce should already be set up,
1123 // meaning the luminance information is already queried from
1124 // hardware composer and stored properly.
1125 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1126 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1127 capabilities.getDesiredMaxLuminance(),
1128 capabilities.getDesiredMaxAverageLuminance(),
1129 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001130
1131 return NO_ERROR;
1132}
1133
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001134status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1136 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001137
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138 if (mInjectVSyncs == enable) {
1139 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001140 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141
1142 if (enable) {
1143 ALOGV("VSync Injections enabled");
1144 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001145 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001146 mInjectorEventThread =
1147 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1148 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 } else {
1152 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001153 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 }
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 });
1158 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 return NO_ERROR;
1160}
1161
1162status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 Mutex::Autolock _l(mStateLock);
1164
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001165 if (!mInjectVSyncs) {
1166 ALOGE("VSync Injections not enabled");
1167 return BAD_VALUE;
1168 }
1169 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1170 ALOGV("Injecting VSync inside SurfaceFlinger");
1171 mVSyncInjector->onInjectSyncEvent(when);
1172 }
1173 return NO_ERROR;
1174}
1175
Lloyd Pique755e3192018-01-31 16:46:15 -08001176status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1177 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001178 IPCThreadState* ipc = IPCThreadState::self();
1179 const int pid = ipc->getCallingPid();
1180 const int uid = ipc->getCallingUid();
1181 if ((uid != AID_SHELL) &&
1182 !PermissionCache::checkPermission(sDump, pid, uid)) {
1183 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1184 return PERMISSION_DENIED;
1185 }
1186
1187 // Try to acquire a lock for 1s, fail gracefully
1188 const status_t err = mStateLock.timedLock(s2ns(1));
1189 const bool locked = (err == NO_ERROR);
1190 if (!locked) {
1191 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1192 return TIMED_OUT;
1193 }
1194
1195 outLayers->clear();
1196 mCurrentState.traverseInZOrder([&](Layer* layer) {
1197 outLayers->push_back(layer->getLayerDebugInfo());
1198 });
1199
1200 mStateLock.unlock();
1201 return NO_ERROR;
1202}
1203
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001204// ----------------------------------------------------------------------------
1205
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001206sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1207 ISurfaceComposer::VsyncSource vsyncSource) {
1208 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1209 return mSFEventThread->createEventConnection();
1210 } else {
1211 return mEventThread->createEventConnection();
1212 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001213}
1214
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216
1217void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001222 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001223}
1224
1225void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001230 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001235 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001240 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242 if (res == NO_ERROR) {
1243 msg->wait();
1244 }
1245 return res;
1246}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001248void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001249 do {
1250 waitForEvent();
1251 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001252}
1253
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254void SurfaceFlinger::enableHardwareVsync() {
1255 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1259 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001261 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262}
1263
Jesse Hall948fe0c2013-10-14 12:56:09 -07001264void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265 Mutex::Autolock _l(mHWVsyncLock);
1266
Jesse Hall948fe0c2013-10-14 12:56:09 -07001267 if (makeAvailable) {
1268 mHWVsyncAvailable = true;
1269 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 // Hardware vsync is not currently available, so abort the resync
1271 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001272 return;
1273 }
1274
David Sodman105b7dc2017-11-04 20:28:14 -07001275 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001276 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
1278 mPrimaryDispSync.reset();
1279 mPrimaryDispSync.setPeriod(period);
1280
1281 if (!mPrimaryHWVsyncEnabled) {
1282 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1284 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 mPrimaryHWVsyncEnabled = true;
1286 }
1287}
1288
Jesse Hall948fe0c2013-10-14 12:56:09 -07001289void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290 Mutex::Autolock _l(mHWVsyncLock);
1291 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1293 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 mPrimaryDispSync.endResync();
1295 mPrimaryHWVsyncEnabled = false;
1296 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (makeUnavailable) {
1298 mHWVsyncAvailable = false;
1299 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300}
1301
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302void SurfaceFlinger::resyncWithRateLimit() {
1303 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001304
1305 // No explicit locking is needed here since EventThread holds a lock while calling this method
1306 static nsecs_t sLastResyncAttempted = 0;
1307 const nsecs_t now = systemTime();
1308 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001310 }
Dan Stoza57164302017-05-08 14:03:54 -07001311 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312}
1313
Steven Thomasb02664d2017-07-26 18:48:28 -07001314void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1315 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001316 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001318 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 return;
1320 }
1321
1322 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001323 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001324 return;
1325 }
1326
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 { // Scope for the lock
1330 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001334 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001335
1336 if (needsHwVsync) {
1337 enableHardwareVsync();
1338 } else {
1339 disableHardwareVsync(false);
1340 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001341}
1342
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001344 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1345 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001346}
1347
Lloyd Pique715a2c12017-12-14 17:18:08 -08001348void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1349 HWC2::Connection connection) {
1350 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1351 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
Lloyd Piqueba04e622017-12-14 17:11:26 -08001353 // Ignore events that do not have the right sequenceId.
1354 if (sequenceId != getBE().mComposerSequenceId) {
1355 return;
1356 }
1357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Only lock if we're not on the main thread. This function is normally
1359 // called on a hwbinder thread, but for the primary display it's called on
1360 // the main thread with the state lock already held, so don't attempt to
1361 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363
Lloyd Pique715a2c12017-12-14 17:18:08 -08001364 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001366 if (std::this_thread::get_id() == mMainThreadId) {
1367 // Process all pending hot plug events immediately if we are on the main thread.
1368 processDisplayHotplugEventsLocked();
1369 }
1370
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Steven Thomasb02664d2017-07-26 18:48:28 -07001374void SurfaceFlinger::onRefreshReceived(int sequenceId,
1375 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001380 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001381}
1382
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 getHwComposer().setVsyncEnabled(disp,
1387 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001388}
1389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 // Clear the drawing state so that the logic inside of
1394 // handleTransactionLocked will fire. It will determine the delta between
1395 // mCurrentState and mDrawingState and re-apply all changes when we make the
1396 // transition.
1397 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001398 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399 mDisplays.clear();
1400}
1401
Steven Thomas050b2c82017-03-06 11:45:16 -08001402void SurfaceFlinger::updateVrFlinger() {
1403 if (!mVrFlinger)
1404 return;
1405 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001406 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001407 return;
1408 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409
David Sodman105b7dc2017-11-04 20:28:14 -07001410 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 ALOGE("Vr flinger is only supported for remote hardware composer"
1412 " service connections. Ignoring request to transition to vr"
1413 " flinger.");
1414 mVrFlingerRequestsDisplay = false;
1415 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 int currentDisplayPowerMode = getDisplayDeviceLocked(
1421 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001428 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001429 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1430 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001431 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
David Sodman105b7dc2017-11-04 20:28:14 -07001433 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1434 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001435
1436 if (vrFlingerRequestsDisplay) {
1437 mVrFlinger->GrantDisplayOwnership();
1438 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
1442 mVisibleRegionsDirty = true;
1443 invalidateHwcGeometry();
1444
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1447 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1448 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001449
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001451 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 const nsecs_t period = activeConfig->getVsyncPeriod();
1453 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Use phase of 0 since phase is not known.
1456 // Use latency of 0, which will snap to the ideal latency.
1457 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001458
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459 android_atomic_or(1, &mRepaintEverything);
1460 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001461}
1462
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001464 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001465 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001467 bool frameMissed = !mHadClientComposition &&
1468 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001469 (mPreviousPresentFence->getSignalTime() ==
1470 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001471 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001472 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001473 signalLayerUpdate();
1474 break;
1475 }
1476
Steven Thomas050b2c82017-03-06 11:45:16 -08001477 // Now that we're going to make it to the handleMessageTransaction()
1478 // call below it's safe to call updateVrFlinger(), which will
1479 // potentially trigger a display handoff.
1480 updateVrFlinger();
1481
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482 bool refreshNeeded = handleMessageTransaction();
1483 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001484 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001486 // Signal a refresh if a transaction modified the window state,
1487 // a new buffer was latched, or if HWC has requested a full
1488 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 signalRefresh();
1490 }
1491 break;
1492 }
1493 case MessageQueue::REFRESH: {
1494 handleMessageRefresh();
1495 break;
1496 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001497 }
1498}
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001501 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001503 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512}
1513
1514void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001517 mRefreshPending = false;
1518
Chia-I Wu30505fb2018-03-26 16:20:31 -07001519 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Chia-I Wu30505fb2018-03-26 16:20:31 -07001521 preComposition(refreshStartTime);
1522 rebuildLayerStacks();
1523 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001524 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001525 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001526 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001527 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001528 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001529
David Sodman105b7dc2017-11-04 20:28:14 -07001530 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001531
1532 mHadClientComposition = false;
1533 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1534 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1535 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001536 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001537 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001538 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001539
Dan Stoza9e56aa02015-11-02 13:00:03 -08001540 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543void SurfaceFlinger::doDebugFlashRegions()
1544{
1545 // is debugging enabled
1546 if (CC_LIKELY(!mDebugRegion))
1547 return;
1548
1549 const bool repaintEverything = mRepaintEverything;
1550 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1551 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001552 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 // transform the dirty region into this screen's coordinate space
1554 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1555 if (!dirtyRegion.isEmpty()) {
1556 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001557 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558
1559 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001561 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001562 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1563
Mathias Agopianda27af92012-09-13 18:17:13 -07001564 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 }
1566 }
1567 }
1568
1569 postFramebuffer();
1570
1571 if (mDebugRegion > 1) {
1572 usleep(mDebugRegion * 1000);
1573 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001574
Dan Stoza9e56aa02015-11-02 13:00:03 -08001575 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001576 auto& displayDevice = mDisplays[displayId];
1577 if (!displayDevice->isDisplayOn()) {
1578 continue;
1579 }
1580
David Sodman105b7dc2017-11-04 20:28:14 -07001581 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1582 ALOGE_IF(result != NO_ERROR,
1583 "prepareFrame for display %zd failed:"
1584 " %d (%s)",
1585 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001586 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587}
1588
Adrian Roos1e1a1282017-11-01 19:05:31 +01001589void SurfaceFlinger::doTracing(const char* where) {
1590 ATRACE_CALL();
1591 ATRACE_NAME(where);
1592 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001593 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001594 }
1595}
1596
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001597void SurfaceFlinger::logLayerStats() {
1598 ATRACE_CALL();
1599 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1600 int32_t hwcId = -1;
1601 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1602 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1603 if (displayDevice->isPrimary()) {
1604 hwcId = displayDevice->getHwcDisplayId();
1605 break;
1606 }
1607 }
1608 if (hwcId < 0) {
1609 ALOGE("LayerStats: Hmmm, no primary display?");
1610 return;
1611 }
1612 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1613 }
1614}
1615
Chia-I Wu30505fb2018-03-26 16:20:31 -07001616void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 ATRACE_CALL();
1619 ALOGV("preComposition");
1620
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001622 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001623 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624 needExtraInvalidate = true;
1625 }
Robert Carr2047fae2016-11-28 14:09:09 -08001626 });
1627
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 if (needExtraInvalidate) {
1629 signalLayerUpdate();
1630 }
1631}
1632
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633void SurfaceFlinger::updateCompositorTiming(
1634 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1635 std::shared_ptr<FenceTime>& presentFenceTime) {
1636 // Update queue of past composite+present times and determine the
1637 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001638 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001640 while (!getBE().mCompositePresentTimes.empty()) {
1641 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 // Cached values should have been updated before calling this method,
1643 // which helps avoid duplicate syscalls.
1644 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1645 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1646 break;
1647 }
1648 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001649 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 }
1651
1652 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001653 while (getBE().mCompositePresentTimes.size() > 16) {
1654 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 }
1656
Brian Andersond0010582017-03-07 13:20:31 -08001657 setCompositorTimingSnapped(
1658 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1659}
1660
1661void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1662 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 // Integer division and modulo round toward 0 not -inf, so we need to
1664 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001665 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1667 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1668
Brian Andersond0010582017-03-07 13:20:31 -08001669 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1670 if (idealLatency <= 0) {
1671 idealLatency = vsyncInterval;
1672 }
1673
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 // Snap the latency to a value that removes scheduling jitter from the
1675 // composition and present times, which often have >1ms of jitter.
1676 // Reducing jitter is important if an app attempts to extrapolate
1677 // something (such as user input) to an accurate diasplay time.
1678 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1679 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001680 nsecs_t bias = vsyncInterval / 2;
1681 int64_t extraVsyncs =
1682 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1683 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1684 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685
David Sodman99974d22017-11-28 12:04:33 -08001686 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1687 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1688 getBE().mCompositorTiming.interval = vsyncInterval;
1689 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690}
1691
Chia-I Wu30505fb2018-03-26 16:20:31 -07001692void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 ATRACE_CALL();
1695 ALOGV("postComposition");
1696
Brian Anderson3546a3f2016-07-14 11:51:14 -07001697 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001698 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001699 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001700 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 }
1702
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001703 // |mStateLock| not needed as we are on the main thread
1704 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705
David Sodman73beded2017-11-15 11:56:06 -08001706 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001708 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709 glCompositionDoneFenceTime =
1710 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001711 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712 } else {
1713 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1714 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715
David Sodman73beded2017-11-15 11:56:06 -08001716 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001717 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001718 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001719 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1722 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1723
Chia-I Wu30505fb2018-03-26 16:20:31 -07001724 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 // when we started doing work for this frame, but that should be okay
1726 // since updateCompositorTiming has snapping logic.
1727 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001728 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001729 CompositorTiming compositorTiming;
1730 {
David Sodman99974d22017-11-28 12:04:33 -08001731 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1732 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001733 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001734
Robert Carr2047fae2016-11-28 14:09:09 -08001735 mDrawingState.traverseInZOrder([&](Layer* layer) {
1736 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001737 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001738 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001739 recordBufferingStats(layer->getName().string(),
1740 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001741 }
Robert Carr2047fae2016-11-28 14:09:09 -08001742 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001743
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001744 if (presentFenceTime->isValid()) {
1745 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001746 enableHardwareVsync();
1747 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001748 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001749 }
1750 }
1751
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001752 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001753 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001754 enableHardwareVsync();
1755 }
1756 }
1757
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001758 if (mAnimCompositionPending) {
1759 mAnimCompositionPending = false;
1760
Brian Anderson4e606e32017-03-16 15:34:57 -07001761 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001764 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001765 // The HWC doesn't support present fences, so use the refresh
1766 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001767 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001768 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001769 mAnimFrameTracker.setActualPresentTime(presentTime);
1770 }
1771 mAnimFrameTracker.advanceFrame();
1772 }
Dan Stozab90cf072015-03-05 11:05:59 -08001773
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001774 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1775 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001776 return;
1777 }
1778
1779 nsecs_t currentTime = systemTime();
1780 if (mHasPoweredOff) {
1781 mHasPoweredOff = false;
1782 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001783 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001785 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1786 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001787 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001788 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001789 }
David Sodman4a36e932017-11-07 14:29:47 -08001790 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001791 }
David Sodman4a36e932017-11-07 14:29:47 -08001792 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001793}
1794
1795void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 ATRACE_CALL();
1797 ALOGV("rebuildLayerStacks");
1798
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001801 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 mVisibleRegionsDirty = false;
1803 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001804
Jeff Sharkey76488112017-02-27 14:15:18 -07001805 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1806 Region opaqueRegion;
1807 Region dirtyRegion;
1808 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001809 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1811 const Transform& tr(displayDevice->getTransform());
1812 const Rect bounds(displayDevice->getBounds());
1813 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001814 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001815
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001817 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001818 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1819 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001820 Region drawRegion(tr.transform(
1821 layer->visibleNonTransparentRegion));
1822 drawRegion.andSelf(bounds);
1823 if (!drawRegion.isEmpty()) {
1824 layersSortedByZ.add(layer);
1825 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001826 // Clear out the HWC layer if this layer was
1827 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001828 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001829 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001831 } else {
1832 // WM changes displayDevice->layerStack upon sleep/awake.
1833 // Here we make sure we delete the HWC layers even if
1834 // WM changed their layer stack.
1835 hwcLayerDestroyed = layer->destroyHwcLayer(
1836 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001837 }
1838
1839 // If a layer is not going to get a release fence because
1840 // it is invisible, but it is also going to release its
1841 // old buffer, add it to the list of layers needing
1842 // fences.
1843 if (hwcLayerDestroyed) {
1844 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1845 mLayersWithQueuedFrames.cend(), layer);
1846 if (found != mLayersWithQueuedFrames.cend()) {
1847 layersNeedingFences.add(layer);
1848 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001849 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 });
1851 }
1852 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001853 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001854 displayDevice->undefinedRegion.set(bounds);
1855 displayDevice->undefinedRegion.subtractSelf(
1856 tr.transform(opaqueRegion));
1857 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001858 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001859 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001861
Romain Guy0147a172017-06-01 13:53:56 -07001862mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001863 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001864 return mat4();
1865 }
1866
1867 // Rec.709 luma coefficients
1868 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001869 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001870 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001871 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1872 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1873 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001874 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1875 );
1876}
1877
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878// Returns a dataspace that fits all visible layers. The returned dataspace
1879// can only be one of
1880//
1881// - Dataspace::V0_SRGB
1882// - Dataspace::DISPLAY_P3
1883// - Dataspace::V0_SCRGB_LINEAR
1884// TODO(b/73825729) Add BT2020 data space.
1885ui::Dataspace SurfaceFlinger::getBestDataspace(
1886 const sp<const DisplayDevice>& displayDevice) const {
1887 Dataspace bestDataspace = Dataspace::V0_SRGB;
1888 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1889 switch (layer->getDataSpace()) {
1890 case Dataspace::V0_SCRGB:
1891 case Dataspace::V0_SCRGB_LINEAR:
1892 // return immediately
1893 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001894 case Dataspace::DISPLAY_P3:
1895 bestDataspace = Dataspace::DISPLAY_P3;
1896 break;
1897 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1898 // since SurfaceFlinger simulates HDR support now, it should honor
1899 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001900 case Dataspace::BT2020_PQ:
1901 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001902 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 return Dataspace::V0_SCRGB_LINEAR;
1904 }
1905 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001906 case Dataspace::BT2020_HLG:
1907 case Dataspace::BT2020_ITU_HLG:
1908 if (!displayDevice->hasHLGSupport()) {
1909 return Dataspace::V0_SCRGB_LINEAR;
1910 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 break;
1912 default:
1913 break;
1914 }
Romain Guy54f154a2017-10-24 21:40:32 +01001915 }
1916
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001918}
1919
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920// Pick the ColorMode / Dataspace for the display device.
1921// TODO(b/73825729) Add BT2020 color mode.
1922void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1923 ColorMode* outMode, Dataspace* outDataSpace) const {
1924 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1925 *outMode = ColorMode::NATIVE;
1926 *outDataSpace = Dataspace::UNKNOWN;
1927 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001928 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001929
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930 switch (getBestDataspace(displayDevice)) {
1931 case Dataspace::DISPLAY_P3:
1932 case Dataspace::V0_SCRGB_LINEAR:
1933 *outMode = ColorMode::DISPLAY_P3;
1934 *outDataSpace = Dataspace::DISPLAY_P3;
1935 break;
1936 default:
1937 *outMode = ColorMode::SRGB;
1938 *outDataSpace = Dataspace::V0_SRGB;
1939 break;
1940 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001941}
1942
Chia-I Wu30505fb2018-03-26 16:20:31 -07001943void SurfaceFlinger::setUpHWComposer() {
1944 ATRACE_CALL();
1945 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946
Jesse Hall028dc8f2013-08-20 16:35:32 -07001947 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001948 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001949 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1950 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1951
1952 // If nothing has changed (!dirty), don't recompose.
1953 // If something changed, but we don't currently have any visible layers,
1954 // and didn't when we last did a composition, then skip it this time.
1955 // The second rule does two things:
1956 // - When all layers are removed from a display, we'll emit one black
1957 // frame, then nothing more until we get new layers.
1958 // - When a display is created with a private layer stack, we won't
1959 // emit any black frames until a layer is added to the layer stack.
1960 bool mustRecompose = dirty && !(empty && wasEmpty);
1961
Dominik Laskowski281644e2018-04-19 15:47:35 -07001962 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001963 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1964 mustRecompose ? "doing" : "skipping",
1965 dirty ? "+" : "-",
1966 empty ? "+" : "-",
1967 wasEmpty ? "+" : "-");
1968
Dan Stoza71433162014-02-04 16:22:36 -08001969 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001970
1971 if (mustRecompose) {
1972 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1973 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001974 }
1975
Chia-I Wu30505fb2018-03-26 16:20:31 -07001976 // build the h/w work list
1977 if (CC_UNLIKELY(mGeometryInvalid)) {
1978 mGeometryInvalid = false;
1979 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1980 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1981 const auto hwcId = displayDevice->getHwcDisplayId();
1982 if (hwcId >= 0) {
1983 const Vector<sp<Layer>>& currentLayers(
1984 displayDevice->getVisibleLayersSortedByZ());
1985 for (size_t i = 0; i < currentLayers.size(); i++) {
1986 const auto& layer = currentLayers[i];
1987 if (!layer->hasHwcLayer(hwcId)) {
1988 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1989 layer->forceClientComposition(hwcId);
1990 continue;
1991 }
1992 }
1993
1994 layer->setGeometry(displayDevice, i);
1995 if (mDebugDisableHWC || mDebugRegion) {
1996 layer->forceClientComposition(hwcId);
1997 }
1998 }
1999 }
2000 }
2001 }
2002
2003
2004 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
2005
2006 // Set the per-frame data
2007 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2008 auto& displayDevice = mDisplays[displayId];
2009 const auto hwcId = displayDevice->getHwcDisplayId();
2010
2011 if (hwcId < 0) {
2012 continue;
2013 }
2014 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08002015 displayDevice->setColorTransform(colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002016 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
2017 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2018 "display %zd: %d", displayId, result);
2019 }
2020 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002021 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2022 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002023 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002024 layer->forceClientComposition(hwcId);
2025 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002026 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2027 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2028 !displayDevice->hasHLGSupport()) {
2029 layer->forceClientComposition(hwcId);
2030 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002031
2032 if (layer->getForceClientComposition(hwcId)) {
2033 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2034 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2035 continue;
2036 }
2037
2038 layer->setPerFrameData(displayDevice);
2039 }
2040
2041 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002042 ColorMode colorMode;
2043 Dataspace dataSpace;
2044 pickColorMode(displayDevice, &colorMode, &dataSpace);
2045 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002046 }
2047 }
2048
2049 mPreviousColorMatrix = colorMatrix;
2050
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002052 auto& displayDevice = mDisplays[displayId];
2053 if (!displayDevice->isDisplayOn()) {
2054 continue;
2055 }
2056
David Sodman105b7dc2017-11-04 20:28:14 -07002057 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2059 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002060 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002061}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002062
Mathias Agopiancd60f992012-08-16 16:28:27 -07002063void SurfaceFlinger::doComposition() {
2064 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 ALOGV("doComposition");
2066
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002067 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002068 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002069 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002070 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002071 // transform the dirty region into this screen's coordinate space
2072 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002073
2074 // repaint the framebuffer (if needed)
2075 doDisplayComposition(hw, dirtyRegion);
2076
Mathias Agopiancd60f992012-08-16 16:28:27 -07002077 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002078 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002079 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002080 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002081 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002082}
2083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084void SurfaceFlinger::postFramebuffer()
2085{
Mathias Agopian841cde52012-03-01 15:44:37 -08002086 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002088
Mathias Agopiana44b0412011-10-16 18:46:35 -07002089 const nsecs_t now = systemTime();
2090 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002091
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2093 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002094 if (!displayDevice->isDisplayOn()) {
2095 continue;
2096 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 const auto hwcId = displayDevice->getHwcDisplayId();
2098 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002099 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002100 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002101 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002102 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002104 // The layer buffer from the previous frame (if any) is released
2105 // by HWC only when the release fence from this frame (if any) is
2106 // signaled. Always get the release fence from HWC first.
2107 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002108 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002109
2110 // If the layer was client composited in the previous frame, we
2111 // need to merge with the previous client target acquire fence.
2112 // Since we do not track that, always merge with the current
2113 // client target acquire fence when it is available, even though
2114 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002116 releaseFence = Fence::merge("LayerRelease", releaseFence,
2117 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002118 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002119
David Sodmanb8af7922017-12-21 15:17:55 -08002120 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002121 }
Chia-I Wu83806892017-11-16 10:50:20 -08002122
2123 // We've got a list of layers needing fences, that are disjoint with
2124 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2125 // supply them with the present fence.
2126 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002127 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002128 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002129 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002130 }
2131 }
2132
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002134 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002135 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002136 }
2137
Mathias Agopiana44b0412011-10-16 18:46:35 -07002138 mLastSwapBufferTime = systemTime() - now;
2139 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002140
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002141 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002142 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2143 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2144 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2145 logFrameStats();
2146 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148}
2149
Mathias Agopian87baae12012-07-31 12:38:26 -07002150void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151{
Mathias Agopian841cde52012-03-01 15:44:37 -08002152 ATRACE_CALL();
2153
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002154 // here we keep a copy of the drawing state (that is the state that's
2155 // going to be overwritten by handleTransactionLocked()) outside of
2156 // mStateLock so that the side-effects of the State assignment
2157 // don't happen with mStateLock held (which can cause deadlocks).
2158 State drawingState(mDrawingState);
2159
Mathias Agopianca4d3602011-05-19 15:38:14 -07002160 Mutex::Autolock _l(mStateLock);
2161 const nsecs_t now = systemTime();
2162 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163
Mathias Agopianca4d3602011-05-19 15:38:14 -07002164 // Here we're guaranteed that some transaction flags are set
2165 // so we can call handleTransactionLocked() unconditionally.
2166 // We call getTransactionFlags(), which will also clear the flags,
2167 // with mStateLock held to guarantee that mCurrentState won't change
2168 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002169
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002170 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002171 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002172 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002173
Mathias Agopianca4d3602011-05-19 15:38:14 -07002174 mLastTransactionTime = systemTime() - now;
2175 mDebugInTransaction = 0;
2176 invalidateHwcGeometry();
2177 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002178}
2179
Lloyd Pique715a2c12017-12-14 17:18:08 -08002180DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002181 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002182 // Figure out whether the event is for the primary display or an
2183 // external display by matching the Hwc display id against one for a
2184 // connected display. If we did not find a match, we then check what
2185 // displays are not already connected to determine the type. If we don't
2186 // have a connected primary display, we assume the new display is meant to
2187 // be the primary display, and then if we don't have an external display,
2188 // we assume it is that.
2189 const auto primaryDisplayId =
2190 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2191 const auto externalDisplayId =
2192 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2193 if (primaryDisplayId && primaryDisplayId == display) {
2194 return DisplayDevice::DISPLAY_PRIMARY;
2195 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002196 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002197 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2198 return DisplayDevice::DISPLAY_PRIMARY;
2199 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2200 return DisplayDevice::DISPLAY_EXTERNAL;
2201 }
2202
2203 return DisplayDevice::DISPLAY_ID_INVALID;
2204}
2205
Lloyd Piqueba04e622017-12-14 17:11:26 -08002206void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2207 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002208 auto displayType = determineDisplayType(event.display, event.connection);
2209 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2210 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2211 continue;
2212 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002213
2214 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2215 ALOGE("External displays are not supported by the vr hardware composer.");
2216 continue;
2217 }
2218
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002219 const auto displayId =
2220 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2221 if (displayId) {
2222 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2223 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002224
2225 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002226 if (!mBuiltinDisplays[displayType].get()) {
2227 ALOGV("Creating built in display %d", displayType);
2228 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002229 DisplayDeviceState info;
2230 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002231 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2232 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002233 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002234 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2235 mInterceptor->saveDisplayCreation(info);
2236 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002237 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002238 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002239
Lloyd Piquefcd86612017-12-14 17:15:36 -08002240 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2241 if (idx >= 0) {
2242 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002243 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002244 mCurrentState.displays.removeItemsAt(idx);
2245 }
2246 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002247 }
2248
2249 processDisplayChangesLocked();
2250 }
2251
2252 mPendingHotplugEvents.clear();
2253}
2254
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2256 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2257 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258 bool hasWideColorGamut = false;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261 for (ColorMode colorMode : modes) {
2262 switch (colorMode) {
2263 case ColorMode::DISPLAY_P3:
2264 case ColorMode::ADOBE_RGB:
2265 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002266 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique99d3da52018-01-22 17:48:03 -08002269 default:
2270 break;
2271 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272
2273 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2274 colorMode);
2275 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2276 for (auto intent : renderIntents) {
2277 if (intent == RenderIntent::ENHANCE) {
2278 mBuiltinDisplaySupportsEnhance = true;
2279 break;
2280 }
2281 }
2282 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002283 }
2284 }
2285
Peiyong Lin62665892018-04-16 11:07:44 -07002286 HdrCapabilities hdrCapabilities;
2287 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002288
2289 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2290 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2291
2292 /*
2293 * Create our display's surface
2294 */
2295 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2296 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002297 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298 renderSurface->setNativeWindow(nativeWindow.get());
2299 const int displayWidth = renderSurface->queryWidth();
2300 const int displayHeight = renderSurface->queryHeight();
2301
2302 // Make sure that composition can never be stalled by a virtual display
2303 // consumer that isn't processing buffers fast enough. We have to do this
2304 // in two places:
2305 // * Here, in case the display is composed entirely by HWC.
2306 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2307 // window's swap interval in eglMakeCurrent, so they'll override the
2308 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002309 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2311 }
2312
2313 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002314 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315
2316 sp<DisplayDevice> hw =
2317 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2318 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002319 hasWideColorGamut, hdrCapabilities,
2320 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2321 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322
2323 if (maxFrameBufferAcquiredBuffers >= 3) {
2324 nativeWindowSurface->preallocateBuffers();
2325 }
2326
2327 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2329 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334 hw->setLayerStack(state.layerStack);
2335 hw->setProjection(state.orientation, state.viewport, state.frame);
2336 hw->setDisplayName(state.displayName);
2337
2338 return hw;
2339}
2340
Lloyd Pique347200f2017-12-14 17:00:15 -08002341void SurfaceFlinger::processDisplayChangesLocked() {
2342 // here we take advantage of Vector's copy-on-write semantics to
2343 // improve performance by skipping the transaction entirely when
2344 // know that the lists are identical
2345 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2346 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2347 if (!curr.isIdenticalTo(draw)) {
2348 mVisibleRegionsDirty = true;
2349 const size_t cc = curr.size();
2350 size_t dc = draw.size();
2351
2352 // find the displays that were removed
2353 // (ie: in drawing state but not in current state)
2354 // also handle displays that changed
2355 // (ie: displays that are in both lists)
2356 for (size_t i = 0; i < dc;) {
2357 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2358 if (j < 0) {
2359 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002360 // Call makeCurrent() on the primary display so we can
2361 // be sure that nothing associated with this display
2362 // is current.
2363 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2364 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2365 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2366 if (hw != nullptr) hw->disconnect(getHwComposer());
2367 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2368 mEventThread->onHotplugReceived(draw[i].type, false);
2369 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 } else {
2371 // this display is in both lists. see if something changed.
2372 const DisplayDeviceState& state(curr[j]);
2373 const wp<IBinder>& display(curr.keyAt(j));
2374 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2375 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2376 if (state_binder != draw_binder) {
2377 // changing the surface is like destroying and
2378 // recreating the DisplayDevice, so we just remove it
2379 // from the drawing state, so that it get re-added
2380 // below.
2381 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2382 if (hw != nullptr) hw->disconnect(getHwComposer());
2383 mDisplays.removeItem(display);
2384 mDrawingState.displays.removeItemsAt(i);
2385 dc--;
2386 // at this point we must loop to the next item
2387 continue;
2388 }
2389
2390 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2391 if (disp != nullptr) {
2392 if (state.layerStack != draw[i].layerStack) {
2393 disp->setLayerStack(state.layerStack);
2394 }
2395 if ((state.orientation != draw[i].orientation) ||
2396 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2397 disp->setProjection(state.orientation, state.viewport, state.frame);
2398 }
2399 if (state.width != draw[i].width || state.height != draw[i].height) {
2400 disp->setDisplaySize(state.width, state.height);
2401 }
2402 }
2403 }
2404 ++i;
2405 }
2406
2407 // find displays that were added
2408 // (ie: in current state but not in drawing state)
2409 for (size_t i = 0; i < cc; i++) {
2410 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2411 const DisplayDeviceState& state(curr[i]);
2412
2413 sp<DisplaySurface> dispSurface;
2414 sp<IGraphicBufferProducer> producer;
2415 sp<IGraphicBufferProducer> bqProducer;
2416 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002417 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002418
2419 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002420 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002421 // Virtual displays without a surface are dormant:
2422 // they have external state (layer stack, projection,
2423 // etc.) but no internal state (i.e. a DisplayDevice).
2424 if (state.surface != nullptr) {
2425 // Allow VR composer to use virtual displays.
2426 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2427 int width = 0;
2428 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2429 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2430 int height = 0;
2431 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2432 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2433 int intFormat = 0;
2434 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2435 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002436 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002437
2438 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2439 }
2440
2441 // TODO: Plumb requested format back up to consumer
2442
2443 sp<VirtualDisplaySurface> vds =
2444 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2445 bqProducer, bqConsumer,
2446 state.displayName);
2447
2448 dispSurface = vds;
2449 producer = vds;
2450 }
2451 } else {
2452 ALOGE_IF(state.surface != nullptr,
2453 "adding a supported display, but rendering "
2454 "surface is provided (%p), ignoring it",
2455 state.surface.get());
2456
2457 hwcId = state.type;
2458 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2459 producer = bqProducer;
2460 }
2461
2462 const wp<IBinder>& display(curr.keyAt(i));
2463 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464 mDisplays.add(display,
2465 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2466 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002467 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 mEventThread->onHotplugReceived(state.type, true);
2469 }
2470 }
2471 }
2472 }
2473 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002474
2475 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002476}
2477
Mathias Agopian87baae12012-07-31 12:38:26 -07002478void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002479{
Dan Stoza7dde5992015-05-22 09:51:44 -07002480 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002481 mCurrentState.traverseInZOrder([](Layer* layer) {
2482 layer->notifyAvailableFrames();
2483 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002484
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485 /*
2486 * Traversal of the children
2487 * (perform the transaction for each of them if needed)
2488 */
2489
Mathias Agopian3559b072012-08-15 13:46:03 -07002490 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002491 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002493 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494
2495 const uint32_t flags = layer->doTransaction(0);
2496 if (flags & Layer::eVisibleRegion)
2497 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002498 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499 }
2500
2501 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002502 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503 */
2504
Mathias Agopiane57f2922012-08-09 16:29:12 -07002505 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002507 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002510 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002511 // The transform hint might have changed for some layers
2512 // (either because a display has changed, or because a layer
2513 // as changed).
2514 //
2515 // Walk through all the layers in currentLayers,
2516 // and update their transform hint.
2517 //
2518 // If a layer is visible only on a single display, then that
2519 // display is used to calculate the hint, otherwise we use the
2520 // default display.
2521 //
2522 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2523 // the hint is set before we acquire a buffer from the surface texture.
2524 //
2525 // NOTE: layer transactions have taken place already, so we use their
2526 // drawing state. However, SurfaceFlinger's own transaction has not
2527 // happened yet, so we must use the current state layer list
2528 // (soon to become the drawing state list).
2529 //
2530 sp<const DisplayDevice> disp;
2531 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002532 bool first = true;
2533 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002534 // NOTE: we rely on the fact that layers are sorted by
2535 // layerStack first (so we don't have to traverse the list
2536 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002538 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002539 currentlayerStack = layerStack;
2540 // figure out if this layerstack is mirrored
2541 // (more than one display) if so, pick the default display,
2542 // if not, pick the only display it's on.
2543 disp.clear();
2544 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2545 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002546 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002547 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002548 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002549 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002550 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002551 break;
2552 }
2553 }
2554 }
2555 }
Chet Haase91d25932013-04-11 15:24:55 -07002556
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002557 if (disp == nullptr) {
2558 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2559 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002560
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002561 // could be null when this layer is using a layerStack
2562 // that is not visible on any display. Also can occur at
2563 // screen off/on times.
2564 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002565 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002566
2567 // disp can be null if there is no display available at all to get
2568 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002569 if (disp != nullptr) {
2570 layer->updateTransformHint(disp);
2571 }
Robert Carr2047fae2016-11-28 14:09:09 -08002572
2573 first = false;
2574 });
Mathias Agopian84300952012-11-21 16:02:13 -08002575 }
2576
2577
Mathias Agopian3559b072012-08-15 13:46:03 -07002578 /*
2579 * Perform our own transaction if needed
2580 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002581
2582 if (mLayersAdded) {
2583 mLayersAdded = false;
2584 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002585 mVisibleRegionsDirty = true;
2586 }
2587
2588 // some layers might have been removed, so
2589 // we need to update the regions they're exposing.
2590 if (mLayersRemoved) {
2591 mLayersRemoved = false;
2592 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002593 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002595 // this layer is not visible anymore
2596 // TODO: we could traverse the tree from front to back and
2597 // compute the actual visible region
2598 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002599 Region visibleReg;
2600 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002601 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002602 }
Robert Carr2047fae2016-11-28 14:09:09 -08002603 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 }
2605
2606 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002607
2608 updateCursorAsync();
2609}
2610
2611void SurfaceFlinger::updateCursorAsync()
2612{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2614 auto& displayDevice = mDisplays[displayId];
2615 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002616 continue;
2617 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002618
2619 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2620 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002621 }
2622 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002623}
2624
2625void SurfaceFlinger::commitTransaction()
2626{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002627 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002629 for (const auto& l : mLayersPendingRemoval) {
2630 recordBufferingStats(l->getName().string(),
2631 l->getOccupancyHistory(true));
2632 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002633 }
2634 mLayersPendingRemoval.clear();
2635 }
2636
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002637 // If this transaction is part of a window animation then the next frame
2638 // we composite should be considered an animation as well.
2639 mAnimCompositionPending = mAnimTransactionPending;
2640
Mathias Agopian4fec8732012-06-29 14:12:52 -07002641 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 mDrawingState.traverseInZOrder([](Layer* layer) {
2643 layer->commitChildList();
2644 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002645 mTransactionPending = false;
2646 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002647 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648}
2649
Chia-I Wuab0c3192017-08-01 11:29:00 -07002650void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002651 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652{
Mathias Agopian841cde52012-03-01 15:44:37 -08002653 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 Region aboveOpaqueLayers;
2657 Region aboveCoveredLayers;
2658 Region dirty;
2659
Mathias Agopian87baae12012-07-31 12:38:26 -07002660 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661
Robert Carr2047fae2016-11-28 14:09:09 -08002662 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002664 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Jesse Hall01e29052013-02-19 16:13:35 -08002666 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002667 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002668 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002669
Mathias Agopianab028732010-03-16 16:41:46 -07002670 /*
2671 * opaqueRegion: area of a surface that is fully opaque.
2672 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002674
2675 /*
2676 * visibleRegion: area of a surface that is visible on screen
2677 * and not fully transparent. This is essentially the layer's
2678 * footprint minus the opaque regions above it.
2679 * Areas covered by a translucent surface are considered visible.
2680 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002682
2683 /*
2684 * coveredRegion: area of a surface that is covered by all
2685 * visible regions above it (which includes the translucent areas).
2686 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002688
Jesse Halla8026d22012-09-25 13:25:04 -07002689 /*
2690 * transparentRegion: area of a surface that is hinted to be completely
2691 * transparent. This is only used to tell when the layer has no visible
2692 * non-transparent regions and can be removed from the layer list. It
2693 * does not affect the visibleRegion of this layer or any layers
2694 * beneath it. The hint may not be correct if apps don't respect the
2695 * SurfaceView restrictions (which, sadly, some don't).
2696 */
2697 Region transparentRegion;
2698
Mathias Agopianab028732010-03-16 16:41:46 -07002699
2700 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002701 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002702 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002705 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002706 if (!visibleRegion.isEmpty()) {
2707 // Remove the transparent area from the visible region
2708 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002709 if (tr.preserveRects()) {
2710 // transform the transparent region
2711 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002713 // transformation too complex, can't do the
2714 // transparent region optimization.
2715 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002716 }
Mathias Agopianab028732010-03-16 16:41:46 -07002717 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718
Mathias Agopianab028732010-03-16 16:41:46 -07002719 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002721 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002722 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2723 // the opaque region is the layer's footprint
2724 opaqueRegion = visibleRegion;
2725 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 }
2727 }
2728
Robert Carre5f4f692018-01-12 13:12:28 -08002729 if (visibleRegion.isEmpty()) {
2730 layer->clearVisibilityRegions();
2731 return;
2732 }
2733
Mathias Agopianab028732010-03-16 16:41:46 -07002734 // Clip the covered region to the visible region
2735 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2736
2737 // Update aboveCoveredLayers for next (lower) layer
2738 aboveCoveredLayers.orSelf(visibleRegion);
2739
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 // subtract the opaque region covered by the layers above us
2741 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
2743 // compute this layer's dirty region
2744 if (layer->contentDirty) {
2745 // we need to invalidate the whole region
2746 dirty = visibleRegion;
2747 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749 layer->contentDirty = false;
2750 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002751 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002752 * the exposed region consists of two components:
2753 * 1) what's VISIBLE now and was COVERED before
2754 * 2) what's EXPOSED now less what was EXPOSED before
2755 *
2756 * note that (1) is conservative, we start with the whole
2757 * visible region but only keep what used to be covered by
2758 * something -- which mean it may have been exposed.
2759 *
2760 * (2) handles areas that were not covered by anything but got
2761 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002762 */
Mathias Agopianab028732010-03-16 16:41:46 -07002763 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002764 const Region oldVisibleRegion = layer->visibleRegion;
2765 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002766 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2767 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 }
2769 dirty.subtractSelf(aboveOpaqueLayers);
2770
2771 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002772 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Mathias Agopianab028732010-03-16 16:41:46 -07002774 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002776
Jesse Halla8026d22012-09-25 13:25:04 -07002777 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 layer->setVisibleRegion(visibleRegion);
2779 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002780 layer->setVisibleNonTransparentRegion(
2781 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002782 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783
Mathias Agopian87baae12012-07-31 12:38:26 -07002784 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785}
2786
Chia-I Wuab0c3192017-08-01 11:29:00 -07002787void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002788 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002789 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002790 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002791 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002792 }
2793 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002794}
2795
Dan Stoza6b9454d2014-11-07 16:00:59 -08002796bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 ALOGV("handlePageFlip");
2799
Brian Andersond6927fb2016-07-23 23:37:30 -07002800 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801
Mathias Agopian4fec8732012-06-29 14:12:52 -07002802 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002803 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002804 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002805
2806 // Store the set of layers that need updates. This set must not change as
2807 // buffers are being latched, as this could result in a deadlock.
2808 // Example: Two producers share the same command stream and:
2809 // 1.) Layer 0 is latched
2810 // 2.) Layer 0 gets a new frame
2811 // 2.) Layer 1 gets a new frame
2812 // 3.) Layer 1 is latched.
2813 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2814 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002815 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 if (layer->hasQueuedFrame()) {
2817 frameQueued = true;
2818 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002819 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002820 } else {
2821 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002822 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002823 } else {
2824 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825 }
Robert Carr2047fae2016-11-28 14:09:09 -08002826 });
2827
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002829 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002830 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002831 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002832 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002833 newDataLatched = true;
2834 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002835 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002836
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002837 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838
2839 // If we will need to wake up at some time in the future to deal with a
2840 // queued frame that shouldn't be displayed during this vsync period, wake
2841 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002842 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002843 signalLayerUpdate();
2844 }
2845
2846 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002847 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848}
2849
Mathias Agopianad456f92011-01-13 17:53:01 -08002850void SurfaceFlinger::invalidateHwcGeometry()
2851{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002852 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002853}
2854
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002855
Fabien Sanglard830b8472016-11-30 16:35:58 -08002856void SurfaceFlinger::doDisplayComposition(
2857 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002858 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859{
Dan Stoza71433162014-02-04 16:22:36 -08002860 // We only need to actually compose the display if:
2861 // 1) It is being handled by hardware composer, which may need this to
2862 // keep its virtual display state machine in sync, or
2863 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002864 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002865 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002867 return;
2868 }
2869
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002871 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002872
2873 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002874 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875}
2876
Chia-I Wub02087d2017-11-09 10:19:54 -08002877bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002878{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002880
Chia-I Wub02087d2017-11-09 10:19:54 -08002881 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002882 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002884 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2885 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2886 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2887 HWC2::Capability::SkipClientColorTransform);
2888 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002889
2890 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002891 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2892 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002893 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002894 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002895 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002896 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002897 }
2898
Dan Stoza9e56aa02015-11-02 13:00:03 -08002899 if (hasClientComposition) {
2900 ALOGV("hasClientComposition");
2901
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002902 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002903 if (displayDevice->hasWideColorGamut()) {
2904 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002905 }
2906 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002907 getBE().mRenderEngine->setDisplayMaxLuminance(
2908 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002909
Chia-I Wu7f402902017-11-09 12:51:10 -08002910 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002911 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002912 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002913 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002914
2915 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002916 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002917 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2918 }
2919 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002920 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002921
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002922 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 // when using overlays, we assume a fully transparent framebuffer
2925 // NOTE: we could reduce how much we need to clear, for instance
2926 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002927 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002928 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002929 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002930 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002931 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002932 // we're left with the letterbox region
2933 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002935
2936 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002938
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002940 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002941 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002943 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002944 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002945
Dominik Laskowski281644e2018-04-19 15:47:35 -07002946 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002947 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002948 // scissor on the main display. It should never be needed
2949 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002950 const Rect& bounds(displayDevice->getBounds());
2951 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002952 if (scissor != bounds) {
2953 // scissor doesn't match the screen's dimensions, so we
2954 // need to clear everything outside of it and enable
2955 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002956
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002958 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002959 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002960 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002961 }
2962 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002963 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002964
Mathias Agopian85d751c2012-08-29 16:59:24 -07002965 /*
2966 * and then, render the layers targeted at the framebuffer
2967 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002968
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 ALOGV("Rendering client layers");
2970 const Transform& displayTransform = displayDevice->getTransform();
2971 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002972 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 bool firstLayer = true;
2974 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002975 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 displayTransform.transform(layer->visibleRegion)));
2977 ALOGV("Layer: %s", layer->getName().string());
2978 ALOGV(" Composition type: %s",
2979 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002980 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 switch (layer->getCompositionType(hwcId)) {
2982 case HWC2::Composition::Cursor:
2983 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002984 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002986 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002988 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002990 // never clear the very first layer since we're
2991 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002992 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002993 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002994 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002995 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002997 // Only apply saturation matrix layer that is legacy SRGB dataspace
2998 // when auto color mode is on.
2999 bool restore = false;
3000 mat4 savedMatrix;
3001 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3002 layer->isLegacySrgbDataSpace()) {
3003 savedMatrix =
3004 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3005 restore = true;
3006 }
chaviwa76b2712017-09-20 12:02:26 -07003007 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003008 if (restore) {
3009 getRenderEngine().setupColorTransform(savedMatrix);
3010 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003011 break;
3012 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003014 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003015 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 } else {
3017 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003018 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003020 }
3021 } else {
3022 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003024 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003026 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003027 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003028 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003029 }
3030 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003032 if (applyColorMatrix) {
3033 getRenderEngine().setupColorTransform(oldColorMatrix);
3034 }
3035
Mathias Agopianf45c5102012-10-24 16:29:17 -07003036 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003037 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003038 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Fabien Sanglard830b8472016-11-30 16:35:58 -08003041void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3042 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003043 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003044 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045}
3046
Dan Stoza7d89d062015-04-30 13:29:25 -07003047status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003048 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003049 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 const sp<Layer>& lbc,
3051 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003052{
Dan Stoza7d89d062015-04-30 13:29:25 -07003053 // add this layer to the current state list
3054 {
3055 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003056 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003057 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3058 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003059 return NO_MEMORY;
3060 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 if (parent == nullptr) {
3062 mCurrentState.layersSortedByZ.add(lbc);
3063 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003064 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003065 ALOGE("addClientLayer called with a removed parent");
3066 return NAME_NOT_FOUND;
3067 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003068 parent->addChild(lbc);
3069 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003070
Dan Stoza101d8dc2018-02-27 15:42:25 -08003071 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003072 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3073 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3074 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3075 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3076 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 mLayersAdded = true;
3078 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003079 }
3080
Mathias Agopian96f08192010-06-02 23:28:45 -07003081 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003082 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003083
Dan Stoza7d89d062015-04-30 13:29:25 -07003084 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003085}
3086
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003087status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003088 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003089 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3090}
Robert Carr7f9b8992017-03-10 11:08:39 -08003091
chaviwca27f252018-02-06 16:46:39 -08003092status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3093 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003094 if (layer->isPendingRemoval()) {
3095 return NO_ERROR;
3096 }
3097
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003099 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003100 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003101 if (topLevelOnly) {
3102 return NO_ERROR;
3103 }
3104
Chia-I Wu98f1c102017-05-30 14:54:08 -07003105 sp<Layer> ancestor = p;
3106 while (ancestor->getParent() != nullptr) {
3107 ancestor = ancestor->getParent();
3108 }
3109 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3110 ALOGE("removeLayer called with a layer whose parent has been removed");
3111 return NAME_NOT_FOUND;
3112 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003113
3114 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003115 } else {
3116 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003117 }
3118
Robert Carr136e2f62017-02-08 17:54:29 -08003119 // As a matter of normal operation, the LayerCleaner will produce a second
3120 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3121 // so we will succeed in promoting it, but it's already been removed
3122 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3123 // otherwise something has gone wrong and we are leaking the layer.
3124 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3126 layer->getName().string(),
3127 (p != nullptr) ? p->getName().string() : "no-parent");
3128 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003129 } else if (index < 0) {
3130 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003131 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003132
Chia-I Wuc6657022017-08-15 11:18:17 -07003133 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 mLayersPendingRemoval.add(layer);
3135 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003136 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137 setTransactionFlags(eTransactionNeeded);
3138 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139}
3140
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003141uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003142 return android_atomic_release_load(&mTransactionFlags);
3143}
3144
Mathias Agopian3f844832013-08-07 21:24:32 -07003145uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3147}
3148
Mathias Agopian3f844832013-08-07 21:24:32 -07003149uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003150 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3151}
3152
3153uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3154 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003156 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003158 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159 }
3160 return old;
3161}
3162
chaviwca27f252018-02-06 16:46:39 -08003163bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3164 for (const ComposerState& state : states) {
3165 // Here we need to check that the interface we're given is indeed
3166 // one of our own. A malicious client could give us a nullptr
3167 // IInterface, or one of its own or even one of our own but a
3168 // different type. All these situations would cause us to crash.
3169 if (state.client == nullptr) {
3170 return true;
3171 }
3172
3173 sp<IBinder> binder = IInterface::asBinder(state.client);
3174 if (binder == nullptr) {
3175 return true;
3176 }
3177
3178 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3179 return true;
3180 }
3181 }
3182 return false;
3183}
3184
Mathias Agopian8b33f032012-07-24 20:43:54 -07003185void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003186 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003187 const Vector<DisplayState>& displays,
3188 uint32_t flags)
3189{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003190 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003191 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003192 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003193
chaviwca27f252018-02-06 16:46:39 -08003194 if (containsAnyInvalidClientState(states)) {
3195 return;
3196 }
3197
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003198 if (flags & eAnimation) {
3199 // For window updates that are part of an animation we must wait for
3200 // previous animation "frames" to be handled.
3201 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003202 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003203 if (CC_UNLIKELY(err != NO_ERROR)) {
3204 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003205 // caller after a few seconds.
3206 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3207 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003208 mAnimTransactionPending = false;
3209 break;
3210 }
3211 }
3212 }
3213
chaviwca27f252018-02-06 16:46:39 -08003214 for (const DisplayState& display : displays) {
3215 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003216 }
3217
chaviwca27f252018-02-06 16:46:39 -08003218 for (const ComposerState& state : states) {
3219 transactionFlags |= setClientStateLocked(state);
3220 }
3221
3222 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3223 // as destroyed should only occur after setting all other states. This is to allow for a
3224 // child re-parent to happen before marking its original parent as destroyed (which would
3225 // then mark the child as destroyed).
3226 for (const ComposerState& state : states) {
3227 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003228 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003229
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003230 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3231 // anyway. This can be used as a flush mechanism for previous async transactions.
3232 // Empty animation transaction can be used to simulate back-pressure, so also force a
3233 // transaction for empty animation transactions.
3234 if (transactionFlags == 0 &&
3235 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003236 transactionFlags = eTransactionNeeded;
3237 }
3238
Mathias Agopian386aa982011-11-07 21:58:03 -08003239 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003240 if (mInterceptor->isEnabled()) {
3241 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003242 }
Irvel468051e2016-06-13 16:44:44 -07003243
Mathias Agopian386aa982011-11-07 21:58:03 -08003244 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003245 const auto start = (flags & eEarlyWakeup)
3246 ? VSyncModulator::TransactionStart::EARLY
3247 : VSyncModulator::TransactionStart::NORMAL;
3248 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003249
3250 // if this is a synchronous transaction, wait for it to take effect
3251 // before returning.
3252 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003253 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003254 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003255 if (flags & eAnimation) {
3256 mAnimTransactionPending = true;
3257 }
3258 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003259 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3260 if (CC_UNLIKELY(err != NO_ERROR)) {
3261 // just in case something goes wrong in SF, return to the
3262 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3264 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003265 break;
3266 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003267 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 }
3269}
3270
Mathias Agopiane57f2922012-08-09 16:29:12 -07003271uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3272{
Jesse Hall9a143922012-10-04 16:29:19 -07003273 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3274 if (dpyIdx < 0)
3275 return 0;
3276
Mathias Agopiane57f2922012-08-09 16:29:12 -07003277 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003278 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003279 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 const uint32_t what = s.what;
3281 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003282 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003283 disp.surface = s.surface;
3284 flags |= eDisplayTransactionNeeded;
3285 }
3286 }
3287 if (what & DisplayState::eLayerStackChanged) {
3288 if (disp.layerStack != s.layerStack) {
3289 disp.layerStack = s.layerStack;
3290 flags |= eDisplayTransactionNeeded;
3291 }
3292 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003293 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003294 if (disp.orientation != s.orientation) {
3295 disp.orientation = s.orientation;
3296 flags |= eDisplayTransactionNeeded;
3297 }
3298 if (disp.frame != s.frame) {
3299 disp.frame = s.frame;
3300 flags |= eDisplayTransactionNeeded;
3301 }
3302 if (disp.viewport != s.viewport) {
3303 disp.viewport = s.viewport;
3304 flags |= eDisplayTransactionNeeded;
3305 }
3306 }
Michael Lentine47e45402014-07-18 15:34:25 -07003307 if (what & DisplayState::eDisplaySizeChanged) {
3308 if (disp.width != s.width) {
3309 disp.width = s.width;
3310 flags |= eDisplayTransactionNeeded;
3311 }
3312 if (disp.height != s.height) {
3313 disp.height = s.height;
3314 flags |= eDisplayTransactionNeeded;
3315 }
3316 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003317 }
3318 return flags;
3319}
3320
chaviwca27f252018-02-06 16:46:39 -08003321uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3322 const layer_state_t& s = composerState.state;
3323 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3324
Mathias Agopian13127d82013-03-05 17:47:11 -08003325 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003326 if (layer == nullptr) {
3327 return 0;
3328 }
3329
3330 if (layer->isPendingRemoval()) {
3331 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3332 return 0;
3333 }
3334
3335 uint32_t flags = 0;
3336
3337 const uint32_t what = s.what;
3338 bool geometryAppliesWithResize =
3339 what & layer_state_t::eGeometryAppliesWithResize;
3340 if (what & layer_state_t::ePositionChanged) {
3341 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3342 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003343 }
chaviw8b3871a2017-11-01 17:41:01 -07003344 }
3345 if (what & layer_state_t::eLayerChanged) {
3346 // NOTE: index needs to be calculated before we update the state
3347 const auto& p = layer->getParent();
3348 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003349 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003350 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003351 mCurrentState.layersSortedByZ.removeAt(idx);
3352 mCurrentState.layersSortedByZ.add(layer);
3353 // we need traversal (state changed)
3354 // AND transaction (list changed)
3355 flags |= eTransactionNeeded|eTraversalNeeded;
3356 }
chaviw8b3871a2017-11-01 17:41:01 -07003357 } else {
3358 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003359 flags |= eTransactionNeeded|eTraversalNeeded;
3360 }
3361 }
chaviw8b3871a2017-11-01 17:41:01 -07003362 }
3363 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003364 // NOTE: index needs to be calculated before we update the state
3365 const auto& p = layer->getParent();
3366 if (p == nullptr) {
3367 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3368 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3369 mCurrentState.layersSortedByZ.removeAt(idx);
3370 mCurrentState.layersSortedByZ.add(layer);
3371 // we need traversal (state changed)
3372 // AND transaction (list changed)
3373 flags |= eTransactionNeeded|eTraversalNeeded;
3374 }
3375 } else {
3376 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3377 flags |= eTransactionNeeded|eTraversalNeeded;
3378 }
chaviw8b3871a2017-11-01 17:41:01 -07003379 }
3380 }
3381 if (what & layer_state_t::eSizeChanged) {
3382 if (layer->setSize(s.w, s.h)) {
3383 flags |= eTraversalNeeded;
3384 }
3385 }
3386 if (what & layer_state_t::eAlphaChanged) {
3387 if (layer->setAlpha(s.alpha))
3388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eColorChanged) {
3391 if (layer->setColor(s.color))
3392 flags |= eTraversalNeeded;
3393 }
3394 if (what & layer_state_t::eMatrixChanged) {
3395 if (layer->setMatrix(s.matrix))
3396 flags |= eTraversalNeeded;
3397 }
3398 if (what & layer_state_t::eTransparentRegionChanged) {
3399 if (layer->setTransparentRegionHint(s.transparentRegion))
3400 flags |= eTraversalNeeded;
3401 }
3402 if (what & layer_state_t::eFlagsChanged) {
3403 if (layer->setFlags(s.flags, s.mask))
3404 flags |= eTraversalNeeded;
3405 }
3406 if (what & layer_state_t::eCropChanged) {
3407 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3408 flags |= eTraversalNeeded;
3409 }
3410 if (what & layer_state_t::eFinalCropChanged) {
3411 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3412 flags |= eTraversalNeeded;
3413 }
3414 if (what & layer_state_t::eLayerStackChanged) {
3415 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3416 // We only allow setting layer stacks for top level layers,
3417 // everything else inherits layer stack from its parent.
3418 if (layer->hasParent()) {
3419 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3420 layer->getName().string());
3421 } else if (idx < 0) {
3422 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3423 "that also does not appear in the top level layer list. Something"
3424 " has gone wrong.", layer->getName().string());
3425 } else if (layer->setLayerStack(s.layerStack)) {
3426 mCurrentState.layersSortedByZ.removeAt(idx);
3427 mCurrentState.layersSortedByZ.add(layer);
3428 // we need traversal (state changed)
3429 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003430 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003431 }
3432 }
3433 if (what & layer_state_t::eDeferTransaction) {
3434 if (s.barrierHandle != nullptr) {
3435 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3436 } else if (s.barrierGbp != nullptr) {
3437 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3438 if (authenticateSurfaceTextureLocked(gbp)) {
3439 const auto& otherLayer =
3440 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3441 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3442 } else {
3443 ALOGE("Attempt to defer transaction to to an"
3444 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003445 }
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 // We don't trigger a traversal here because if no other state is
3448 // changed, we don't want this to cause any more work
3449 }
3450 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003451 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003452 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003453 if (!hadParent) {
3454 mCurrentState.layersSortedByZ.remove(layer);
3455 }
chaviw8b3871a2017-11-01 17:41:01 -07003456 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 }
3459 if (what & layer_state_t::eReparentChildren) {
3460 if (layer->reparentChildren(s.reparentHandle)) {
3461 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003462 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003463 }
chaviw8b3871a2017-11-01 17:41:01 -07003464 if (what & layer_state_t::eDetachChildren) {
3465 layer->detachChildren();
3466 }
3467 if (what & layer_state_t::eOverrideScalingModeChanged) {
3468 layer->setOverrideScalingMode(s.overrideScalingMode);
3469 // We don't trigger a traversal here because if no other state is
3470 // changed, we don't want this to cause any more work
3471 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003472 return flags;
3473}
3474
chaviwca27f252018-02-06 16:46:39 -08003475void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3476 const layer_state_t& state = composerState.state;
3477 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3478
3479 sp<Layer> layer(client->getLayerUser(state.surface));
3480 if (layer == nullptr) {
3481 return;
3482 }
3483
3484 if (layer->isPendingRemoval()) {
3485 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3486 return;
3487 }
3488
3489 if (state.what & layer_state_t::eDestroySurface) {
3490 removeLayerLocked(mStateLock, layer);
3491 }
3492}
3493
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003494status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003495 const String8& name,
3496 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003497 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003498 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003499 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003501 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003502 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003503 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003504 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003505 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003506
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507 status_t result = NO_ERROR;
3508
3509 sp<Layer> layer;
3510
Cody Northropbc755282017-03-31 12:00:08 -06003511 String8 uniqueName = getUniqueLayerName(name);
3512
Mathias Agopian3165cc22012-08-08 19:42:09 -07003513 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3514 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003515 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003516 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 break;
chaviw13fdc492017-06-27 12:40:18 -07003520 case ISurfaceComposerClient::eFXSurfaceColor:
3521 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003522 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003523 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003524 break;
3525 default:
3526 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 break;
3528 }
3529
Dan Stoza7d89d062015-04-30 13:29:25 -07003530 if (result != NO_ERROR) {
3531 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003533
Chia-I Wuab0c3192017-08-01 11:29:00 -07003534 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3535 // TODO b/64227542
3536 if (windowType == 441731) {
3537 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3538 layer->setPrimaryDisplayOnly();
3539 }
3540
Albert Chaulk479c60c2017-01-27 14:21:34 -05003541 layer->setInfo(windowType, ownerUid);
3542
Robert Carr1f0a16a2016-10-24 16:27:39 -07003543 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003544 if (result != NO_ERROR) {
3545 return result;
3546 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003547 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003548
3549 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003550 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551}
3552
Cody Northropbc755282017-03-31 12:00:08 -06003553String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3554{
3555 bool matchFound = true;
3556 uint32_t dupeCounter = 0;
3557
3558 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3559 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3560
3561 // Loop over layers until we're sure there is no matching name
3562 while (matchFound) {
3563 matchFound = false;
3564 mDrawingState.traverseInZOrder([&](Layer* layer) {
3565 if (layer->getName() == uniqueName) {
3566 matchFound = true;
3567 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3568 }
3569 });
3570 }
3571
3572 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3573
3574 return uniqueName;
3575}
3576
David Sodman0c69cad2017-08-21 12:12:51 -07003577status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003578 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3579 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580{
3581 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003582 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 case PIXEL_FORMAT_TRANSPARENT:
3584 case PIXEL_FORMAT_TRANSLUCENT:
3585 format = PIXEL_FORMAT_RGBA_8888;
3586 break;
3587 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003588 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 break;
3590 }
3591
David Sodman0c69cad2017-08-21 12:12:51 -07003592 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3593 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003595 *handle = layer->getHandle();
3596 *gbp = layer->getProducer();
3597 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599
David Sodman0c69cad2017-08-21 12:12:51 -07003600 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003601 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602}
3603
chaviw13fdc492017-06-27 12:40:18 -07003604status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003606 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607{
chaviw13fdc492017-06-27 12:40:18 -07003608 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003611}
3612
Mathias Agopianac9fa422013-02-11 16:40:36 -08003613status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614{
Robert Carr9524cb32017-02-13 11:32:32 -08003615 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003616 status_t err = NO_ERROR;
3617 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003618 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003619 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003620 err = removeLayer(l);
3621 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3622 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003623 }
3624 return err;
3625}
3626
Mathias Agopian13127d82013-03-05 17:47:11 -08003627status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003628{
Mathias Agopian67106042013-03-14 19:18:13 -07003629 // called by ~LayerCleaner() when all references to the IBinder (handle)
3630 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003631 sp<Layer> l = layer.promote();
3632 if (l == nullptr) {
3633 // The layer has already been removed, carry on
3634 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003635 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003636 // If we have a parent, then we can continue to live as long as it does.
3637 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638}
3639
Mathias Agopianb60314a2012-04-10 22:09:54 -07003640// ---------------------------------------------------------------------------
3641
Andy McFadden13a082e2012-08-24 10:16:42 -07003642void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003643 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003644 Vector<ComposerState> state;
3645 Vector<DisplayState> displays;
3646 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003647 d.what = DisplayState::eDisplayProjectionChanged |
3648 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003649 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003650 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003651 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003652 d.frame.makeInvalid();
3653 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003654 d.width = 0;
3655 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003656 displays.add(d);
3657 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003658 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3659 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003660
David Sodman105b7dc2017-11-04 20:28:14 -07003661 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003662 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003663 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003664
Brian Andersond0010582017-03-07 13:20:31 -08003665 // Use phase of 0 since phase is not known.
3666 // Use latency of 0, which will snap to the ideal latency.
3667 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003668}
3669
3670void SurfaceFlinger::initializeDisplays() {
3671 class MessageScreenInitialized : public MessageBase {
3672 SurfaceFlinger* flinger;
3673 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003674 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003675 virtual bool handler() {
3676 flinger->onInitializeDisplays();
3677 return true;
3678 }
3679 };
3680 sp<MessageBase> msg = new MessageScreenInitialized(this);
3681 postMessageAsync(msg); // we may be called from main thread, use async message
3682}
3683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003685 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003686 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3687 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003688 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003689
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003690 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003691 return;
3692 }
3693
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003694 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003695 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 ALOGW("Trying to set power mode for virtual display");
3697 return;
3698 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003699
Lloyd Pique4dccc412018-01-22 17:21:36 -08003700 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003701 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003702 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3703 if (idx < 0) {
3704 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3705 return;
3706 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003707 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003708 }
3709
Dominik Laskowski281644e2018-04-19 15:47:35 -07003710 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003712 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003713 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003714 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715 // FIXME: eventthread only knows about the main display right now
3716 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003717 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003721 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003722 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003723
3724 struct sched_param param = {0};
3725 param.sched_priority = 1;
3726 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3727 ALOGW("Couldn't set SCHED_FIFO on display on");
3728 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003730 // Turn off the display
3731 struct sched_param param = {0};
3732 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3733 ALOGW("Couldn't set SCHED_OTHER on display off");
3734 }
3735
Dominik Laskowski281644e2018-04-19 15:47:35 -07003736 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003737 disableHardwareVsync(true); // also cancels any in-progress resync
3738
Mathias Agopiancde87a32012-09-13 14:09:01 -07003739 // FIXME: eventthread only knows about the main display right now
3740 mEventThread->onScreenReleased();
3741 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003742
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003743 getHwComposer().setPowerMode(type, mode);
3744 mVisibleRegionsDirty = true;
3745 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003746 } else if (mode == HWC_POWER_MODE_DOZE ||
3747 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003748 // Update display while dozing
3749 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003750 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003751 // FIXME: eventthread only knows about the main display right now
3752 mEventThread->onScreenAcquired();
3753 resyncToHardwareVsync(true);
3754 }
3755 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3756 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003757 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003758 disableHardwareVsync(true); // also cancels any in-progress resync
3759 // FIXME: eventthread only knows about the main display right now
3760 mEventThread->onScreenReleased();
3761 }
3762 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003764 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003766 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003767 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003768}
3769
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3771 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003772 SurfaceFlinger& mFlinger;
3773 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 MessageSetPowerMode(SurfaceFlinger& flinger,
3777 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3778 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003779 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003781 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003783 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003784 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785 ALOGW("Attempt to set power mode = %d for virtual display",
3786 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003787 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003788 mFlinger.setPowerModeInternal(
3789 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003790 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003791 return true;
3792 }
3793 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003795 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003796}
3797
3798// ---------------------------------------------------------------------------
3799
Lloyd Pique755e3192018-01-31 16:46:15 -08003800status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3801 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003803
Mathias Agopianbd115332013-04-18 16:41:04 -07003804 IPCThreadState* ipc = IPCThreadState::self();
3805 const int pid = ipc->getCallingPid();
3806 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003807
Mathias Agopianbd115332013-04-18 16:41:04 -07003808 if ((uid != AID_SHELL) &&
3809 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003810 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003811 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003812 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003813 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003814 // (this would indicate SF is stuck, but we want to be able to
3815 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003816 status_t err = mStateLock.timedLock(s2ns(1));
3817 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003818 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003819 result.appendFormat(
3820 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3821 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003822 }
3823
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003824 bool dumpAll = true;
3825 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003826 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003827
3828 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003829 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003830 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3831 dumpAll = false;
3832 }
3833
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003835 if ((index < numArgs) &&
3836 (args[index] == String16("--list"))) {
3837 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003838 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003839 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 }
3841
3842 if ((index < numArgs) &&
3843 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003844 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003845 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003846 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003848
3849 if ((index < numArgs) &&
3850 (args[index] == String16("--latency-clear"))) {
3851 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003852 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003853 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003854 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003855
3856 if ((index < numArgs) &&
3857 (args[index] == String16("--dispsync"))) {
3858 index++;
3859 mPrimaryDispSync.dump(result);
3860 dumpAll = false;
3861 }
Dan Stozab90cf072015-03-05 11:05:59 -08003862
3863 if ((index < numArgs) &&
3864 (args[index] == String16("--static-screen"))) {
3865 index++;
3866 dumpStaticScreenStats(result);
3867 dumpAll = false;
3868 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003869
3870 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003871 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003872 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003873 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003874 dumpAll = false;
3875 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003876
3877 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3878 index++;
3879 dumpWideColorInfo(result);
3880 dumpAll = false;
3881 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003882
3883 if ((index < numArgs) &&
3884 (args[index] == String16("--enable-layer-stats"))) {
3885 index++;
3886 mLayerStats.enable();
3887 dumpAll = false;
3888 }
3889
3890 if ((index < numArgs) &&
3891 (args[index] == String16("--disable-layer-stats"))) {
3892 index++;
3893 mLayerStats.disable();
3894 dumpAll = false;
3895 }
3896
3897 if ((index < numArgs) &&
3898 (args[index] == String16("--clear-layer-stats"))) {
3899 index++;
3900 mLayerStats.clear();
3901 dumpAll = false;
3902 }
3903
3904 if ((index < numArgs) &&
3905 (args[index] == String16("--dump-layer-stats"))) {
3906 index++;
3907 mLayerStats.dump(result);
3908 dumpAll = false;
3909 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003910
3911 if ((index < numArgs) &&
3912 (args[index] == String16("--display-identification"))) {
3913 index++;
3914 dumpDisplayIdentificationData(result);
3915 dumpAll = false;
3916 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003918
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003919 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003921 }
3922
Mathias Agopian9795c422009-08-26 16:36:26 -07003923 if (locked) {
3924 mStateLock.unlock();
3925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 }
3927 write(fd, result.string(), result.size());
3928 return NO_ERROR;
3929}
3930
Dan Stozac7014012014-02-14 15:03:43 -08003931void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3932 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003933{
Robert Carr2047fae2016-11-28 14:09:09 -08003934 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003935 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003936 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003937}
3938
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003940 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003941{
3942 String8 name;
3943 if (index < args.size()) {
3944 name = String8(args[index]);
3945 index++;
3946 }
3947
David Sodman105b7dc2017-11-04 20:28:14 -07003948 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003949 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003950 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003951
3952 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003953 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003954 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003955 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003956 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003957 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003958 }
Robert Carr2047fae2016-11-28 14:09:09 -08003959 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960 }
3961}
3962
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003964 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965{
3966 String8 name;
3967 if (index < args.size()) {
3968 name = String8(args[index]);
3969 index++;
3970 }
3971
Robert Carr2047fae2016-11-28 14:09:09 -08003972 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003973 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003974 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003975 }
Robert Carr2047fae2016-11-28 14:09:09 -08003976 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003977
Svetoslavd85084b2014-03-20 10:28:31 -07003978 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979}
3980
Jamie Gennis6547ff42013-07-16 20:12:42 -07003981// This should only be called from the main thread. Otherwise it would need
3982// the lock and should use mCurrentState rather than mDrawingState.
3983void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003984 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003985 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003986 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003987
3988 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3989}
3990
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003991void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003992{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003993 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003994
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003995 if (isLayerTripleBufferingDisabled())
3996 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003997
3998 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003999 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004000 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004001 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004002 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4003 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004004 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004005}
4006
Dan Stozab90cf072015-03-05 11:05:59 -08004007void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4008{
4009 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004010 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4011 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004012 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004013 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004014 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4015 b + 1, bucketTimeSec, percent);
4016 }
David Sodman4a36e932017-11-07 14:29:47 -08004017 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004018 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004019 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004020 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004021 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004022}
4023
Dan Stozae77c7662016-05-13 11:37:28 -07004024void SurfaceFlinger::recordBufferingStats(const char* layerName,
4025 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004026 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4027 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004028 for (const auto& segment : history) {
4029 if (!segment.usedThirdBuffer) {
4030 stats.twoBufferTime += segment.totalTime;
4031 }
4032 if (segment.occupancyAverage < 1.0f) {
4033 stats.doubleBufferedTime += segment.totalTime;
4034 } else if (segment.occupancyAverage < 2.0f) {
4035 stats.tripleBufferedTime += segment.totalTime;
4036 }
4037 ++stats.numSegments;
4038 stats.totalTime += segment.totalTime;
4039 }
4040}
4041
Brian Andersond6927fb2016-07-23 23:37:30 -07004042void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4043 result.appendFormat("Layer frame timestamps:\n");
4044
4045 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4046 const size_t count = currentLayers.size();
4047 for (size_t i=0 ; i<count ; i++) {
4048 currentLayers[i]->dumpFrameEvents(result);
4049 }
4050}
4051
Dan Stozae77c7662016-05-13 11:37:28 -07004052void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4053 result.append("Buffering stats:\n");
4054 result.append(" [Layer name] <Active time> <Two buffer> "
4055 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004056 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004057 typedef std::tuple<std::string, float, float, float> BufferTuple;
4058 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004059 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004060 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004061 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004062 if (stats.numSegments == 0) {
4063 continue;
4064 }
4065 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4066 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4067 stats.totalTime;
4068 float doubleBufferRatio = static_cast<float>(
4069 stats.doubleBufferedTime) / stats.totalTime;
4070 float tripleBufferRatio = static_cast<float>(
4071 stats.tripleBufferedTime) / stats.totalTime;
4072 sorted.insert({activeTime, {name, twoBufferRatio,
4073 doubleBufferRatio, tripleBufferRatio}});
4074 }
4075 for (const auto& sortedPair : sorted) {
4076 float activeTime = sortedPair.first;
4077 const BufferTuple& values = sortedPair.second;
4078 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4079 std::get<0>(values).c_str(), activeTime,
4080 std::get<1>(values), std::get<2>(values),
4081 std::get<3>(values));
4082 }
4083 result.append("\n");
4084}
4085
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004086void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4087 for (size_t d = 0; d < mDisplays.size(); d++) {
4088 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4089 const int32_t hwcId = displayDevice->getHwcDisplayId();
4090 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4091 if (!displayId) {
4092 continue;
4093 }
4094
4095 result.appendFormat("Display %d: ", hwcId);
4096 uint8_t port;
4097 DisplayIdentificationData data;
4098 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4099 result.append("no identification data\n");
4100 continue;
4101 }
4102
4103 if (!isEdid(data)) {
4104 result.append("unknown identification data: ");
4105 for (uint8_t byte : data) {
4106 result.appendFormat("%x ", byte);
4107 }
4108 result.append("\n");
4109 continue;
4110 }
4111
4112 const auto edid = parseEdid(data);
4113 if (!edid) {
4114 result.append("invalid EDID: ");
4115 for (uint8_t byte : data) {
4116 result.appendFormat("%x ", byte);
4117 }
4118 result.append("\n");
4119 continue;
4120 }
4121
4122 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4123 result.append(edid->displayName.data(), edid->displayName.length());
4124 result.append("\"\n");
4125 }
4126 result.append("\n");
4127}
4128
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004129void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4130 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004131 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004132
4133 // TODO: print out if wide-color mode is active or not
4134
4135 for (size_t d = 0; d < mDisplays.size(); d++) {
4136 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4137 int32_t hwcId = displayDevice->getHwcDisplayId();
4138 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4139 continue;
4140 }
4141
4142 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004143 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004144 for (auto&& mode : modes) {
4145 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4146 }
4147
Peiyong Lina52f0292018-03-14 17:26:31 -07004148 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004149 result.appendFormat(" Current color mode: %s (%d)\n",
4150 decodeColorMode(currentMode).c_str(), currentMode);
4151 }
4152 result.append("\n");
4153}
4154
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004155LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004156 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004157 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4158 const State& state = useDrawing ? mDrawingState : mCurrentState;
4159 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004160 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004161 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004162 });
4163
4164 return layersProto;
4165}
4166
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004167LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4168 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004169 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004170
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004171 SizeProto* resolution = layersProto.mutable_resolution();
4172 resolution->set_w(displayDevice->getWidth());
4173 resolution->set_h(displayDevice->getHeight());
4174
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004175 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4176 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4177 layersProto.set_global_transform(
4178 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4179
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004180 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004181 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004182 LayerProto* layerProto = layersProto.add_layers();
4183 layer->writeToProto(layerProto, hwcId);
4184 }
4185 });
4186
4187 return layersProto;
4188}
4189
Mathias Agopian74d211a2013-04-22 16:55:35 +02004190void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4191 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004192{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004193 bool colorize = false;
4194 if (index < args.size()
4195 && (args[index] == String16("--color"))) {
4196 colorize = true;
4197 index++;
4198 }
4199
4200 Colorizer colorizer(colorize);
4201
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004202 // figure out if we're stuck somewhere
4203 const nsecs_t now = systemTime();
4204 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4205 const nsecs_t inTransaction(mDebugInTransaction);
4206 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4207 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4208
4209 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004210 * Dump library configuration.
4211 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212
4213 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004214 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004216 appendSfConfigString(result);
4217 appendUiConfigString(result);
4218 appendGuiConfigString(result);
4219 result.append("\n");
4220
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004221 result.append("\nDisplay identification data:\n");
4222 dumpDisplayIdentificationData(result);
4223
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004224 result.append("\nWide-Color information:\n");
4225 dumpWideColorInfo(result);
4226
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004227 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004228 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004230 result.append(SyncFeatures::getInstance().toString());
4231 result.append("\n");
4232
David Sodman105b7dc2017-11-04 20:28:14 -07004233 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004234
Andy McFadden41d67d72014-04-25 16:58:34 -07004235 colorizer.bold(result);
4236 result.append("DispSync configuration: ");
4237 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004238 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4239 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4240 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004241 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004242 result.append("\n");
4243
Dan Stozab90cf072015-03-05 11:05:59 -08004244 // Dump static screen stats
4245 result.append("\n");
4246 dumpStaticScreenStats(result);
4247 result.append("\n");
4248
Dan Stozae77c7662016-05-13 11:37:28 -07004249 dumpBufferingStats(result);
4250
Andy McFadden4803b742012-09-24 19:07:20 -07004251 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004252 * Dump the visible layer list
4253 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004254 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004255 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004256 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4257 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004258 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004259
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004260 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004261 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004262 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004263 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264
4265 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004266 * Dump Display state
4267 */
4268
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004269 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004270 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004271 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004272 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4273 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004275 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004276 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004277
4278 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279 * Dump SurfaceFlinger global state
4280 */
4281
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004282 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004283 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004285
Mathias Agopian888c8222012-08-04 21:10:38 -07004286 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004287 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004288
David Sodmanbc815282017-11-05 18:57:52 -08004289 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004290
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004291 if (hw) {
4292 hw->undefinedRegion.dump(result, "undefinedRegion");
4293 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4294 hw->getOrientation(), hw->isDisplayOn());
4295 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004296 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 " last eglSwapBuffers() time: %f us\n"
4298 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004299 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004300 " refresh-rate : %f fps\n"
4301 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004302 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004303 " gpu_to_cpu_unsupported : %d\n"
4304 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305 mLastSwapBufferTime/1000.0,
4306 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004307 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004308 1e9 / activeConfig->getVsyncPeriod(),
4309 activeConfig->getDpiX(),
4310 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004311 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312
Mathias Agopian74d211a2013-04-22 16:55:35 +02004313 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315
Mathias Agopian74d211a2013-04-22 16:55:35 +02004316 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318
4319 /*
4320 * VSYNC state
4321 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004322 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004323 result.append("\n");
4324
4325 /*
4326 * HWC layer minidump
4327 */
4328 for (size_t d = 0; d < mDisplays.size(); d++) {
4329 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4330 int32_t hwcId = displayDevice->getHwcDisplayId();
4331 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4332 continue;
4333 }
4334
4335 result.appendFormat("Display %d HWC layers:\n", hwcId);
4336 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004337 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004338 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004339 });
Dan Stozae22aec72016-08-01 13:20:59 -07004340 result.append("\n");
4341 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342
4343 /*
4344 * Dump HWComposer state
4345 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004346 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004347 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004348 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004349 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004350 result.appendFormat(" h/w composer %s\n",
4351 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004352 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004353
4354 /*
4355 * Dump gralloc state
4356 */
4357 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4358 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004359
4360 /*
4361 * Dump VrFlinger state if in use.
4362 */
4363 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4364 result.append("VrFlinger state:\n");
4365 result.append(mVrFlinger->Dump().c_str());
4366 result.append("\n");
4367 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368}
4369
Mathias Agopian13127d82013-03-05 17:47:11 -08004370const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004371SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004372 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004373 wp<IBinder> dpy;
4374 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4375 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4376 dpy = mDisplays.keyAt(i);
4377 break;
4378 }
4379 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004380 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004381 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4382 // Just use the primary display so we have something to return
4383 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4384 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004385 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004386}
4387
Keun young Park63f165f2012-08-31 10:53:36 -07004388bool SurfaceFlinger::startDdmConnection()
4389{
4390 void* libddmconnection_dso =
4391 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4392 if (!libddmconnection_dso) {
4393 return false;
4394 }
4395 void (*DdmConnection_start)(const char* name);
4396 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004397 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004398 if (!DdmConnection_start) {
4399 dlclose(libddmconnection_dso);
4400 return false;
4401 }
4402 (*DdmConnection_start)(getServiceName());
4403 return true;
4404}
4405
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004406status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004407 switch (code) {
4408 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004409 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004410 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004411 case CLEAR_ANIMATION_FRAME_STATS:
4412 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004413 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004414 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004415 case ENABLE_VSYNC_INJECTIONS:
4416 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004417 {
4418 // codes that require permission check
4419 IPCThreadState* ipc = IPCThreadState::self();
4420 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004421 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004422 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004423 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004424 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004425 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004426 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004427 break;
4428 }
Robert Carr1db73f62016-12-21 12:58:51 -08004429 /*
4430 * Calling setTransactionState is safe, because you need to have been
4431 * granted a reference to Client* and Handle* to do anything with it.
4432 *
4433 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4434 */
4435 case SET_TRANSACTION_STATE:
4436 case CREATE_SCOPED_CONNECTION:
4437 {
4438 return OK;
4439 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004440 case CAPTURE_SCREEN:
4441 {
4442 // codes that require permission check
4443 IPCThreadState* ipc = IPCThreadState::self();
4444 const int pid = ipc->getCallingPid();
4445 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004446 if ((uid != AID_GRAPHICS) &&
4447 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004448 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004449 return PERMISSION_DENIED;
4450 }
4451 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 }
chaviwa76b2712017-09-20 12:02:26 -07004453 case CAPTURE_LAYERS: {
4454 IPCThreadState* ipc = IPCThreadState::self();
4455 const int pid = ipc->getCallingPid();
4456 const int uid = ipc->getCallingUid();
4457 if ((uid != AID_GRAPHICS) &&
4458 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4459 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4460 return PERMISSION_DENIED;
4461 }
4462 break;
4463 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004465 return OK;
4466}
4467
4468status_t SurfaceFlinger::onTransact(
4469 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4470{
4471 status_t credentialCheck = CheckTransactCodeCredentials(code);
4472 if (credentialCheck != OK) {
4473 return credentialCheck;
4474 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004475
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4477 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004478 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004479 IPCThreadState* ipc = IPCThreadState::self();
4480 const int uid = ipc->getCallingUid();
4481 if (CC_UNLIKELY(uid != AID_SYSTEM
4482 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004483 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004484 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004485 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004486 return PERMISSION_DENIED;
4487 }
4488 int n;
4489 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004490 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004491 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004492 return NO_ERROR;
4493 case 1002: // SHOW_UPDATES
4494 n = data.readInt32();
4495 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004496 invalidateHwcGeometry();
4497 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004498 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004499 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004500 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004501 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004502 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004503 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004504 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004505 setTransactionFlags(
4506 eTransactionNeeded|
4507 eDisplayTransactionNeeded|
4508 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004509 return NO_ERROR;
4510 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004511 case 1006:{ // send empty update
4512 signalRefresh();
4513 return NO_ERROR;
4514 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004515 case 1008: // toggle use of hw composer
4516 n = data.readInt32();
4517 mDebugDisableHWC = n ? 1 : 0;
4518 invalidateHwcGeometry();
4519 repaintEverything();
4520 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004521 case 1009: // toggle use of transform hint
4522 n = data.readInt32();
4523 mDebugDisableTransformHint = n ? 1 : 0;
4524 invalidateHwcGeometry();
4525 repaintEverything();
4526 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004528 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 reply->writeInt32(0);
4530 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004531 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004532 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 return NO_ERROR;
4534 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004535 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004536 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004537 return NO_ERROR;
4538 }
4539 case 1014: {
4540 // daltonize
4541 n = data.readInt32();
4542 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004543 case 1:
4544 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4545 break;
4546 case 2:
4547 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4548 break;
4549 case 3:
4550 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4551 break;
4552 default:
4553 mDaltonizer.setType(ColorBlindnessType::None);
4554 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004555 }
4556 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004557 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004558 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004559 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004560 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004561 invalidateHwcGeometry();
4562 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004563 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004565 case 1015: {
4566 // apply a color matrix
4567 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004568 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004569 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004570 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004571 for (size_t j = 0; j < 4; j++) {
4572 mColorMatrix[i][j] = data.readFloat();
4573 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004574 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004575 } else {
4576 mColorMatrix = mat4();
4577 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004578
4579 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4580 // the division by w in the fragment shader
4581 float4 lastRow(transpose(mColorMatrix)[3]);
4582 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4583 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4584 }
4585
Alan Viverette9c5a3332013-09-12 20:04:35 -07004586 invalidateHwcGeometry();
4587 repaintEverything();
4588 return NO_ERROR;
4589 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004590 // This is an experimental interface
4591 // Needs to be shifted to proper binder interface when we productize
4592 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004593 n = data.readInt32();
4594 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004595 return NO_ERROR;
4596 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004597 case 1017: {
4598 n = data.readInt32();
4599 mForceFullDamage = static_cast<bool>(n);
4600 return NO_ERROR;
4601 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004602 case 1018: { // Modify Choreographer's phase offset
4603 n = data.readInt32();
4604 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4605 return NO_ERROR;
4606 }
4607 case 1019: { // Modify SurfaceFlinger's phase offset
4608 n = data.readInt32();
4609 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4610 return NO_ERROR;
4611 }
Irvel468051e2016-06-13 16:44:44 -07004612 case 1020: { // Layer updates interceptor
4613 n = data.readInt32();
4614 if (n) {
4615 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004616 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004617 }
4618 else{
4619 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004620 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004621 }
4622 return NO_ERROR;
4623 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004624 case 1021: { // Disable HWC virtual displays
4625 n = data.readInt32();
4626 mUseHwcVirtualDisplays = !n;
4627 return NO_ERROR;
4628 }
Romain Guy0147a172017-06-01 13:53:56 -07004629 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004630 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004631
4632 invalidateHwcGeometry();
4633 repaintEverything();
4634 return NO_ERROR;
4635 }
Romain Guy54f154a2017-10-24 21:40:32 +01004636 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004637 int32_t value = data.readInt32();
4638 if (value > 2) {
4639 return BAD_VALUE;
4640 }
4641 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4642 return BAD_VALUE;
4643 }
Romain Guy54f154a2017-10-24 21:40:32 +01004644
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004645 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004646 invalidateHwcGeometry();
4647 repaintEverything();
4648 return NO_ERROR;
4649 }
4650 case 1024: { // Is wide color gamut rendering/color management supported?
4651 reply->writeBool(hasWideColorDisplay);
4652 return NO_ERROR;
4653 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004654 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004655 n = data.readInt32();
4656 if (n) {
4657 ALOGV("LayerTracing enabled");
4658 mTracing.enable();
4659 doTracing("tracing.enable");
4660 reply->writeInt32(NO_ERROR);
4661 } else {
4662 ALOGV("LayerTracing disabled");
4663 status_t err = mTracing.disable();
4664 reply->writeInt32(err);
4665 }
4666 return NO_ERROR;
4667 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004668 case 1026: { // Get layer tracing status
4669 reply->writeBool(mTracing.isEnabled());
4670 return NO_ERROR;
4671 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004672 // Is a DisplayColorSetting supported?
4673 case 1027: {
4674 int32_t value = data.readInt32();
4675 switch (value) {
4676 case 0:
4677 reply->writeBool(hasWideColorDisplay);
4678 return NO_ERROR;
4679 case 1:
4680 reply->writeBool(true);
4681 return NO_ERROR;
4682 case 2:
4683 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4684 return NO_ERROR;
4685 default:
4686 return BAD_VALUE;
4687 }
4688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004689 }
4690 }
4691 return err;
4692}
4693
Steven Thomas6d8110b2017-08-31 18:24:21 -07004694void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004695 android_atomic_or(1, &mRepaintEverything);
4696 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004697}
4698
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004699// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4700class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004701public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004702 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4703 ~WindowDisconnector() {
4704 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004705 }
4706
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004707private:
4708 ANativeWindow* mWindow;
4709 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004710};
4711
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004712status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4713 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4714 int32_t minLayerZ, int32_t maxLayerZ,
4715 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004716 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004717 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004718
chaviwa76b2712017-09-20 12:02:26 -07004719 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4720
4721 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004722 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4723
chaviwa76b2712017-09-20 12:02:26 -07004724 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4725
4726 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4727 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004728 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004729}
4730
4731status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004732 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004733 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004734 ATRACE_CALL();
4735
4736 class LayerRenderArea : public RenderArea {
4737 public:
Robert Carr578038f2018-03-09 12:25:24 -08004738 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4739 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004740 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004741 mLayer(layer),
4742 mCrop(crop),
4743 mFlinger(flinger),
4744 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004745 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004746 Rect getBounds() const override {
4747 const Layer::State& layerState(mLayer->getDrawingState());
4748 return Rect(layerState.active.w, layerState.active.h);
4749 }
4750 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4751 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4752 bool isSecure() const override { return false; }
4753 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004754 Rect getSourceCrop() const override {
4755 if (mCrop.isEmpty()) {
4756 return getBounds();
4757 } else {
4758 return mCrop;
4759 }
4760 }
4761 bool getWideColorSupport() const override { return false; }
4762 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004763 float getDisplayMaxLuminance() const override {
4764 return DisplayDevice::sDefaultMaxLumiance;
4765 }
Robert Carr578038f2018-03-09 12:25:24 -08004766
4767 class ReparentForDrawing {
4768 public:
4769 const sp<Layer>& oldParent;
4770 const sp<Layer>& newParent;
4771
4772 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4773 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004774 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004775 }
Robert Carr15eae092018-03-23 13:43:53 -07004776 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004777 };
4778
4779 void render(std::function<void()> drawLayers) override {
4780 if (!mChildrenOnly) {
4781 mTransform = mLayer->getTransform().inverse();
4782 drawLayers();
4783 } else {
4784 Rect bounds = getBounds();
4785 screenshotParentLayer =
4786 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4787 bounds.getWidth(), bounds.getHeight(), 0);
4788
4789 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4790 drawLayers();
4791 }
4792 }
chaviwa76b2712017-09-20 12:02:26 -07004793
chaviwa76b2712017-09-20 12:02:26 -07004794 private:
chaviw7206d492017-11-10 16:16:12 -08004795 const sp<Layer> mLayer;
4796 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004797
4798 // In the "childrenOnly" case we reparent the children to a screenshot
4799 // layer which has no properties set and which does not draw.
4800 sp<ContainerLayer> screenshotParentLayer;
4801 Transform mTransform;
4802
4803 SurfaceFlinger* mFlinger;
4804 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004805 };
4806
4807 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4808 auto parent = layerHandle->owner.promote();
4809
chaviw7206d492017-11-10 16:16:12 -08004810 if (parent == nullptr || parent->isPendingRemoval()) {
4811 ALOGE("captureLayers called with a removed parent");
4812 return NAME_NOT_FOUND;
4813 }
4814
Robert Carr578038f2018-03-09 12:25:24 -08004815 const int uid = IPCThreadState::self()->getCallingUid();
4816 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4817 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4818 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4819 return PERMISSION_DENIED;
4820 }
4821
chaviw7206d492017-11-10 16:16:12 -08004822 Rect crop(sourceCrop);
4823 if (sourceCrop.width() <= 0) {
4824 crop.left = 0;
4825 crop.right = parent->getCurrentState().active.w;
4826 }
4827
4828 if (sourceCrop.height() <= 0) {
4829 crop.top = 0;
4830 crop.bottom = parent->getCurrentState().active.h;
4831 }
4832
4833 int32_t reqWidth = crop.width() * frameScale;
4834 int32_t reqHeight = crop.height() * frameScale;
4835
Robert Carr578038f2018-03-09 12:25:24 -08004836 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004837
Robert Carr578038f2018-03-09 12:25:24 -08004838 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004839 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4840 if (!layer->isVisible()) {
4841 return;
Robert Carr578038f2018-03-09 12:25:24 -08004842 } else if (childrenOnly && layer == parent.get()) {
4843 return;
chaviwa76b2712017-09-20 12:02:26 -07004844 }
4845 visitor(layer);
4846 });
4847 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004848 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004849}
4850
4851status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4852 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004853 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004854 bool useIdentityTransform) {
4855 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004856
chaviwa76b2712017-09-20 12:02:26 -07004857 renderArea.updateDimensions();
4858
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004859 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4860 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4861 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4862 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004863
4864 // This mutex protects syncFd and captureResult for communication of the return values from the
4865 // main thread back to this Binder thread
4866 std::mutex captureMutex;
4867 std::condition_variable captureCondition;
4868 std::unique_lock<std::mutex> captureLock(captureMutex);
4869 int syncFd = -1;
4870 std::optional<status_t> captureResult;
4871
Robert Carr03480e22018-01-04 16:02:06 -08004872 const int uid = IPCThreadState::self()->getCallingUid();
4873 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4874
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004875 sp<LambdaMessage> message = new LambdaMessage([&]() {
4876 // If there is a refresh pending, bug out early and tell the binder thread to try again
4877 // after the refresh.
4878 if (mRefreshPending) {
4879 ATRACE_NAME("Skipping screenshot for now");
4880 std::unique_lock<std::mutex> captureLock(captureMutex);
4881 captureResult = std::make_optional<status_t>(EAGAIN);
4882 captureCondition.notify_one();
4883 return;
4884 }
4885
4886 status_t result = NO_ERROR;
4887 int fd = -1;
4888 {
4889 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004890 renderArea.render([&]() {
4891 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4892 useIdentityTransform, forSystem, &fd);
4893 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004894 }
4895
4896 {
4897 std::unique_lock<std::mutex> captureLock(captureMutex);
4898 syncFd = fd;
4899 captureResult = std::make_optional<status_t>(result);
4900 captureCondition.notify_one();
4901 }
4902 });
4903
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004904 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004905 if (result == NO_ERROR) {
4906 captureCondition.wait(captureLock, [&]() { return captureResult; });
4907 while (*captureResult == EAGAIN) {
4908 captureResult.reset();
4909 result = postMessageAsync(message);
4910 if (result != NO_ERROR) {
4911 return result;
4912 }
4913 captureCondition.wait(captureLock, [&]() { return captureResult; });
4914 }
4915 result = *captureResult;
4916 }
4917
4918 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004919 sync_wait(syncFd, -1);
4920 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004921 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004922
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004923 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004924}
4925
chaviwa76b2712017-09-20 12:02:26 -07004926void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4927 TraverseLayersFunction traverseLayers, bool yswap,
4928 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004929 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004930
Lloyd Pique144e1162017-12-20 16:44:52 -08004931 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004932
4933 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004934 const auto raWidth = renderArea.getWidth();
4935 const auto raHeight = renderArea.getHeight();
4936
4937 const auto reqWidth = renderArea.getReqWidth();
4938 const auto reqHeight = renderArea.getReqHeight();
4939 Rect sourceCrop = renderArea.getSourceCrop();
4940
4941 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4942 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004943
Dan Stozac1879002014-05-22 15:59:05 -07004944 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004945 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004946 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004947 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004948 }
4949
4950 // ensure that sourceCrop is inside screen
4951 if (sourceCrop.left < 0) {
4952 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4953 }
chaviwa76b2712017-09-20 12:02:26 -07004954 if (sourceCrop.right > raWidth) {
4955 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004956 }
4957 if (sourceCrop.top < 0) {
4958 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4959 }
chaviwa76b2712017-09-20 12:02:26 -07004960 if (sourceCrop.bottom > raHeight) {
4961 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004962 }
4963
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004964 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004965 if (renderArea.getWideColorSupport()) {
4966 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004967 }
Peiyong Linfb069302018-04-25 14:34:31 -07004968 engine.setOutputDataSpace(outputDataspace);
4969 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004970
Mathias Agopian180f10d2013-04-10 22:55:41 -07004971 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004972 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004973
4974 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004975 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4976 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004977 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004978
chaviw50da5042018-04-09 13:49:37 -07004979 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004980 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004981 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004982
chaviwa76b2712017-09-20 12:02:26 -07004983 traverseLayers([&](Layer* layer) {
4984 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004985 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004986 if (filtering) layer->setFiltering(false);
4987 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004988}
4989
chaviwa76b2712017-09-20 12:02:26 -07004990status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4991 TraverseLayersFunction traverseLayers,
4992 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004993 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004994 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004995 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004996 ATRACE_CALL();
4997
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004998 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004999
5000 traverseLayers([&](Layer* layer) {
5001 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5002 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005003
Robert Carr03480e22018-01-04 16:02:06 -08005004 // We allow the system server to take screenshots of secure layers for
5005 // use in situations like the Screen-rotation animation and place
5006 // the impetus on WindowManager to not persist them.
5007 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005008 ALOGW("FB is protected: PERMISSION_DENIED");
5009 return PERMISSION_DENIED;
5010 }
5011
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005012 // this binds the given EGLImage as a framebuffer for the
5013 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005014 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005015 if (bufferBond.getStatus() != NO_ERROR) {
5016 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005017 return INVALID_OPERATION;
5018 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005019
Dan Stozaabcda352017-06-01 14:37:39 -07005020 // this will in fact render into our dequeued buffer
5021 // via an FBO, which means we didn't have to create
5022 // an EGLSurface and therefore we're not
5023 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005024 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005025
Dan Stozaabcda352017-06-01 14:37:39 -07005026 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005027 getRenderEngine().finish();
5028 *outSyncFd = -1;
5029
chaviwa76b2712017-09-20 12:02:26 -07005030 const auto reqWidth = renderArea.getReqWidth();
5031 const auto reqHeight = renderArea.getReqHeight();
5032
Dan Stozaabcda352017-06-01 14:37:39 -07005033 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5034 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005035 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005036 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005037 } else {
5038 base::unique_fd syncFd = getRenderEngine().flush();
5039 if (syncFd < 0) {
5040 getRenderEngine().finish();
5041 }
5042 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005043 }
5044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005045 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005046}
5047
Mathias Agopiand5556842013-09-19 17:08:37 -07005048void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005049 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005050 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005051 for (size_t y = 0; y < h; y++) {
5052 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5053 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005054 if (p[x] != 0xFF000000) return;
5055 }
5056 }
chaviwa76b2712017-09-20 12:02:26 -07005057 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005058
Robert Carr2047fae2016-11-28 14:09:09 -08005059 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005060 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005061 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005062 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5063 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5064 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5065 static_cast<float>(state.color.a));
5066 i++;
5067 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005068 }
5069}
5070
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005071// ---------------------------------------------------------------------------
5072
Dan Stoza412903f2017-04-27 13:42:17 -07005073void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5074 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005075}
5076
Dan Stoza412903f2017-04-27 13:42:17 -07005077void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5078 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005079}
5080
chaviwa76b2712017-09-20 12:02:26 -07005081void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5082 int32_t maxLayerZ,
5083 const LayerVector::Visitor& visitor) {
5084 // We loop through the first level of layers without traversing,
5085 // as we need to interpret min/max layer Z in the top level Z space.
5086 for (const auto& layer : mDrawingState.layersSortedByZ) {
5087 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5088 continue;
5089 }
5090 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005091 // relative layers are traversed in Layer::traverseInZOrder
5092 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005093 continue;
5094 }
5095 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005096 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5097 return;
5098 }
chaviwa76b2712017-09-20 12:02:26 -07005099 if (!layer->isVisible()) {
5100 return;
5101 }
5102 visitor(layer);
5103 });
5104 }
5105}
5106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005107}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005108
Chia-I Wu30505fb2018-03-26 16:20:31 -07005109
Mathias Agopian3f844832013-08-07 21:24:32 -07005110#if defined(__gl_h_)
5111#error "don't include gl/gl.h in this file"
5112#endif
5113
5114#if defined(__gl2_h_)
5115#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005116#endif