blob: abd74c1ca26f3d0759e94b77f1f90a46cf4af630 [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) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001473 mTimeStats.incrementMissedFrames(true);
Dan Stoza50182882016-07-08 12:02:20 -07001474 signalLayerUpdate();
1475 break;
1476 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001477 if (frameMissed) {
1478 mTimeStats.incrementMissedFrames(false);
1479 }
Dan Stoza50182882016-07-08 12:02:20 -07001480
Steven Thomas050b2c82017-03-06 11:45:16 -08001481 // Now that we're going to make it to the handleMessageTransaction()
1482 // call below it's safe to call updateVrFlinger(), which will
1483 // potentially trigger a display handoff.
1484 updateVrFlinger();
1485
Dan Stoza6b9454d2014-11-07 16:00:59 -08001486 bool refreshNeeded = handleMessageTransaction();
1487 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001488 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001490 // Signal a refresh if a transaction modified the window state,
1491 // a new buffer was latched, or if HWC has requested a full
1492 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 signalRefresh();
1494 }
1495 break;
1496 }
1497 case MessageQueue::REFRESH: {
1498 handleMessageRefresh();
1499 break;
1500 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001501 }
1502}
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001505 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001507 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511}
1512
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516}
1517
1518void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001521 mRefreshPending = false;
1522
Chia-I Wu30505fb2018-03-26 16:20:31 -07001523 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001524
Chia-I Wu30505fb2018-03-26 16:20:31 -07001525 preComposition(refreshStartTime);
1526 rebuildLayerStacks();
1527 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001528 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001529 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001530 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001531 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001532 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001533
David Sodman105b7dc2017-11-04 20:28:14 -07001534 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001535
1536 mHadClientComposition = false;
1537 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1538 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1539 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001540 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001541 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001542 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001543
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001546
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547void SurfaceFlinger::doDebugFlashRegions()
1548{
1549 // is debugging enabled
1550 if (CC_LIKELY(!mDebugRegion))
1551 return;
1552
1553 const bool repaintEverything = mRepaintEverything;
1554 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1555 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001556 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 // transform the dirty region into this screen's coordinate space
1558 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1559 if (!dirtyRegion.isEmpty()) {
1560 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001561 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562
1563 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001565 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001566 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1567
Mathias Agopianda27af92012-09-13 18:17:13 -07001568 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 }
1570 }
1571 }
1572
1573 postFramebuffer();
1574
1575 if (mDebugRegion > 1) {
1576 usleep(mDebugRegion * 1000);
1577 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001578
Dan Stoza9e56aa02015-11-02 13:00:03 -08001579 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001580 auto& displayDevice = mDisplays[displayId];
1581 if (!displayDevice->isDisplayOn()) {
1582 continue;
1583 }
1584
David Sodman105b7dc2017-11-04 20:28:14 -07001585 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1586 ALOGE_IF(result != NO_ERROR,
1587 "prepareFrame for display %zd failed:"
1588 " %d (%s)",
1589 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001590 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591}
1592
Adrian Roos1e1a1282017-11-01 19:05:31 +01001593void SurfaceFlinger::doTracing(const char* where) {
1594 ATRACE_CALL();
1595 ATRACE_NAME(where);
1596 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001597 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001598 }
1599}
1600
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001601void SurfaceFlinger::logLayerStats() {
1602 ATRACE_CALL();
1603 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1604 int32_t hwcId = -1;
1605 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1606 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1607 if (displayDevice->isPrimary()) {
1608 hwcId = displayDevice->getHwcDisplayId();
1609 break;
1610 }
1611 }
1612 if (hwcId < 0) {
1613 ALOGE("LayerStats: Hmmm, no primary display?");
1614 return;
1615 }
1616 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1617 }
1618}
1619
Chia-I Wu30505fb2018-03-26 16:20:31 -07001620void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001622 ATRACE_CALL();
1623 ALOGV("preComposition");
1624
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001626 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001627 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 needExtraInvalidate = true;
1629 }
Robert Carr2047fae2016-11-28 14:09:09 -08001630 });
1631
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632 if (needExtraInvalidate) {
1633 signalLayerUpdate();
1634 }
1635}
1636
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637void SurfaceFlinger::updateCompositorTiming(
1638 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1639 std::shared_ptr<FenceTime>& presentFenceTime) {
1640 // Update queue of past composite+present times and determine the
1641 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001642 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001644 while (!getBE().mCompositePresentTimes.empty()) {
1645 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 // Cached values should have been updated before calling this method,
1647 // which helps avoid duplicate syscalls.
1648 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1649 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1650 break;
1651 }
1652 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001653 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 }
1655
1656 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001657 while (getBE().mCompositePresentTimes.size() > 16) {
1658 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 }
1660
Brian Andersond0010582017-03-07 13:20:31 -08001661 setCompositorTimingSnapped(
1662 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1663}
1664
1665void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1666 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 // Integer division and modulo round toward 0 not -inf, so we need to
1668 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001669 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1671 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1672
Brian Andersond0010582017-03-07 13:20:31 -08001673 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1674 if (idealLatency <= 0) {
1675 idealLatency = vsyncInterval;
1676 }
1677
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 // Snap the latency to a value that removes scheduling jitter from the
1679 // composition and present times, which often have >1ms of jitter.
1680 // Reducing jitter is important if an app attempts to extrapolate
1681 // something (such as user input) to an accurate diasplay time.
1682 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1683 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001684 nsecs_t bias = vsyncInterval / 2;
1685 int64_t extraVsyncs =
1686 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1687 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1688 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689
David Sodman99974d22017-11-28 12:04:33 -08001690 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1691 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1692 getBE().mCompositorTiming.interval = vsyncInterval;
1693 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694}
1695
Chia-I Wu30505fb2018-03-26 16:20:31 -07001696void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 ATRACE_CALL();
1699 ALOGV("postComposition");
1700
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001702 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001703 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001704 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001705 }
1706
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001707 // |mStateLock| not needed as we are on the main thread
1708 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709
David Sodman73beded2017-11-15 11:56:06 -08001710 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001712 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713 glCompositionDoneFenceTime =
1714 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001715 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001716 } else {
1717 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1718 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001721 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1726 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1727
Chia-I Wu30505fb2018-03-26 16:20:31 -07001728 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 // when we started doing work for this frame, but that should be okay
1730 // since updateCompositorTiming has snapping logic.
1731 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001732 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001733 CompositorTiming compositorTiming;
1734 {
David Sodman99974d22017-11-28 12:04:33 -08001735 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1736 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001737 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738
Robert Carr2047fae2016-11-28 14:09:09 -08001739 mDrawingState.traverseInZOrder([&](Layer* layer) {
1740 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001741 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001742 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001743 recordBufferingStats(layer->getName().string(),
1744 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001745 }
Robert Carr2047fae2016-11-28 14:09:09 -08001746 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001747
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001748 if (presentFenceTime->isValid()) {
1749 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001750 enableHardwareVsync();
1751 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001752 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001753 }
1754 }
1755
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001756 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001757 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001758 enableHardwareVsync();
1759 }
1760 }
1761
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001762 if (mAnimCompositionPending) {
1763 mAnimCompositionPending = false;
1764
Brian Anderson4e606e32017-03-16 15:34:57 -07001765 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001766 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001767 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001768 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001769 // The HWC doesn't support present fences, so use the refresh
1770 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001771 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001772 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001773 mAnimFrameTracker.setActualPresentTime(presentTime);
1774 }
1775 mAnimFrameTracker.advanceFrame();
1776 }
Dan Stozab90cf072015-03-05 11:05:59 -08001777
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001778 mTimeStats.incrementTotalFrames();
1779 if (mHadClientComposition) {
1780 mTimeStats.incrementClientCompositionFrames();
1781 }
1782
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001783 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1784 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001785 return;
1786 }
1787
1788 nsecs_t currentTime = systemTime();
1789 if (mHasPoweredOff) {
1790 mHasPoweredOff = false;
1791 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001792 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001793 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001794 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1795 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001796 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001797 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001798 }
David Sodman4a36e932017-11-07 14:29:47 -08001799 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001800 }
David Sodman4a36e932017-11-07 14:29:47 -08001801 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001802}
1803
1804void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001805 ATRACE_CALL();
1806 ALOGV("rebuildLayerStacks");
1807
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001809 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001810 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 mVisibleRegionsDirty = false;
1812 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001813
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1815 Region opaqueRegion;
1816 Region dirtyRegion;
1817 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001818 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1820 const Transform& tr(displayDevice->getTransform());
1821 const Rect bounds(displayDevice->getBounds());
1822 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001823 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001824
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001826 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001827 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1828 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 Region drawRegion(tr.transform(
1830 layer->visibleNonTransparentRegion));
1831 drawRegion.andSelf(bounds);
1832 if (!drawRegion.isEmpty()) {
1833 layersSortedByZ.add(layer);
1834 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001835 // Clear out the HWC layer if this layer was
1836 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001837 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001838 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001840 } else {
1841 // WM changes displayDevice->layerStack upon sleep/awake.
1842 // Here we make sure we delete the HWC layers even if
1843 // WM changed their layer stack.
1844 hwcLayerDestroyed = layer->destroyHwcLayer(
1845 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001846 }
1847
1848 // If a layer is not going to get a release fence because
1849 // it is invisible, but it is also going to release its
1850 // old buffer, add it to the list of layers needing
1851 // fences.
1852 if (hwcLayerDestroyed) {
1853 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1854 mLayersWithQueuedFrames.cend(), layer);
1855 if (found != mLayersWithQueuedFrames.cend()) {
1856 layersNeedingFences.add(layer);
1857 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001858 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001859 });
1860 }
1861 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001862 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 displayDevice->undefinedRegion.set(bounds);
1864 displayDevice->undefinedRegion.subtractSelf(
1865 tr.transform(opaqueRegion));
1866 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001867 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001870
Romain Guy0147a172017-06-01 13:53:56 -07001871mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001872 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001873 return mat4();
1874 }
1875
1876 // Rec.709 luma coefficients
1877 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001879 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1881 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1882 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001883 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1884 );
1885}
1886
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001887// Returns a dataspace that fits all visible layers. The returned dataspace
1888// can only be one of
1889//
1890// - Dataspace::V0_SRGB
1891// - Dataspace::DISPLAY_P3
1892// - Dataspace::V0_SCRGB_LINEAR
1893// TODO(b/73825729) Add BT2020 data space.
1894ui::Dataspace SurfaceFlinger::getBestDataspace(
1895 const sp<const DisplayDevice>& displayDevice) const {
1896 Dataspace bestDataspace = Dataspace::V0_SRGB;
1897 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1898 switch (layer->getDataSpace()) {
1899 case Dataspace::V0_SCRGB:
1900 case Dataspace::V0_SCRGB_LINEAR:
1901 // return immediately
1902 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001903 case Dataspace::DISPLAY_P3:
1904 bestDataspace = Dataspace::DISPLAY_P3;
1905 break;
1906 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1907 // since SurfaceFlinger simulates HDR support now, it should honor
1908 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001909 case Dataspace::BT2020_PQ:
1910 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001911 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return Dataspace::V0_SCRGB_LINEAR;
1913 }
1914 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001915 case Dataspace::BT2020_HLG:
1916 case Dataspace::BT2020_ITU_HLG:
1917 if (!displayDevice->hasHLGSupport()) {
1918 return Dataspace::V0_SCRGB_LINEAR;
1919 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 break;
1921 default:
1922 break;
1923 }
Romain Guy54f154a2017-10-24 21:40:32 +01001924 }
1925
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001927}
1928
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929// Pick the ColorMode / Dataspace for the display device.
1930// TODO(b/73825729) Add BT2020 color mode.
1931void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1932 ColorMode* outMode, Dataspace* outDataSpace) const {
1933 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1934 *outMode = ColorMode::NATIVE;
1935 *outDataSpace = Dataspace::UNKNOWN;
1936 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001937 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001938
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939 switch (getBestDataspace(displayDevice)) {
1940 case Dataspace::DISPLAY_P3:
1941 case Dataspace::V0_SCRGB_LINEAR:
1942 *outMode = ColorMode::DISPLAY_P3;
1943 *outDataSpace = Dataspace::DISPLAY_P3;
1944 break;
1945 default:
1946 *outMode = ColorMode::SRGB;
1947 *outDataSpace = Dataspace::V0_SRGB;
1948 break;
1949 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001950}
1951
Chia-I Wu30505fb2018-03-26 16:20:31 -07001952void SurfaceFlinger::setUpHWComposer() {
1953 ATRACE_CALL();
1954 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955
Jesse Hall028dc8f2013-08-20 16:35:32 -07001956 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001957 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001958 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1959 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1960
1961 // If nothing has changed (!dirty), don't recompose.
1962 // If something changed, but we don't currently have any visible layers,
1963 // and didn't when we last did a composition, then skip it this time.
1964 // The second rule does two things:
1965 // - When all layers are removed from a display, we'll emit one black
1966 // frame, then nothing more until we get new layers.
1967 // - When a display is created with a private layer stack, we won't
1968 // emit any black frames until a layer is added to the layer stack.
1969 bool mustRecompose = dirty && !(empty && wasEmpty);
1970
Dominik Laskowski281644e2018-04-19 15:47:35 -07001971 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001972 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1973 mustRecompose ? "doing" : "skipping",
1974 dirty ? "+" : "-",
1975 empty ? "+" : "-",
1976 wasEmpty ? "+" : "-");
1977
Dan Stoza71433162014-02-04 16:22:36 -08001978 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001979
1980 if (mustRecompose) {
1981 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1982 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001983 }
1984
Chia-I Wu30505fb2018-03-26 16:20:31 -07001985 // build the h/w work list
1986 if (CC_UNLIKELY(mGeometryInvalid)) {
1987 mGeometryInvalid = false;
1988 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1989 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1990 const auto hwcId = displayDevice->getHwcDisplayId();
1991 if (hwcId >= 0) {
1992 const Vector<sp<Layer>>& currentLayers(
1993 displayDevice->getVisibleLayersSortedByZ());
1994 for (size_t i = 0; i < currentLayers.size(); i++) {
1995 const auto& layer = currentLayers[i];
1996 if (!layer->hasHwcLayer(hwcId)) {
1997 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1998 layer->forceClientComposition(hwcId);
1999 continue;
2000 }
2001 }
2002
2003 layer->setGeometry(displayDevice, i);
2004 if (mDebugDisableHWC || mDebugRegion) {
2005 layer->forceClientComposition(hwcId);
2006 }
2007 }
2008 }
2009 }
2010 }
2011
2012
2013 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
2014
2015 // Set the per-frame data
2016 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2017 auto& displayDevice = mDisplays[displayId];
2018 const auto hwcId = displayDevice->getHwcDisplayId();
2019
2020 if (hwcId < 0) {
2021 continue;
2022 }
2023 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08002024 displayDevice->setColorTransform(colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002025 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
2026 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2027 "display %zd: %d", displayId, result);
2028 }
2029 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002030 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2031 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002032 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002033 layer->forceClientComposition(hwcId);
2034 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002035 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2036 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2037 !displayDevice->hasHLGSupport()) {
2038 layer->forceClientComposition(hwcId);
2039 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002040
2041 if (layer->getForceClientComposition(hwcId)) {
2042 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2043 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2044 continue;
2045 }
2046
2047 layer->setPerFrameData(displayDevice);
2048 }
2049
2050 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002051 ColorMode colorMode;
2052 Dataspace dataSpace;
2053 pickColorMode(displayDevice, &colorMode, &dataSpace);
2054 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002055 }
2056 }
2057
2058 mPreviousColorMatrix = colorMatrix;
2059
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002061 auto& displayDevice = mDisplays[displayId];
2062 if (!displayDevice->isDisplayOn()) {
2063 continue;
2064 }
2065
David Sodman105b7dc2017-11-04 20:28:14 -07002066 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2068 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002069 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002070}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002071
Mathias Agopiancd60f992012-08-16 16:28:27 -07002072void SurfaceFlinger::doComposition() {
2073 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ALOGV("doComposition");
2075
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002077 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002078 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002079 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002080 // transform the dirty region into this screen's coordinate space
2081 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002082
2083 // repaint the framebuffer (if needed)
2084 doDisplayComposition(hw, dirtyRegion);
2085
Mathias Agopiancd60f992012-08-16 16:28:27 -07002086 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002087 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002088 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002089 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002090 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002091}
2092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093void SurfaceFlinger::postFramebuffer()
2094{
Mathias Agopian841cde52012-03-01 15:44:37 -08002095 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002097
Mathias Agopiana44b0412011-10-16 18:46:35 -07002098 const nsecs_t now = systemTime();
2099 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002100
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2102 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002103 if (!displayDevice->isDisplayOn()) {
2104 continue;
2105 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 const auto hwcId = displayDevice->getHwcDisplayId();
2107 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002108 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002109 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002110 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002111 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002113 // The layer buffer from the previous frame (if any) is released
2114 // by HWC only when the release fence from this frame (if any) is
2115 // signaled. Always get the release fence from HWC first.
2116 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002117 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002118
2119 // If the layer was client composited in the previous frame, we
2120 // need to merge with the previous client target acquire fence.
2121 // Since we do not track that, always merge with the current
2122 // client target acquire fence when it is available, even though
2123 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002125 releaseFence = Fence::merge("LayerRelease", releaseFence,
2126 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002127 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002128
David Sodmanb8af7922017-12-21 15:17:55 -08002129 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 }
Chia-I Wu83806892017-11-16 10:50:20 -08002131
2132 // We've got a list of layers needing fences, that are disjoint with
2133 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2134 // supply them with the present fence.
2135 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002136 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002137 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002138 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002139 }
2140 }
2141
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002143 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002144 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002145 }
2146
Mathias Agopiana44b0412011-10-16 18:46:35 -07002147 mLastSwapBufferTime = systemTime() - now;
2148 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002149
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002150 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002151 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2152 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2153 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2154 logFrameStats();
2155 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157}
2158
Mathias Agopian87baae12012-07-31 12:38:26 -07002159void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160{
Mathias Agopian841cde52012-03-01 15:44:37 -08002161 ATRACE_CALL();
2162
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002163 // here we keep a copy of the drawing state (that is the state that's
2164 // going to be overwritten by handleTransactionLocked()) outside of
2165 // mStateLock so that the side-effects of the State assignment
2166 // don't happen with mStateLock held (which can cause deadlocks).
2167 State drawingState(mDrawingState);
2168
Mathias Agopianca4d3602011-05-19 15:38:14 -07002169 Mutex::Autolock _l(mStateLock);
2170 const nsecs_t now = systemTime();
2171 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002172
Mathias Agopianca4d3602011-05-19 15:38:14 -07002173 // Here we're guaranteed that some transaction flags are set
2174 // so we can call handleTransactionLocked() unconditionally.
2175 // We call getTransactionFlags(), which will also clear the flags,
2176 // with mStateLock held to guarantee that mCurrentState won't change
2177 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002178
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002179 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002180 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002181 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002182
Mathias Agopianca4d3602011-05-19 15:38:14 -07002183 mLastTransactionTime = systemTime() - now;
2184 mDebugInTransaction = 0;
2185 invalidateHwcGeometry();
2186 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002187}
2188
Lloyd Pique715a2c12017-12-14 17:18:08 -08002189DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002190 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002191 // Figure out whether the event is for the primary display or an
2192 // external display by matching the Hwc display id against one for a
2193 // connected display. If we did not find a match, we then check what
2194 // displays are not already connected to determine the type. If we don't
2195 // have a connected primary display, we assume the new display is meant to
2196 // be the primary display, and then if we don't have an external display,
2197 // we assume it is that.
2198 const auto primaryDisplayId =
2199 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2200 const auto externalDisplayId =
2201 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2202 if (primaryDisplayId && primaryDisplayId == display) {
2203 return DisplayDevice::DISPLAY_PRIMARY;
2204 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002205 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002206 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2207 return DisplayDevice::DISPLAY_PRIMARY;
2208 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2209 return DisplayDevice::DISPLAY_EXTERNAL;
2210 }
2211
2212 return DisplayDevice::DISPLAY_ID_INVALID;
2213}
2214
Lloyd Piqueba04e622017-12-14 17:11:26 -08002215void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2216 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002217 auto displayType = determineDisplayType(event.display, event.connection);
2218 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2219 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2220 continue;
2221 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002222
2223 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2224 ALOGE("External displays are not supported by the vr hardware composer.");
2225 continue;
2226 }
2227
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002228 const auto displayId =
2229 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2230 if (displayId) {
2231 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2232 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002233
2234 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002235 if (!mBuiltinDisplays[displayType].get()) {
2236 ALOGV("Creating built in display %d", displayType);
2237 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002238 DisplayDeviceState info;
2239 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002240 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2241 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002242 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002243 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2244 mInterceptor->saveDisplayCreation(info);
2245 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002246 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002247 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002248
Lloyd Piquefcd86612017-12-14 17:15:36 -08002249 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2250 if (idx >= 0) {
2251 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002252 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002253 mCurrentState.displays.removeItemsAt(idx);
2254 }
2255 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002256 }
2257
2258 processDisplayChangesLocked();
2259 }
2260
2261 mPendingHotplugEvents.clear();
2262}
2263
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2265 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2266 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 bool hasWideColorGamut = false;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002268 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270 for (ColorMode colorMode : modes) {
2271 switch (colorMode) {
2272 case ColorMode::DISPLAY_P3:
2273 case ColorMode::ADOBE_RGB:
2274 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002275 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 default:
2279 break;
2280 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002281
2282 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2283 colorMode);
2284 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2285 for (auto intent : renderIntents) {
2286 if (intent == RenderIntent::ENHANCE) {
2287 mBuiltinDisplaySupportsEnhance = true;
2288 break;
2289 }
2290 }
2291 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292 }
2293 }
2294
Peiyong Lin62665892018-04-16 11:07:44 -07002295 HdrCapabilities hdrCapabilities;
2296 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002297
2298 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2299 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2300
2301 /*
2302 * Create our display's surface
2303 */
2304 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2305 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002306 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002307 renderSurface->setNativeWindow(nativeWindow.get());
2308 const int displayWidth = renderSurface->queryWidth();
2309 const int displayHeight = renderSurface->queryHeight();
2310
2311 // Make sure that composition can never be stalled by a virtual display
2312 // consumer that isn't processing buffers fast enough. We have to do this
2313 // in two places:
2314 // * Here, in case the display is composed entirely by HWC.
2315 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2316 // window's swap interval in eglMakeCurrent, so they'll override the
2317 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002318 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2320 }
2321
2322 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002323 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324
2325 sp<DisplayDevice> hw =
2326 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2327 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002328 hasWideColorGamut, hdrCapabilities,
2329 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2330 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
2332 if (maxFrameBufferAcquiredBuffers >= 3) {
2333 nativeWindowSurface->preallocateBuffers();
2334 }
2335
2336 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2338 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002342 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002343 hw->setLayerStack(state.layerStack);
2344 hw->setProjection(state.orientation, state.viewport, state.frame);
2345 hw->setDisplayName(state.displayName);
2346
2347 return hw;
2348}
2349
Lloyd Pique347200f2017-12-14 17:00:15 -08002350void SurfaceFlinger::processDisplayChangesLocked() {
2351 // here we take advantage of Vector's copy-on-write semantics to
2352 // improve performance by skipping the transaction entirely when
2353 // know that the lists are identical
2354 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2355 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2356 if (!curr.isIdenticalTo(draw)) {
2357 mVisibleRegionsDirty = true;
2358 const size_t cc = curr.size();
2359 size_t dc = draw.size();
2360
2361 // find the displays that were removed
2362 // (ie: in drawing state but not in current state)
2363 // also handle displays that changed
2364 // (ie: displays that are in both lists)
2365 for (size_t i = 0; i < dc;) {
2366 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2367 if (j < 0) {
2368 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002369 // Call makeCurrent() on the primary display so we can
2370 // be sure that nothing associated with this display
2371 // is current.
2372 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2373 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2374 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2375 if (hw != nullptr) hw->disconnect(getHwComposer());
2376 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2377 mEventThread->onHotplugReceived(draw[i].type, false);
2378 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002379 } else {
2380 // this display is in both lists. see if something changed.
2381 const DisplayDeviceState& state(curr[j]);
2382 const wp<IBinder>& display(curr.keyAt(j));
2383 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2384 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2385 if (state_binder != draw_binder) {
2386 // changing the surface is like destroying and
2387 // recreating the DisplayDevice, so we just remove it
2388 // from the drawing state, so that it get re-added
2389 // below.
2390 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2391 if (hw != nullptr) hw->disconnect(getHwComposer());
2392 mDisplays.removeItem(display);
2393 mDrawingState.displays.removeItemsAt(i);
2394 dc--;
2395 // at this point we must loop to the next item
2396 continue;
2397 }
2398
2399 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2400 if (disp != nullptr) {
2401 if (state.layerStack != draw[i].layerStack) {
2402 disp->setLayerStack(state.layerStack);
2403 }
2404 if ((state.orientation != draw[i].orientation) ||
2405 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2406 disp->setProjection(state.orientation, state.viewport, state.frame);
2407 }
2408 if (state.width != draw[i].width || state.height != draw[i].height) {
2409 disp->setDisplaySize(state.width, state.height);
2410 }
2411 }
2412 }
2413 ++i;
2414 }
2415
2416 // find displays that were added
2417 // (ie: in current state but not in drawing state)
2418 for (size_t i = 0; i < cc; i++) {
2419 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2420 const DisplayDeviceState& state(curr[i]);
2421
2422 sp<DisplaySurface> dispSurface;
2423 sp<IGraphicBufferProducer> producer;
2424 sp<IGraphicBufferProducer> bqProducer;
2425 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002426 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002427
2428 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002429 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002430 // Virtual displays without a surface are dormant:
2431 // they have external state (layer stack, projection,
2432 // etc.) but no internal state (i.e. a DisplayDevice).
2433 if (state.surface != nullptr) {
2434 // Allow VR composer to use virtual displays.
2435 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2436 int width = 0;
2437 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2438 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2439 int height = 0;
2440 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2441 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2442 int intFormat = 0;
2443 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2444 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002445 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002446
2447 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2448 }
2449
2450 // TODO: Plumb requested format back up to consumer
2451
2452 sp<VirtualDisplaySurface> vds =
2453 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2454 bqProducer, bqConsumer,
2455 state.displayName);
2456
2457 dispSurface = vds;
2458 producer = vds;
2459 }
2460 } else {
2461 ALOGE_IF(state.surface != nullptr,
2462 "adding a supported display, but rendering "
2463 "surface is provided (%p), ignoring it",
2464 state.surface.get());
2465
2466 hwcId = state.type;
2467 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2468 producer = bqProducer;
2469 }
2470
2471 const wp<IBinder>& display(curr.keyAt(i));
2472 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473 mDisplays.add(display,
2474 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2475 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002476 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 mEventThread->onHotplugReceived(state.type, true);
2478 }
2479 }
2480 }
2481 }
2482 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002483
2484 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002485}
2486
Mathias Agopian87baae12012-07-31 12:38:26 -07002487void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002488{
Dan Stoza7dde5992015-05-22 09:51:44 -07002489 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002490 mCurrentState.traverseInZOrder([](Layer* layer) {
2491 layer->notifyAvailableFrames();
2492 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002493
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494 /*
2495 * Traversal of the children
2496 * (perform the transaction for each of them if needed)
2497 */
2498
Mathias Agopian3559b072012-08-15 13:46:03 -07002499 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002500 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002502 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503
2504 const uint32_t flags = layer->doTransaction(0);
2505 if (flags & Layer::eVisibleRegion)
2506 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002507 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 }
2509
2510 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002511 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 */
2513
Mathias Agopiane57f2922012-08-09 16:29:12 -07002514 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002516 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002517 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002519 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002520 // The transform hint might have changed for some layers
2521 // (either because a display has changed, or because a layer
2522 // as changed).
2523 //
2524 // Walk through all the layers in currentLayers,
2525 // and update their transform hint.
2526 //
2527 // If a layer is visible only on a single display, then that
2528 // display is used to calculate the hint, otherwise we use the
2529 // default display.
2530 //
2531 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2532 // the hint is set before we acquire a buffer from the surface texture.
2533 //
2534 // NOTE: layer transactions have taken place already, so we use their
2535 // drawing state. However, SurfaceFlinger's own transaction has not
2536 // happened yet, so we must use the current state layer list
2537 // (soon to become the drawing state list).
2538 //
2539 sp<const DisplayDevice> disp;
2540 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002541 bool first = true;
2542 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002543 // NOTE: we rely on the fact that layers are sorted by
2544 // layerStack first (so we don't have to traverse the list
2545 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002546 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002547 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002548 currentlayerStack = layerStack;
2549 // figure out if this layerstack is mirrored
2550 // (more than one display) if so, pick the default display,
2551 // if not, pick the only display it's on.
2552 disp.clear();
2553 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2554 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002555 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002556 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002557 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002558 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002559 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002560 break;
2561 }
2562 }
2563 }
2564 }
Chet Haase91d25932013-04-11 15:24:55 -07002565
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002566 if (disp == nullptr) {
2567 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2568 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002569
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002570 // could be null when this layer is using a layerStack
2571 // that is not visible on any display. Also can occur at
2572 // screen off/on times.
2573 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002574 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002575
2576 // disp can be null if there is no display available at all to get
2577 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002578 if (disp != nullptr) {
2579 layer->updateTransformHint(disp);
2580 }
Robert Carr2047fae2016-11-28 14:09:09 -08002581
2582 first = false;
2583 });
Mathias Agopian84300952012-11-21 16:02:13 -08002584 }
2585
2586
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 /*
2588 * Perform our own transaction if needed
2589 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590
2591 if (mLayersAdded) {
2592 mLayersAdded = false;
2593 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 mVisibleRegionsDirty = true;
2595 }
2596
2597 // some layers might have been removed, so
2598 // we need to update the regions they're exposing.
2599 if (mLayersRemoved) {
2600 mLayersRemoved = false;
2601 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002602 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002604 // this layer is not visible anymore
2605 // TODO: we could traverse the tree from front to back and
2606 // compute the actual visible region
2607 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002608 Region visibleReg;
2609 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002610 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002611 }
Robert Carr2047fae2016-11-28 14:09:09 -08002612 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 }
2614
2615 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002616
2617 updateCursorAsync();
2618}
2619
2620void SurfaceFlinger::updateCursorAsync()
2621{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002622 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2623 auto& displayDevice = mDisplays[displayId];
2624 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002625 continue;
2626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627
2628 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2629 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002630 }
2631 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002632}
2633
2634void SurfaceFlinger::commitTransaction()
2635{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002636 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 for (const auto& l : mLayersPendingRemoval) {
2639 recordBufferingStats(l->getName().string(),
2640 l->getOccupancyHistory(true));
2641 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 }
2643 mLayersPendingRemoval.clear();
2644 }
2645
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002646 // If this transaction is part of a window animation then the next frame
2647 // we composite should be considered an animation as well.
2648 mAnimCompositionPending = mAnimTransactionPending;
2649
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 mDrawingState.traverseInZOrder([](Layer* layer) {
2652 layer->commitChildList();
2653 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002654 mTransactionPending = false;
2655 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002656 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657}
2658
Chia-I Wuab0c3192017-08-01 11:29:00 -07002659void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002660 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661{
Mathias Agopian841cde52012-03-01 15:44:37 -08002662 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 Region aboveOpaqueLayers;
2666 Region aboveCoveredLayers;
2667 Region dirty;
2668
Mathias Agopian87baae12012-07-31 12:38:26 -07002669 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670
Robert Carr2047fae2016-11-28 14:09:09 -08002671 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002673 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674
Jesse Hall01e29052013-02-19 16:13:35 -08002675 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002676 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002677 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002678
Mathias Agopianab028732010-03-16 16:41:46 -07002679 /*
2680 * opaqueRegion: area of a surface that is fully opaque.
2681 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002683
2684 /*
2685 * visibleRegion: area of a surface that is visible on screen
2686 * and not fully transparent. This is essentially the layer's
2687 * footprint minus the opaque regions above it.
2688 * Areas covered by a translucent surface are considered visible.
2689 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002691
2692 /*
2693 * coveredRegion: area of a surface that is covered by all
2694 * visible regions above it (which includes the translucent areas).
2695 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002697
Jesse Halla8026d22012-09-25 13:25:04 -07002698 /*
2699 * transparentRegion: area of a surface that is hinted to be completely
2700 * transparent. This is only used to tell when the layer has no visible
2701 * non-transparent regions and can be removed from the layer list. It
2702 * does not affect the visibleRegion of this layer or any layers
2703 * beneath it. The hint may not be correct if apps don't respect the
2704 * SurfaceView restrictions (which, sadly, some don't).
2705 */
2706 Region transparentRegion;
2707
Mathias Agopianab028732010-03-16 16:41:46 -07002708
2709 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002710 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002711 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002712 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002714 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002715 if (!visibleRegion.isEmpty()) {
2716 // Remove the transparent area from the visible region
2717 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002718 if (tr.preserveRects()) {
2719 // transform the transparent region
2720 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002722 // transformation too complex, can't do the
2723 // transparent region optimization.
2724 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 }
Mathias Agopianab028732010-03-16 16:41:46 -07002726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727
Mathias Agopianab028732010-03-16 16:41:46 -07002728 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002730 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002731 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2732 // the opaque region is the layer's footprint
2733 opaqueRegion = visibleRegion;
2734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 }
2736 }
2737
Robert Carre5f4f692018-01-12 13:12:28 -08002738 if (visibleRegion.isEmpty()) {
2739 layer->clearVisibilityRegions();
2740 return;
2741 }
2742
Mathias Agopianab028732010-03-16 16:41:46 -07002743 // Clip the covered region to the visible region
2744 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2745
2746 // Update aboveCoveredLayers for next (lower) layer
2747 aboveCoveredLayers.orSelf(visibleRegion);
2748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749 // subtract the opaque region covered by the layers above us
2750 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751
2752 // compute this layer's dirty region
2753 if (layer->contentDirty) {
2754 // we need to invalidate the whole region
2755 dirty = visibleRegion;
2756 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002757 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 layer->contentDirty = false;
2759 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002760 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002761 * the exposed region consists of two components:
2762 * 1) what's VISIBLE now and was COVERED before
2763 * 2) what's EXPOSED now less what was EXPOSED before
2764 *
2765 * note that (1) is conservative, we start with the whole
2766 * visible region but only keep what used to be covered by
2767 * something -- which mean it may have been exposed.
2768 *
2769 * (2) handles areas that were not covered by anything but got
2770 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002771 */
Mathias Agopianab028732010-03-16 16:41:46 -07002772 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002773 const Region oldVisibleRegion = layer->visibleRegion;
2774 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002775 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2776 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 }
2778 dirty.subtractSelf(aboveOpaqueLayers);
2779
2780 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002781 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782
Mathias Agopianab028732010-03-16 16:41:46 -07002783 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002785
Jesse Halla8026d22012-09-25 13:25:04 -07002786 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 layer->setVisibleRegion(visibleRegion);
2788 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002789 layer->setVisibleNonTransparentRegion(
2790 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002791 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792
Mathias Agopian87baae12012-07-31 12:38:26 -07002793 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794}
2795
Chia-I Wuab0c3192017-08-01 11:29:00 -07002796void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002797 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002798 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002799 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002800 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002801 }
2802 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002803}
2804
Dan Stoza6b9454d2014-11-07 16:00:59 -08002805bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 ALOGV("handlePageFlip");
2808
Brian Andersond6927fb2016-07-23 23:37:30 -07002809 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002812 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002813 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002814
2815 // Store the set of layers that need updates. This set must not change as
2816 // buffers are being latched, as this could result in a deadlock.
2817 // Example: Two producers share the same command stream and:
2818 // 1.) Layer 0 is latched
2819 // 2.) Layer 0 gets a new frame
2820 // 2.) Layer 1 gets a new frame
2821 // 3.) Layer 1 is latched.
2822 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2823 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002824 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825 if (layer->hasQueuedFrame()) {
2826 frameQueued = true;
2827 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002828 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002829 } else {
2830 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002831 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002832 } else {
2833 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002834 }
Robert Carr2047fae2016-11-28 14:09:09 -08002835 });
2836
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002838 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002839 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002840 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002841 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002842 newDataLatched = true;
2843 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002844 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002845
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002846 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002847
2848 // If we will need to wake up at some time in the future to deal with a
2849 // queued frame that shouldn't be displayed during this vsync period, wake
2850 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002851 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002852 signalLayerUpdate();
2853 }
2854
2855 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002856 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857}
2858
Mathias Agopianad456f92011-01-13 17:53:01 -08002859void SurfaceFlinger::invalidateHwcGeometry()
2860{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002862}
2863
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002864
Fabien Sanglard830b8472016-11-30 16:35:58 -08002865void SurfaceFlinger::doDisplayComposition(
2866 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002867 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868{
Dan Stoza71433162014-02-04 16:22:36 -08002869 // We only need to actually compose the display if:
2870 // 1) It is being handled by hardware composer, which may need this to
2871 // keep its virtual display state machine in sync, or
2872 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002873 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002874 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002876 return;
2877 }
2878
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002880 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002881
2882 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002883 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884}
2885
Chia-I Wub02087d2017-11-09 10:19:54 -08002886bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002887{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002889
Chia-I Wub02087d2017-11-09 10:19:54 -08002890 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002891 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002893 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2894 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2895 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2896 HWC2::Capability::SkipClientColorTransform);
2897 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002898
2899 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002900 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2901 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002902 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002903 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002904 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002905 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002906 }
2907
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 if (hasClientComposition) {
2909 ALOGV("hasClientComposition");
2910
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002911 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002912 if (displayDevice->hasWideColorGamut()) {
2913 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002914 }
2915 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002916 getBE().mRenderEngine->setDisplayMaxLuminance(
2917 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002918
Chia-I Wu7f402902017-11-09 12:51:10 -08002919 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002920 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002921 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002922 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002923
2924 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002925 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002926 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2927 }
2928 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002929 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002930
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002931 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 // when using overlays, we assume a fully transparent framebuffer
2934 // NOTE: we could reduce how much we need to clear, for instance
2935 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002936 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002938 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002940 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002941 // we're left with the letterbox region
2942 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002944
2945 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002947
Mathias Agopianb9494d52012-04-18 02:28:45 -07002948 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002949 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002950 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002952 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002953 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002954
Dominik Laskowski281644e2018-04-19 15:47:35 -07002955 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002956 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957 // scissor on the main display. It should never be needed
2958 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 const Rect& bounds(displayDevice->getBounds());
2960 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002961 if (scissor != bounds) {
2962 // scissor doesn't match the screen's dimensions, so we
2963 // need to clear everything outside of it and enable
2964 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002965
Mathias Agopianf45c5102012-10-24 16:29:17 -07002966 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002968 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002969 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002970 }
2971 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002972 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002973
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 /*
2975 * and then, render the layers targeted at the framebuffer
2976 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002977
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 ALOGV("Rendering client layers");
2979 const Transform& displayTransform = displayDevice->getTransform();
2980 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002981 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 bool firstLayer = true;
2983 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002984 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 displayTransform.transform(layer->visibleRegion)));
2986 ALOGV("Layer: %s", layer->getName().string());
2987 ALOGV(" Composition type: %s",
2988 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002989 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 switch (layer->getCompositionType(hwcId)) {
2991 case HWC2::Composition::Cursor:
2992 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002993 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002995 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002997 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002998 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002999 // never clear the very first layer since we're
3000 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07003001 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003002 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003003 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003004 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003005 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003006 // Only apply saturation matrix layer that is legacy SRGB dataspace
3007 // when auto color mode is on.
3008 bool restore = false;
3009 mat4 savedMatrix;
3010 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3011 layer->isLegacySrgbDataSpace()) {
3012 savedMatrix =
3013 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3014 restore = true;
3015 }
chaviwa76b2712017-09-20 12:02:26 -07003016 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003017 if (restore) {
3018 getRenderEngine().setupColorTransform(savedMatrix);
3019 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003020 break;
3021 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003022 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003023 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003024 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 } else {
3026 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003027 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003029 }
3030 } else {
3031 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003033 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003035 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003036 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003037 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003038 }
3039 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003040
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003041 if (applyColorMatrix) {
3042 getRenderEngine().setupColorTransform(oldColorMatrix);
3043 }
3044
Mathias Agopianf45c5102012-10-24 16:29:17 -07003045 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003046 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003047 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048}
3049
Fabien Sanglard830b8472016-11-30 16:35:58 -08003050void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3051 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003052 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003053 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054}
3055
Dan Stoza7d89d062015-04-30 13:29:25 -07003056status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003057 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003058 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003059 const sp<Layer>& lbc,
3060 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003061{
Dan Stoza7d89d062015-04-30 13:29:25 -07003062 // add this layer to the current state list
3063 {
3064 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003066 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3067 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003068 return NO_MEMORY;
3069 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003070 if (parent == nullptr) {
3071 mCurrentState.layersSortedByZ.add(lbc);
3072 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003073 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003074 ALOGE("addClientLayer called with a removed parent");
3075 return NAME_NOT_FOUND;
3076 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 parent->addChild(lbc);
3078 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003079
Dan Stoza101d8dc2018-02-27 15:42:25 -08003080 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003081 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3082 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3083 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3084 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3085 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersAdded = true;
3087 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003088 }
3089
Mathias Agopian96f08192010-06-02 23:28:45 -07003090 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003091 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003092
Dan Stoza7d89d062015-04-30 13:29:25 -07003093 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003094}
3095
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003096status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003097 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003098 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3099}
Robert Carr7f9b8992017-03-10 11:08:39 -08003100
chaviwca27f252018-02-06 16:46:39 -08003101status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3102 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003103 if (layer->isPendingRemoval()) {
3104 return NO_ERROR;
3105 }
3106
Robert Carr1f0a16a2016-10-24 16:27:39 -07003107 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003108 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003109 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003110 if (topLevelOnly) {
3111 return NO_ERROR;
3112 }
3113
Chia-I Wu98f1c102017-05-30 14:54:08 -07003114 sp<Layer> ancestor = p;
3115 while (ancestor->getParent() != nullptr) {
3116 ancestor = ancestor->getParent();
3117 }
3118 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3119 ALOGE("removeLayer called with a layer whose parent has been removed");
3120 return NAME_NOT_FOUND;
3121 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003122
3123 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003124 } else {
3125 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003126 }
3127
Robert Carr136e2f62017-02-08 17:54:29 -08003128 // As a matter of normal operation, the LayerCleaner will produce a second
3129 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3130 // so we will succeed in promoting it, but it's already been removed
3131 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3132 // otherwise something has gone wrong and we are leaking the layer.
3133 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3135 layer->getName().string(),
3136 (p != nullptr) ? p->getName().string() : "no-parent");
3137 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003138 } else if (index < 0) {
3139 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003140 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003141
Chia-I Wuc6657022017-08-15 11:18:17 -07003142 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 mLayersPendingRemoval.add(layer);
3144 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003145 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003146 setTransactionFlags(eTransactionNeeded);
3147 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148}
3149
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003150uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003151 return android_atomic_release_load(&mTransactionFlags);
3152}
3153
Mathias Agopian3f844832013-08-07 21:24:32 -07003154uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3156}
3157
Mathias Agopian3f844832013-08-07 21:24:32 -07003158uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003159 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3160}
3161
3162uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3163 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003165 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003167 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
3169 return old;
3170}
3171
chaviwca27f252018-02-06 16:46:39 -08003172bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3173 for (const ComposerState& state : states) {
3174 // Here we need to check that the interface we're given is indeed
3175 // one of our own. A malicious client could give us a nullptr
3176 // IInterface, or one of its own or even one of our own but a
3177 // different type. All these situations would cause us to crash.
3178 if (state.client == nullptr) {
3179 return true;
3180 }
3181
3182 sp<IBinder> binder = IInterface::asBinder(state.client);
3183 if (binder == nullptr) {
3184 return true;
3185 }
3186
3187 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3188 return true;
3189 }
3190 }
3191 return false;
3192}
3193
Mathias Agopian8b33f032012-07-24 20:43:54 -07003194void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003195 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003196 const Vector<DisplayState>& displays,
3197 uint32_t flags)
3198{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003199 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003200 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003201 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003202
chaviwca27f252018-02-06 16:46:39 -08003203 if (containsAnyInvalidClientState(states)) {
3204 return;
3205 }
3206
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 // For window updates that are part of an animation we must wait for
3209 // previous animation "frames" to be handled.
3210 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003214 // caller after a few seconds.
3215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3216 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003217 mAnimTransactionPending = false;
3218 break;
3219 }
3220 }
3221 }
3222
chaviwca27f252018-02-06 16:46:39 -08003223 for (const DisplayState& display : displays) {
3224 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003225 }
3226
chaviwca27f252018-02-06 16:46:39 -08003227 for (const ComposerState& state : states) {
3228 transactionFlags |= setClientStateLocked(state);
3229 }
3230
3231 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3232 // as destroyed should only occur after setting all other states. This is to allow for a
3233 // child re-parent to happen before marking its original parent as destroyed (which would
3234 // then mark the child as destroyed).
3235 for (const ComposerState& state : states) {
3236 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003237 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003238
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003239 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3240 // anyway. This can be used as a flush mechanism for previous async transactions.
3241 // Empty animation transaction can be used to simulate back-pressure, so also force a
3242 // transaction for empty animation transactions.
3243 if (transactionFlags == 0 &&
3244 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003245 transactionFlags = eTransactionNeeded;
3246 }
3247
Mathias Agopian386aa982011-11-07 21:58:03 -08003248 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003249 if (mInterceptor->isEnabled()) {
3250 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003251 }
Irvel468051e2016-06-13 16:44:44 -07003252
Mathias Agopian386aa982011-11-07 21:58:03 -08003253 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003254 const auto start = (flags & eEarlyWakeup)
3255 ? VSyncModulator::TransactionStart::EARLY
3256 : VSyncModulator::TransactionStart::NORMAL;
3257 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003258
3259 // if this is a synchronous transaction, wait for it to take effect
3260 // before returning.
3261 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003263 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003264 if (flags & eAnimation) {
3265 mAnimTransactionPending = true;
3266 }
3267 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3269 if (CC_UNLIKELY(err != NO_ERROR)) {
3270 // just in case something goes wrong in SF, return to the
3271 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003272 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3273 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003274 break;
3275 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 }
3278}
3279
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3281{
Jesse Hall9a143922012-10-04 16:29:19 -07003282 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3283 if (dpyIdx < 0)
3284 return 0;
3285
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003287 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003288 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289 const uint32_t what = s.what;
3290 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003291 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 disp.surface = s.surface;
3293 flags |= eDisplayTransactionNeeded;
3294 }
3295 }
3296 if (what & DisplayState::eLayerStackChanged) {
3297 if (disp.layerStack != s.layerStack) {
3298 disp.layerStack = s.layerStack;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003302 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003303 if (disp.orientation != s.orientation) {
3304 disp.orientation = s.orientation;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 if (disp.frame != s.frame) {
3308 disp.frame = s.frame;
3309 flags |= eDisplayTransactionNeeded;
3310 }
3311 if (disp.viewport != s.viewport) {
3312 disp.viewport = s.viewport;
3313 flags |= eDisplayTransactionNeeded;
3314 }
3315 }
Michael Lentine47e45402014-07-18 15:34:25 -07003316 if (what & DisplayState::eDisplaySizeChanged) {
3317 if (disp.width != s.width) {
3318 disp.width = s.width;
3319 flags |= eDisplayTransactionNeeded;
3320 }
3321 if (disp.height != s.height) {
3322 disp.height = s.height;
3323 flags |= eDisplayTransactionNeeded;
3324 }
3325 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003326 }
3327 return flags;
3328}
3329
chaviwca27f252018-02-06 16:46:39 -08003330uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3331 const layer_state_t& s = composerState.state;
3332 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3333
Mathias Agopian13127d82013-03-05 17:47:11 -08003334 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003335 if (layer == nullptr) {
3336 return 0;
3337 }
3338
3339 if (layer->isPendingRemoval()) {
3340 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3341 return 0;
3342 }
3343
3344 uint32_t flags = 0;
3345
3346 const uint32_t what = s.what;
3347 bool geometryAppliesWithResize =
3348 what & layer_state_t::eGeometryAppliesWithResize;
3349 if (what & layer_state_t::ePositionChanged) {
3350 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3351 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003352 }
chaviw8b3871a2017-11-01 17:41:01 -07003353 }
3354 if (what & layer_state_t::eLayerChanged) {
3355 // NOTE: index needs to be calculated before we update the state
3356 const auto& p = layer->getParent();
3357 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003358 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003359 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003360 mCurrentState.layersSortedByZ.removeAt(idx);
3361 mCurrentState.layersSortedByZ.add(layer);
3362 // we need traversal (state changed)
3363 // AND transaction (list changed)
3364 flags |= eTransactionNeeded|eTraversalNeeded;
3365 }
chaviw8b3871a2017-11-01 17:41:01 -07003366 } else {
3367 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003368 flags |= eTransactionNeeded|eTraversalNeeded;
3369 }
3370 }
chaviw8b3871a2017-11-01 17:41:01 -07003371 }
3372 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003373 // NOTE: index needs to be calculated before we update the state
3374 const auto& p = layer->getParent();
3375 if (p == nullptr) {
3376 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3377 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3378 mCurrentState.layersSortedByZ.removeAt(idx);
3379 mCurrentState.layersSortedByZ.add(layer);
3380 // we need traversal (state changed)
3381 // AND transaction (list changed)
3382 flags |= eTransactionNeeded|eTraversalNeeded;
3383 }
3384 } else {
3385 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3386 flags |= eTransactionNeeded|eTraversalNeeded;
3387 }
chaviw8b3871a2017-11-01 17:41:01 -07003388 }
3389 }
3390 if (what & layer_state_t::eSizeChanged) {
3391 if (layer->setSize(s.w, s.h)) {
3392 flags |= eTraversalNeeded;
3393 }
3394 }
3395 if (what & layer_state_t::eAlphaChanged) {
3396 if (layer->setAlpha(s.alpha))
3397 flags |= eTraversalNeeded;
3398 }
3399 if (what & layer_state_t::eColorChanged) {
3400 if (layer->setColor(s.color))
3401 flags |= eTraversalNeeded;
3402 }
3403 if (what & layer_state_t::eMatrixChanged) {
3404 if (layer->setMatrix(s.matrix))
3405 flags |= eTraversalNeeded;
3406 }
3407 if (what & layer_state_t::eTransparentRegionChanged) {
3408 if (layer->setTransparentRegionHint(s.transparentRegion))
3409 flags |= eTraversalNeeded;
3410 }
3411 if (what & layer_state_t::eFlagsChanged) {
3412 if (layer->setFlags(s.flags, s.mask))
3413 flags |= eTraversalNeeded;
3414 }
3415 if (what & layer_state_t::eCropChanged) {
3416 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3417 flags |= eTraversalNeeded;
3418 }
3419 if (what & layer_state_t::eFinalCropChanged) {
3420 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3421 flags |= eTraversalNeeded;
3422 }
3423 if (what & layer_state_t::eLayerStackChanged) {
3424 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3425 // We only allow setting layer stacks for top level layers,
3426 // everything else inherits layer stack from its parent.
3427 if (layer->hasParent()) {
3428 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3429 layer->getName().string());
3430 } else if (idx < 0) {
3431 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3432 "that also does not appear in the top level layer list. Something"
3433 " has gone wrong.", layer->getName().string());
3434 } else if (layer->setLayerStack(s.layerStack)) {
3435 mCurrentState.layersSortedByZ.removeAt(idx);
3436 mCurrentState.layersSortedByZ.add(layer);
3437 // we need traversal (state changed)
3438 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003439 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003440 }
3441 }
3442 if (what & layer_state_t::eDeferTransaction) {
3443 if (s.barrierHandle != nullptr) {
3444 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3445 } else if (s.barrierGbp != nullptr) {
3446 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3447 if (authenticateSurfaceTextureLocked(gbp)) {
3448 const auto& otherLayer =
3449 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3450 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3451 } else {
3452 ALOGE("Attempt to defer transaction to to an"
3453 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003454 }
3455 }
chaviw8b3871a2017-11-01 17:41:01 -07003456 // We don't trigger a traversal here because if no other state is
3457 // changed, we don't want this to cause any more work
3458 }
3459 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003460 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003461 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003462 if (!hadParent) {
3463 mCurrentState.layersSortedByZ.remove(layer);
3464 }
chaviw8b3871a2017-11-01 17:41:01 -07003465 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003466 }
chaviw8b3871a2017-11-01 17:41:01 -07003467 }
3468 if (what & layer_state_t::eReparentChildren) {
3469 if (layer->reparentChildren(s.reparentHandle)) {
3470 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003471 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003472 }
chaviw8b3871a2017-11-01 17:41:01 -07003473 if (what & layer_state_t::eDetachChildren) {
3474 layer->detachChildren();
3475 }
3476 if (what & layer_state_t::eOverrideScalingModeChanged) {
3477 layer->setOverrideScalingMode(s.overrideScalingMode);
3478 // We don't trigger a traversal here because if no other state is
3479 // changed, we don't want this to cause any more work
3480 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003481 return flags;
3482}
3483
chaviwca27f252018-02-06 16:46:39 -08003484void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3485 const layer_state_t& state = composerState.state;
3486 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3487
3488 sp<Layer> layer(client->getLayerUser(state.surface));
3489 if (layer == nullptr) {
3490 return;
3491 }
3492
3493 if (layer->isPendingRemoval()) {
3494 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3495 return;
3496 }
3497
3498 if (state.what & layer_state_t::eDestroySurface) {
3499 removeLayerLocked(mStateLock, layer);
3500 }
3501}
3502
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003504 const String8& name,
3505 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003506 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003507 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003508 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003510 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003511 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003512 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003514 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003515
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 status_t result = NO_ERROR;
3517
3518 sp<Layer> layer;
3519
Cody Northropbc755282017-03-31 12:00:08 -06003520 String8 uniqueName = getUniqueLayerName(name);
3521
Mathias Agopian3165cc22012-08-08 19:42:09 -07003522 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3523 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003524 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003525 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003526 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 break;
chaviw13fdc492017-06-27 12:40:18 -07003529 case ISurfaceComposerClient::eFXSurfaceColor:
3530 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003531 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003532 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003533 break;
3534 default:
3535 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 break;
3537 }
3538
Dan Stoza7d89d062015-04-30 13:29:25 -07003539 if (result != NO_ERROR) {
3540 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003542
Chia-I Wuab0c3192017-08-01 11:29:00 -07003543 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3544 // TODO b/64227542
3545 if (windowType == 441731) {
3546 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3547 layer->setPrimaryDisplayOnly();
3548 }
3549
Albert Chaulk479c60c2017-01-27 14:21:34 -05003550 layer->setInfo(windowType, ownerUid);
3551
Robert Carr1f0a16a2016-10-24 16:27:39 -07003552 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003553 if (result != NO_ERROR) {
3554 return result;
3555 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003556 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003557
3558 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003559 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560}
3561
Cody Northropbc755282017-03-31 12:00:08 -06003562String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3563{
3564 bool matchFound = true;
3565 uint32_t dupeCounter = 0;
3566
3567 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3568 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3569
3570 // Loop over layers until we're sure there is no matching name
3571 while (matchFound) {
3572 matchFound = false;
3573 mDrawingState.traverseInZOrder([&](Layer* layer) {
3574 if (layer->getName() == uniqueName) {
3575 matchFound = true;
3576 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3577 }
3578 });
3579 }
3580
3581 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3582
3583 return uniqueName;
3584}
3585
David Sodman0c69cad2017-08-21 12:12:51 -07003586status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003587 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3588 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589{
3590 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003591 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 case PIXEL_FORMAT_TRANSPARENT:
3593 case PIXEL_FORMAT_TRANSLUCENT:
3594 format = PIXEL_FORMAT_RGBA_8888;
3595 break;
3596 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003597 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 break;
3599 }
3600
David Sodman0c69cad2017-08-21 12:12:51 -07003601 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3602 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003604 *handle = layer->getHandle();
3605 *gbp = layer->getProducer();
3606 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608
David Sodman0c69cad2017-08-21 12:12:51 -07003609 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611}
3612
chaviw13fdc492017-06-27 12:40:18 -07003613status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003615 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616{
chaviw13fdc492017-06-27 12:40:18 -07003617 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003620}
3621
Mathias Agopianac9fa422013-02-11 16:40:36 -08003622status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623{
Robert Carr9524cb32017-02-13 11:32:32 -08003624 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003625 status_t err = NO_ERROR;
3626 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003627 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003628 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003629 err = removeLayer(l);
3630 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3631 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003632 }
3633 return err;
3634}
3635
Mathias Agopian13127d82013-03-05 17:47:11 -08003636status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003637{
Mathias Agopian67106042013-03-14 19:18:13 -07003638 // called by ~LayerCleaner() when all references to the IBinder (handle)
3639 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003640 sp<Layer> l = layer.promote();
3641 if (l == nullptr) {
3642 // The layer has already been removed, carry on
3643 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003644 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003645 // If we have a parent, then we can continue to live as long as it does.
3646 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647}
3648
Mathias Agopianb60314a2012-04-10 22:09:54 -07003649// ---------------------------------------------------------------------------
3650
Andy McFadden13a082e2012-08-24 10:16:42 -07003651void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003652 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003653 Vector<ComposerState> state;
3654 Vector<DisplayState> displays;
3655 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003656 d.what = DisplayState::eDisplayProjectionChanged |
3657 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003658 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003659 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003660 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003661 d.frame.makeInvalid();
3662 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003663 d.width = 0;
3664 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003665 displays.add(d);
3666 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003667 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3668 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003669
David Sodman105b7dc2017-11-04 20:28:14 -07003670 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003671 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003672 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003673
Brian Andersond0010582017-03-07 13:20:31 -08003674 // Use phase of 0 since phase is not known.
3675 // Use latency of 0, which will snap to the ideal latency.
3676 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003677}
3678
3679void SurfaceFlinger::initializeDisplays() {
3680 class MessageScreenInitialized : public MessageBase {
3681 SurfaceFlinger* flinger;
3682 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003683 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003684 virtual bool handler() {
3685 flinger->onInitializeDisplays();
3686 return true;
3687 }
3688 };
3689 sp<MessageBase> msg = new MessageScreenInitialized(this);
3690 postMessageAsync(msg); // we may be called from main thread, use async message
3691}
3692
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003693void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003694 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3696 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003697 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003700 return;
3701 }
3702
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003703 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003704 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 ALOGW("Trying to set power mode for virtual display");
3706 return;
3707 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003708
Lloyd Pique4dccc412018-01-22 17:21:36 -08003709 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003710 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003711 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3712 if (idx < 0) {
3713 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3714 return;
3715 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003716 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003717 }
3718
Dominik Laskowski281644e2018-04-19 15:47:35 -07003719 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003721 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003723 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724 // FIXME: eventthread only knows about the main display right now
3725 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003726 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003730 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003731 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003732
3733 struct sched_param param = {0};
3734 param.sched_priority = 1;
3735 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3736 ALOGW("Couldn't set SCHED_FIFO on display on");
3737 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003738 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003739 // Turn off the display
3740 struct sched_param param = {0};
3741 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3742 ALOGW("Couldn't set SCHED_OTHER on display off");
3743 }
3744
Dominik Laskowski281644e2018-04-19 15:47:35 -07003745 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003746 disableHardwareVsync(true); // also cancels any in-progress resync
3747
Mathias Agopiancde87a32012-09-13 14:09:01 -07003748 // FIXME: eventthread only knows about the main display right now
3749 mEventThread->onScreenReleased();
3750 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003751
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003752 getHwComposer().setPowerMode(type, mode);
3753 mVisibleRegionsDirty = true;
3754 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003755 } else if (mode == HWC_POWER_MODE_DOZE ||
3756 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003757 // Update display while dozing
3758 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003759 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003760 // FIXME: eventthread only knows about the main display right now
3761 mEventThread->onScreenAcquired();
3762 resyncToHardwareVsync(true);
3763 }
3764 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3765 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003766 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003767 disableHardwareVsync(true); // also cancels any in-progress resync
3768 // FIXME: eventthread only knows about the main display right now
3769 mEventThread->onScreenReleased();
3770 }
3771 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003773 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003776 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003777}
3778
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3780 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003781 SurfaceFlinger& mFlinger;
3782 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003783 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003784 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785 MessageSetPowerMode(SurfaceFlinger& flinger,
3786 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3787 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003788 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003789 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003790 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003791 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003792 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003793 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 ALOGW("Attempt to set power mode = %d for virtual display",
3795 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003796 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003797 mFlinger.setPowerModeInternal(
3798 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003799 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003800 return true;
3801 }
3802 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003804 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003805}
3806
3807// ---------------------------------------------------------------------------
3808
Lloyd Pique755e3192018-01-31 16:46:15 -08003809status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3810 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003812
Mathias Agopianbd115332013-04-18 16:41:04 -07003813 IPCThreadState* ipc = IPCThreadState::self();
3814 const int pid = ipc->getCallingPid();
3815 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003816
Mathias Agopianbd115332013-04-18 16:41:04 -07003817 if ((uid != AID_SHELL) &&
3818 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003819 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003820 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003822 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003823 // (this would indicate SF is stuck, but we want to be able to
3824 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003825 status_t err = mStateLock.timedLock(s2ns(1));
3826 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003827 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003828 result.appendFormat(
3829 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3830 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003831 }
3832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 bool dumpAll = true;
3834 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003835 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003836
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003838 if ((index < numArgs) &&
3839 (args[index] == String16("--list"))) {
3840 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003841 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003842 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843 }
3844
3845 if ((index < numArgs) &&
3846 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003848 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003849 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003850 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003851
3852 if ((index < numArgs) &&
3853 (args[index] == String16("--latency-clear"))) {
3854 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003855 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003856 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003857 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003858
3859 if ((index < numArgs) &&
3860 (args[index] == String16("--dispsync"))) {
3861 index++;
3862 mPrimaryDispSync.dump(result);
3863 dumpAll = false;
3864 }
Dan Stozab90cf072015-03-05 11:05:59 -08003865
3866 if ((index < numArgs) &&
3867 (args[index] == String16("--static-screen"))) {
3868 index++;
3869 dumpStaticScreenStats(result);
3870 dumpAll = false;
3871 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003872
3873 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003874 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003875 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003876 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003877 dumpAll = false;
3878 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003879
3880 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3881 index++;
3882 dumpWideColorInfo(result);
3883 dumpAll = false;
3884 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003885
3886 if ((index < numArgs) &&
3887 (args[index] == String16("--enable-layer-stats"))) {
3888 index++;
3889 mLayerStats.enable();
3890 dumpAll = false;
3891 }
3892
3893 if ((index < numArgs) &&
3894 (args[index] == String16("--disable-layer-stats"))) {
3895 index++;
3896 mLayerStats.disable();
3897 dumpAll = false;
3898 }
3899
3900 if ((index < numArgs) &&
3901 (args[index] == String16("--clear-layer-stats"))) {
3902 index++;
3903 mLayerStats.clear();
3904 dumpAll = false;
3905 }
3906
3907 if ((index < numArgs) &&
3908 (args[index] == String16("--dump-layer-stats"))) {
3909 index++;
3910 mLayerStats.dump(result);
3911 dumpAll = false;
3912 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003913
3914 if ((index < numArgs) &&
3915 (args[index] == String16("--display-identification"))) {
3916 index++;
3917 dumpDisplayIdentificationData(result);
3918 dumpAll = false;
3919 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003920
3921 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3922 index++;
3923 mTimeStats.parseArgs(asProto, args, index, result);
3924 dumpAll = false;
3925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003927
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003928 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003929 if (asProto) {
3930 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3931 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3932 } else {
3933 dumpAllLocked(args, index, result);
3934 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003935 }
3936
Mathias Agopian9795c422009-08-26 16:36:26 -07003937 if (locked) {
3938 mStateLock.unlock();
3939 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003940 }
3941 write(fd, result.string(), result.size());
3942 return NO_ERROR;
3943}
3944
Dan Stozac7014012014-02-14 15:03:43 -08003945void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3946 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003947{
Robert Carr2047fae2016-11-28 14:09:09 -08003948 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003949 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003950 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003951}
3952
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003953void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955{
3956 String8 name;
3957 if (index < args.size()) {
3958 name = String8(args[index]);
3959 index++;
3960 }
3961
David Sodman105b7dc2017-11-04 20:28:14 -07003962 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003963 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003964 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003965
3966 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003967 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003968 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003969 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003970 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003971 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003972 }
Robert Carr2047fae2016-11-28 14:09:09 -08003973 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974 }
3975}
3976
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003977void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003978 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979{
3980 String8 name;
3981 if (index < args.size()) {
3982 name = String8(args[index]);
3983 index++;
3984 }
3985
Robert Carr2047fae2016-11-28 14:09:09 -08003986 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003988 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 }
Robert Carr2047fae2016-11-28 14:09:09 -08003990 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003991
Svetoslavd85084b2014-03-20 10:28:31 -07003992 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003993}
3994
Jamie Gennis6547ff42013-07-16 20:12:42 -07003995// This should only be called from the main thread. Otherwise it would need
3996// the lock and should use mCurrentState rather than mDrawingState.
3997void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003998 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003999 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004000 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004001
4002 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4003}
4004
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004005void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004006{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004007 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004008
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004009 if (isLayerTripleBufferingDisabled())
4010 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004011
4012 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004013 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004014 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004015 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004016 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4017 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004018 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004019}
4020
Dan Stozab90cf072015-03-05 11:05:59 -08004021void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4022{
4023 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004024 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4025 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004026 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004027 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004028 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4029 b + 1, bucketTimeSec, percent);
4030 }
David Sodman4a36e932017-11-07 14:29:47 -08004031 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004032 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004033 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004035 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004036}
4037
Dan Stozae77c7662016-05-13 11:37:28 -07004038void SurfaceFlinger::recordBufferingStats(const char* layerName,
4039 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004040 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4041 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004042 for (const auto& segment : history) {
4043 if (!segment.usedThirdBuffer) {
4044 stats.twoBufferTime += segment.totalTime;
4045 }
4046 if (segment.occupancyAverage < 1.0f) {
4047 stats.doubleBufferedTime += segment.totalTime;
4048 } else if (segment.occupancyAverage < 2.0f) {
4049 stats.tripleBufferedTime += segment.totalTime;
4050 }
4051 ++stats.numSegments;
4052 stats.totalTime += segment.totalTime;
4053 }
4054}
4055
Brian Andersond6927fb2016-07-23 23:37:30 -07004056void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4057 result.appendFormat("Layer frame timestamps:\n");
4058
4059 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4060 const size_t count = currentLayers.size();
4061 for (size_t i=0 ; i<count ; i++) {
4062 currentLayers[i]->dumpFrameEvents(result);
4063 }
4064}
4065
Dan Stozae77c7662016-05-13 11:37:28 -07004066void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4067 result.append("Buffering stats:\n");
4068 result.append(" [Layer name] <Active time> <Two buffer> "
4069 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004070 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004071 typedef std::tuple<std::string, float, float, float> BufferTuple;
4072 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004073 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004074 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004075 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004076 if (stats.numSegments == 0) {
4077 continue;
4078 }
4079 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4080 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4081 stats.totalTime;
4082 float doubleBufferRatio = static_cast<float>(
4083 stats.doubleBufferedTime) / stats.totalTime;
4084 float tripleBufferRatio = static_cast<float>(
4085 stats.tripleBufferedTime) / stats.totalTime;
4086 sorted.insert({activeTime, {name, twoBufferRatio,
4087 doubleBufferRatio, tripleBufferRatio}});
4088 }
4089 for (const auto& sortedPair : sorted) {
4090 float activeTime = sortedPair.first;
4091 const BufferTuple& values = sortedPair.second;
4092 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4093 std::get<0>(values).c_str(), activeTime,
4094 std::get<1>(values), std::get<2>(values),
4095 std::get<3>(values));
4096 }
4097 result.append("\n");
4098}
4099
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004100void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4101 for (size_t d = 0; d < mDisplays.size(); d++) {
4102 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4103 const int32_t hwcId = displayDevice->getHwcDisplayId();
4104 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4105 if (!displayId) {
4106 continue;
4107 }
4108
4109 result.appendFormat("Display %d: ", hwcId);
4110 uint8_t port;
4111 DisplayIdentificationData data;
4112 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4113 result.append("no identification data\n");
4114 continue;
4115 }
4116
4117 if (!isEdid(data)) {
4118 result.append("unknown identification data: ");
4119 for (uint8_t byte : data) {
4120 result.appendFormat("%x ", byte);
4121 }
4122 result.append("\n");
4123 continue;
4124 }
4125
4126 const auto edid = parseEdid(data);
4127 if (!edid) {
4128 result.append("invalid EDID: ");
4129 for (uint8_t byte : data) {
4130 result.appendFormat("%x ", byte);
4131 }
4132 result.append("\n");
4133 continue;
4134 }
4135
4136 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4137 result.append(edid->displayName.data(), edid->displayName.length());
4138 result.append("\"\n");
4139 }
4140 result.append("\n");
4141}
4142
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004143void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4144 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004145 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004146
4147 // TODO: print out if wide-color mode is active or not
4148
4149 for (size_t d = 0; d < mDisplays.size(); d++) {
4150 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4151 int32_t hwcId = displayDevice->getHwcDisplayId();
4152 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4153 continue;
4154 }
4155
4156 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004157 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004158 for (auto&& mode : modes) {
4159 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4160 }
4161
Peiyong Lina52f0292018-03-14 17:26:31 -07004162 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004163 result.appendFormat(" Current color mode: %s (%d)\n",
4164 decodeColorMode(currentMode).c_str(), currentMode);
4165 }
4166 result.append("\n");
4167}
4168
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004169LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004170 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004171 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4172 const State& state = useDrawing ? mDrawingState : mCurrentState;
4173 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004174 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004175 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004176 });
4177
4178 return layersProto;
4179}
4180
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004181LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4182 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004183 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004184
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004185 SizeProto* resolution = layersProto.mutable_resolution();
4186 resolution->set_w(displayDevice->getWidth());
4187 resolution->set_h(displayDevice->getHeight());
4188
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004189 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4190 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4191 layersProto.set_global_transform(
4192 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4193
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004194 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004195 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004196 LayerProto* layerProto = layersProto.add_layers();
4197 layer->writeToProto(layerProto, hwcId);
4198 }
4199 });
4200
4201 return layersProto;
4202}
4203
Mathias Agopian74d211a2013-04-22 16:55:35 +02004204void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4205 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004206{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004207 bool colorize = false;
4208 if (index < args.size()
4209 && (args[index] == String16("--color"))) {
4210 colorize = true;
4211 index++;
4212 }
4213
4214 Colorizer colorizer(colorize);
4215
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004216 // figure out if we're stuck somewhere
4217 const nsecs_t now = systemTime();
4218 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4219 const nsecs_t inTransaction(mDebugInTransaction);
4220 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4221 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4222
4223 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004224 * Dump library configuration.
4225 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226
4227 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004228 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004230 appendSfConfigString(result);
4231 appendUiConfigString(result);
4232 appendGuiConfigString(result);
4233 result.append("\n");
4234
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004235 result.append("\nDisplay identification data:\n");
4236 dumpDisplayIdentificationData(result);
4237
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004238 result.append("\nWide-Color information:\n");
4239 dumpWideColorInfo(result);
4240
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004241 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004242 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004243 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004244 result.append(SyncFeatures::getInstance().toString());
4245 result.append("\n");
4246
David Sodman105b7dc2017-11-04 20:28:14 -07004247 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004248
Andy McFadden41d67d72014-04-25 16:58:34 -07004249 colorizer.bold(result);
4250 result.append("DispSync configuration: ");
4251 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004252 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4253 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4254 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004255 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004256 result.append("\n");
4257
Dan Stozab90cf072015-03-05 11:05:59 -08004258 // Dump static screen stats
4259 result.append("\n");
4260 dumpStaticScreenStats(result);
4261 result.append("\n");
4262
Dan Stozae77c7662016-05-13 11:37:28 -07004263 dumpBufferingStats(result);
4264
Andy McFadden4803b742012-09-24 19:07:20 -07004265 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 * Dump the visible layer list
4267 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004269 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004270 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4271 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004272 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004273
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004274 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004275 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004276 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004277 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278
4279 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004280 * Dump Display state
4281 */
4282
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004283 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004284 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004285 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004286 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4287 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004288 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004289 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004290 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004291
4292 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004293 * Dump SurfaceFlinger global state
4294 */
4295
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004296 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004297 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004298 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299
Mathias Agopian888c8222012-08-04 21:10:38 -07004300 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004301 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004302
David Sodmanbc815282017-11-05 18:57:52 -08004303 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004305 if (hw) {
4306 hw->undefinedRegion.dump(result, "undefinedRegion");
4307 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4308 hw->getOrientation(), hw->isDisplayOn());
4309 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004310 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004311 " last eglSwapBuffers() time: %f us\n"
4312 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004313 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314 " refresh-rate : %f fps\n"
4315 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004316 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004317 " gpu_to_cpu_unsupported : %d\n"
4318 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319 mLastSwapBufferTime/1000.0,
4320 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004321 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004322 1e9 / activeConfig->getVsyncPeriod(),
4323 activeConfig->getDpiX(),
4324 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004325 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004326
Mathias Agopian74d211a2013-04-22 16:55:35 +02004327 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329
Mathias Agopian74d211a2013-04-22 16:55:35 +02004330 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332
4333 /*
4334 * VSYNC state
4335 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004336 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004337 result.append("\n");
4338
4339 /*
4340 * HWC layer minidump
4341 */
4342 for (size_t d = 0; d < mDisplays.size(); d++) {
4343 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4344 int32_t hwcId = displayDevice->getHwcDisplayId();
4345 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4346 continue;
4347 }
4348
4349 result.appendFormat("Display %d HWC layers:\n", hwcId);
4350 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004351 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004352 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004353 });
Dan Stozae22aec72016-08-01 13:20:59 -07004354 result.append("\n");
4355 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004356
4357 /*
4358 * Dump HWComposer state
4359 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004360 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004361 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004363 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004364 result.appendFormat(" h/w composer %s\n",
4365 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004366 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367
4368 /*
4369 * Dump gralloc state
4370 */
4371 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4372 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004373
4374 /*
4375 * Dump VrFlinger state if in use.
4376 */
4377 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4378 result.append("VrFlinger state:\n");
4379 result.append(mVrFlinger->Dump().c_str());
4380 result.append("\n");
4381 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382}
4383
Mathias Agopian13127d82013-03-05 17:47:11 -08004384const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004385SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004386 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004387 wp<IBinder> dpy;
4388 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4389 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4390 dpy = mDisplays.keyAt(i);
4391 break;
4392 }
4393 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004394 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004395 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4396 // Just use the primary display so we have something to return
4397 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4398 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004399 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004400}
4401
Keun young Park63f165f2012-08-31 10:53:36 -07004402bool SurfaceFlinger::startDdmConnection()
4403{
4404 void* libddmconnection_dso =
4405 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4406 if (!libddmconnection_dso) {
4407 return false;
4408 }
4409 void (*DdmConnection_start)(const char* name);
4410 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004411 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004412 if (!DdmConnection_start) {
4413 dlclose(libddmconnection_dso);
4414 return false;
4415 }
4416 (*DdmConnection_start)(getServiceName());
4417 return true;
4418}
4419
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004420status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004421 switch (code) {
4422 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004423 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004425 case CLEAR_ANIMATION_FRAME_STATS:
4426 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004427 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004428 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004429 case ENABLE_VSYNC_INJECTIONS:
4430 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431 {
4432 // codes that require permission check
4433 IPCThreadState* ipc = IPCThreadState::self();
4434 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004435 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004436 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004437 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004438 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004439 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004440 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004441 break;
4442 }
Robert Carr1db73f62016-12-21 12:58:51 -08004443 /*
4444 * Calling setTransactionState is safe, because you need to have been
4445 * granted a reference to Client* and Handle* to do anything with it.
4446 *
4447 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4448 */
4449 case SET_TRANSACTION_STATE:
4450 case CREATE_SCOPED_CONNECTION:
4451 {
4452 return OK;
4453 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004454 case CAPTURE_SCREEN:
4455 {
4456 // codes that require permission check
4457 IPCThreadState* ipc = IPCThreadState::self();
4458 const int pid = ipc->getCallingPid();
4459 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004460 if ((uid != AID_GRAPHICS) &&
4461 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004462 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004463 return PERMISSION_DENIED;
4464 }
4465 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004466 }
chaviwa76b2712017-09-20 12:02:26 -07004467 case CAPTURE_LAYERS: {
4468 IPCThreadState* ipc = IPCThreadState::self();
4469 const int pid = ipc->getCallingPid();
4470 const int uid = ipc->getCallingUid();
4471 if ((uid != AID_GRAPHICS) &&
4472 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4473 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4474 return PERMISSION_DENIED;
4475 }
4476 break;
4477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004479 return OK;
4480}
4481
4482status_t SurfaceFlinger::onTransact(
4483 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4484{
4485 status_t credentialCheck = CheckTransactCodeCredentials(code);
4486 if (credentialCheck != OK) {
4487 return credentialCheck;
4488 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004489
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4491 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004492 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004493 IPCThreadState* ipc = IPCThreadState::self();
4494 const int uid = ipc->getCallingUid();
4495 if (CC_UNLIKELY(uid != AID_SYSTEM
4496 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004497 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004498 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004499 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004500 return PERMISSION_DENIED;
4501 }
4502 int n;
4503 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004504 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004505 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 return NO_ERROR;
4507 case 1002: // SHOW_UPDATES
4508 n = data.readInt32();
4509 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004510 invalidateHwcGeometry();
4511 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004512 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004514 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004515 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004517 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004518 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004519 setTransactionFlags(
4520 eTransactionNeeded|
4521 eDisplayTransactionNeeded|
4522 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004523 return NO_ERROR;
4524 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004525 case 1006:{ // send empty update
4526 signalRefresh();
4527 return NO_ERROR;
4528 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004529 case 1008: // toggle use of hw composer
4530 n = data.readInt32();
4531 mDebugDisableHWC = n ? 1 : 0;
4532 invalidateHwcGeometry();
4533 repaintEverything();
4534 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004535 case 1009: // toggle use of transform hint
4536 n = data.readInt32();
4537 mDebugDisableTransformHint = n ? 1 : 0;
4538 invalidateHwcGeometry();
4539 repaintEverything();
4540 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004542 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 reply->writeInt32(0);
4544 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004545 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004546 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004547 return NO_ERROR;
4548 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004549 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004550 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004551 return NO_ERROR;
4552 }
4553 case 1014: {
4554 // daltonize
4555 n = data.readInt32();
4556 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004557 case 1:
4558 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4559 break;
4560 case 2:
4561 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4562 break;
4563 case 3:
4564 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4565 break;
4566 default:
4567 mDaltonizer.setType(ColorBlindnessType::None);
4568 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004569 }
4570 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004571 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004572 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004573 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004574 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004575 invalidateHwcGeometry();
4576 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004577 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004578 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004579 case 1015: {
4580 // apply a color matrix
4581 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004582 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004583 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004584 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004585 for (size_t j = 0; j < 4; j++) {
4586 mColorMatrix[i][j] = data.readFloat();
4587 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004588 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004589 } else {
4590 mColorMatrix = mat4();
4591 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004592
4593 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4594 // the division by w in the fragment shader
4595 float4 lastRow(transpose(mColorMatrix)[3]);
4596 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4597 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4598 }
4599
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 invalidateHwcGeometry();
4601 repaintEverything();
4602 return NO_ERROR;
4603 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004604 // This is an experimental interface
4605 // Needs to be shifted to proper binder interface when we productize
4606 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004607 n = data.readInt32();
4608 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004609 return NO_ERROR;
4610 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004611 case 1017: {
4612 n = data.readInt32();
4613 mForceFullDamage = static_cast<bool>(n);
4614 return NO_ERROR;
4615 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004616 case 1018: { // Modify Choreographer's phase offset
4617 n = data.readInt32();
4618 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4619 return NO_ERROR;
4620 }
4621 case 1019: { // Modify SurfaceFlinger's phase offset
4622 n = data.readInt32();
4623 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4624 return NO_ERROR;
4625 }
Irvel468051e2016-06-13 16:44:44 -07004626 case 1020: { // Layer updates interceptor
4627 n = data.readInt32();
4628 if (n) {
4629 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004630 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004631 }
4632 else{
4633 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004634 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004635 }
4636 return NO_ERROR;
4637 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004638 case 1021: { // Disable HWC virtual displays
4639 n = data.readInt32();
4640 mUseHwcVirtualDisplays = !n;
4641 return NO_ERROR;
4642 }
Romain Guy0147a172017-06-01 13:53:56 -07004643 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004644 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004645
4646 invalidateHwcGeometry();
4647 repaintEverything();
4648 return NO_ERROR;
4649 }
Romain Guy54f154a2017-10-24 21:40:32 +01004650 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004651 int32_t value = data.readInt32();
4652 if (value > 2) {
4653 return BAD_VALUE;
4654 }
4655 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4656 return BAD_VALUE;
4657 }
Romain Guy54f154a2017-10-24 21:40:32 +01004658
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004659 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004660 invalidateHwcGeometry();
4661 repaintEverything();
4662 return NO_ERROR;
4663 }
4664 case 1024: { // Is wide color gamut rendering/color management supported?
4665 reply->writeBool(hasWideColorDisplay);
4666 return NO_ERROR;
4667 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004668 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004669 n = data.readInt32();
4670 if (n) {
4671 ALOGV("LayerTracing enabled");
4672 mTracing.enable();
4673 doTracing("tracing.enable");
4674 reply->writeInt32(NO_ERROR);
4675 } else {
4676 ALOGV("LayerTracing disabled");
4677 status_t err = mTracing.disable();
4678 reply->writeInt32(err);
4679 }
4680 return NO_ERROR;
4681 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004682 case 1026: { // Get layer tracing status
4683 reply->writeBool(mTracing.isEnabled());
4684 return NO_ERROR;
4685 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004686 // Is a DisplayColorSetting supported?
4687 case 1027: {
4688 int32_t value = data.readInt32();
4689 switch (value) {
4690 case 0:
4691 reply->writeBool(hasWideColorDisplay);
4692 return NO_ERROR;
4693 case 1:
4694 reply->writeBool(true);
4695 return NO_ERROR;
4696 case 2:
4697 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4698 return NO_ERROR;
4699 default:
4700 return BAD_VALUE;
4701 }
4702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004703 }
4704 }
4705 return err;
4706}
4707
Steven Thomas6d8110b2017-08-31 18:24:21 -07004708void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004709 android_atomic_or(1, &mRepaintEverything);
4710 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004711}
4712
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004713// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4714class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004715public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004716 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4717 ~WindowDisconnector() {
4718 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004719 }
4720
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004721private:
4722 ANativeWindow* mWindow;
4723 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004724};
4725
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004726status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4727 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4728 int32_t minLayerZ, int32_t maxLayerZ,
4729 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004730 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004731 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004732
chaviwa76b2712017-09-20 12:02:26 -07004733 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4734
4735 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004736 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4737
chaviwa76b2712017-09-20 12:02:26 -07004738 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4739
4740 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4741 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004742 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004743}
4744
4745status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004746 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004747 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004748 ATRACE_CALL();
4749
4750 class LayerRenderArea : public RenderArea {
4751 public:
Robert Carr578038f2018-03-09 12:25:24 -08004752 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4753 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004754 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004755 mLayer(layer),
4756 mCrop(crop),
4757 mFlinger(flinger),
4758 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004759 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004760 Rect getBounds() const override {
4761 const Layer::State& layerState(mLayer->getDrawingState());
4762 return Rect(layerState.active.w, layerState.active.h);
4763 }
4764 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4765 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4766 bool isSecure() const override { return false; }
4767 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004768 Rect getSourceCrop() const override {
4769 if (mCrop.isEmpty()) {
4770 return getBounds();
4771 } else {
4772 return mCrop;
4773 }
4774 }
4775 bool getWideColorSupport() const override { return false; }
4776 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004777 float getDisplayMaxLuminance() const override {
4778 return DisplayDevice::sDefaultMaxLumiance;
4779 }
Robert Carr578038f2018-03-09 12:25:24 -08004780
4781 class ReparentForDrawing {
4782 public:
4783 const sp<Layer>& oldParent;
4784 const sp<Layer>& newParent;
4785
4786 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4787 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004788 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004789 }
Robert Carr15eae092018-03-23 13:43:53 -07004790 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004791 };
4792
4793 void render(std::function<void()> drawLayers) override {
4794 if (!mChildrenOnly) {
4795 mTransform = mLayer->getTransform().inverse();
4796 drawLayers();
4797 } else {
4798 Rect bounds = getBounds();
4799 screenshotParentLayer =
4800 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4801 bounds.getWidth(), bounds.getHeight(), 0);
4802
4803 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4804 drawLayers();
4805 }
4806 }
chaviwa76b2712017-09-20 12:02:26 -07004807
chaviwa76b2712017-09-20 12:02:26 -07004808 private:
chaviw7206d492017-11-10 16:16:12 -08004809 const sp<Layer> mLayer;
4810 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004811
4812 // In the "childrenOnly" case we reparent the children to a screenshot
4813 // layer which has no properties set and which does not draw.
4814 sp<ContainerLayer> screenshotParentLayer;
4815 Transform mTransform;
4816
4817 SurfaceFlinger* mFlinger;
4818 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004819 };
4820
4821 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4822 auto parent = layerHandle->owner.promote();
4823
chaviw7206d492017-11-10 16:16:12 -08004824 if (parent == nullptr || parent->isPendingRemoval()) {
4825 ALOGE("captureLayers called with a removed parent");
4826 return NAME_NOT_FOUND;
4827 }
4828
Robert Carr578038f2018-03-09 12:25:24 -08004829 const int uid = IPCThreadState::self()->getCallingUid();
4830 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4831 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4832 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4833 return PERMISSION_DENIED;
4834 }
4835
chaviw7206d492017-11-10 16:16:12 -08004836 Rect crop(sourceCrop);
4837 if (sourceCrop.width() <= 0) {
4838 crop.left = 0;
4839 crop.right = parent->getCurrentState().active.w;
4840 }
4841
4842 if (sourceCrop.height() <= 0) {
4843 crop.top = 0;
4844 crop.bottom = parent->getCurrentState().active.h;
4845 }
4846
4847 int32_t reqWidth = crop.width() * frameScale;
4848 int32_t reqHeight = crop.height() * frameScale;
4849
Robert Carr578038f2018-03-09 12:25:24 -08004850 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004851
Robert Carr578038f2018-03-09 12:25:24 -08004852 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004853 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4854 if (!layer->isVisible()) {
4855 return;
Robert Carr578038f2018-03-09 12:25:24 -08004856 } else if (childrenOnly && layer == parent.get()) {
4857 return;
chaviwa76b2712017-09-20 12:02:26 -07004858 }
4859 visitor(layer);
4860 });
4861 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004862 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004863}
4864
4865status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4866 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004867 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004868 bool useIdentityTransform) {
4869 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004870
chaviwa76b2712017-09-20 12:02:26 -07004871 renderArea.updateDimensions();
4872
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004873 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4874 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4875 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4876 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004877
4878 // This mutex protects syncFd and captureResult for communication of the return values from the
4879 // main thread back to this Binder thread
4880 std::mutex captureMutex;
4881 std::condition_variable captureCondition;
4882 std::unique_lock<std::mutex> captureLock(captureMutex);
4883 int syncFd = -1;
4884 std::optional<status_t> captureResult;
4885
Robert Carr03480e22018-01-04 16:02:06 -08004886 const int uid = IPCThreadState::self()->getCallingUid();
4887 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4888
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004889 sp<LambdaMessage> message = new LambdaMessage([&]() {
4890 // If there is a refresh pending, bug out early and tell the binder thread to try again
4891 // after the refresh.
4892 if (mRefreshPending) {
4893 ATRACE_NAME("Skipping screenshot for now");
4894 std::unique_lock<std::mutex> captureLock(captureMutex);
4895 captureResult = std::make_optional<status_t>(EAGAIN);
4896 captureCondition.notify_one();
4897 return;
4898 }
4899
4900 status_t result = NO_ERROR;
4901 int fd = -1;
4902 {
4903 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004904 renderArea.render([&]() {
4905 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4906 useIdentityTransform, forSystem, &fd);
4907 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004908 }
4909
4910 {
4911 std::unique_lock<std::mutex> captureLock(captureMutex);
4912 syncFd = fd;
4913 captureResult = std::make_optional<status_t>(result);
4914 captureCondition.notify_one();
4915 }
4916 });
4917
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004918 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004919 if (result == NO_ERROR) {
4920 captureCondition.wait(captureLock, [&]() { return captureResult; });
4921 while (*captureResult == EAGAIN) {
4922 captureResult.reset();
4923 result = postMessageAsync(message);
4924 if (result != NO_ERROR) {
4925 return result;
4926 }
4927 captureCondition.wait(captureLock, [&]() { return captureResult; });
4928 }
4929 result = *captureResult;
4930 }
4931
4932 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004933 sync_wait(syncFd, -1);
4934 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004935 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004936
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004937 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004938}
4939
chaviwa76b2712017-09-20 12:02:26 -07004940void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4941 TraverseLayersFunction traverseLayers, bool yswap,
4942 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004943 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004944
Lloyd Pique144e1162017-12-20 16:44:52 -08004945 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004946
4947 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004948 const auto raWidth = renderArea.getWidth();
4949 const auto raHeight = renderArea.getHeight();
4950
4951 const auto reqWidth = renderArea.getReqWidth();
4952 const auto reqHeight = renderArea.getReqHeight();
4953 Rect sourceCrop = renderArea.getSourceCrop();
4954
4955 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4956 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004957
Dan Stozac1879002014-05-22 15:59:05 -07004958 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004959 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004960 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004961 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004962 }
4963
4964 // ensure that sourceCrop is inside screen
4965 if (sourceCrop.left < 0) {
4966 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4967 }
chaviwa76b2712017-09-20 12:02:26 -07004968 if (sourceCrop.right > raWidth) {
4969 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004970 }
4971 if (sourceCrop.top < 0) {
4972 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4973 }
chaviwa76b2712017-09-20 12:02:26 -07004974 if (sourceCrop.bottom > raHeight) {
4975 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004976 }
4977
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004978 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004979 if (renderArea.getWideColorSupport()) {
4980 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004981 }
Peiyong Linfb069302018-04-25 14:34:31 -07004982 engine.setOutputDataSpace(outputDataspace);
4983 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004984
Mathias Agopian180f10d2013-04-10 22:55:41 -07004985 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004986 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004987
4988 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004989 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4990 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004991 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004992
chaviw50da5042018-04-09 13:49:37 -07004993 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004994 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004995 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004996
chaviwa76b2712017-09-20 12:02:26 -07004997 traverseLayers([&](Layer* layer) {
4998 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004999 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005000 if (filtering) layer->setFiltering(false);
5001 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005002}
5003
chaviwa76b2712017-09-20 12:02:26 -07005004status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5005 TraverseLayersFunction traverseLayers,
5006 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005007 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005008 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005009 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005010 ATRACE_CALL();
5011
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005012 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005013
5014 traverseLayers([&](Layer* layer) {
5015 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5016 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005017
Robert Carr03480e22018-01-04 16:02:06 -08005018 // We allow the system server to take screenshots of secure layers for
5019 // use in situations like the Screen-rotation animation and place
5020 // the impetus on WindowManager to not persist them.
5021 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005022 ALOGW("FB is protected: PERMISSION_DENIED");
5023 return PERMISSION_DENIED;
5024 }
5025
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005026 // this binds the given EGLImage as a framebuffer for the
5027 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005028 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005029 if (bufferBond.getStatus() != NO_ERROR) {
5030 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005031 return INVALID_OPERATION;
5032 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005033
Dan Stozaabcda352017-06-01 14:37:39 -07005034 // this will in fact render into our dequeued buffer
5035 // via an FBO, which means we didn't have to create
5036 // an EGLSurface and therefore we're not
5037 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005038 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005039
Dan Stozaabcda352017-06-01 14:37:39 -07005040 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005041 getRenderEngine().finish();
5042 *outSyncFd = -1;
5043
chaviwa76b2712017-09-20 12:02:26 -07005044 const auto reqWidth = renderArea.getReqWidth();
5045 const auto reqHeight = renderArea.getReqHeight();
5046
Dan Stozaabcda352017-06-01 14:37:39 -07005047 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5048 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005049 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005050 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005051 } else {
5052 base::unique_fd syncFd = getRenderEngine().flush();
5053 if (syncFd < 0) {
5054 getRenderEngine().finish();
5055 }
5056 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005057 }
5058
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005059 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005060}
5061
Mathias Agopiand5556842013-09-19 17:08:37 -07005062void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005063 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005064 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005065 for (size_t y = 0; y < h; y++) {
5066 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5067 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005068 if (p[x] != 0xFF000000) return;
5069 }
5070 }
chaviwa76b2712017-09-20 12:02:26 -07005071 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005072
Robert Carr2047fae2016-11-28 14:09:09 -08005073 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005074 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005075 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005076 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5077 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5078 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5079 static_cast<float>(state.color.a));
5080 i++;
5081 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005082 }
5083}
5084
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005085// ---------------------------------------------------------------------------
5086
Dan Stoza412903f2017-04-27 13:42:17 -07005087void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5088 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005089}
5090
Dan Stoza412903f2017-04-27 13:42:17 -07005091void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5092 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005093}
5094
chaviwa76b2712017-09-20 12:02:26 -07005095void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5096 int32_t maxLayerZ,
5097 const LayerVector::Visitor& visitor) {
5098 // We loop through the first level of layers without traversing,
5099 // as we need to interpret min/max layer Z in the top level Z space.
5100 for (const auto& layer : mDrawingState.layersSortedByZ) {
5101 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5102 continue;
5103 }
5104 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005105 // relative layers are traversed in Layer::traverseInZOrder
5106 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005107 continue;
5108 }
5109 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005110 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5111 return;
5112 }
chaviwa76b2712017-09-20 12:02:26 -07005113 if (!layer->isVisible()) {
5114 return;
5115 }
5116 visitor(layer);
5117 });
5118 }
5119}
5120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005122
Chia-I Wu30505fb2018-03-26 16:20:31 -07005123
Mathias Agopian3f844832013-08-07 21:24:32 -07005124#if defined(__gl_h_)
5125#error "don't include gl/gl.h in this file"
5126#endif
5127
5128#if defined(__gl2_h_)
5129#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005130#endif