blob: 225aad1fb91283ba106c0143dd3970ac51948d7c [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),
Dan Stozab90cf072015-03-05 11:05:59 -0800248 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800249 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700250 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800251 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800252 mCreateBufferQueue(&BufferQueue::createBufferQueue),
253 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800254
255SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800257
258 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
260
261 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
263
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700267 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
269
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700270 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
272
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
275
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 // Vr flinger is only enabled on Daydream ready devices.
277 useVrFlinger = getBool< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::useVrFlinger>(false);
279
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
282
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283 hasWideColorDisplay =
284 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
285
David Sodman99974d22017-11-28 12:04:33 -0800286 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 // debugging stuff...
289 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700290
Mathias Agopianb4b17302013-03-20 18:36:41 -0700291 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700292 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294 property_get("debug.sf.showupdates", value, "0");
295 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700297 property_get("debug.sf.ddms", value, "0");
298 mDebugDDMS = atoi(value);
299 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700300 if (!startDdmConnection()) {
301 // start failed, and DDMS debugging not enabled
302 mDebugDDMS = 0;
303 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700304 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700305 ALOGI_IF(mDebugRegion, "showupdates enabled");
306 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700307
308 property_get("debug.sf.disable_backpressure", value, "0");
309 mPropagateBackpressure = !atoi(value);
310 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700311
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800312 property_get("debug.sf.enable_hwc_vds", value, "0");
313 mUseHwcVirtualDisplays = atoi(value);
314 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800315
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800316 property_get("ro.sf.disable_triple_buffer", value, "1");
317 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800318 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700319
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 // TODO (b/74616334): Reduce the default value once we isolate the leak
321 const size_t defaultListSize = 4 * MAX_LAYERS;
322 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
323 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
324
Dan Stoza84d619e2018-03-28 17:07:36 -0700325 property_get("debug.sf.early_phase_offset_ns", value, "0");
326 const int earlyWakeupOffsetOffsetNs = atoi(value);
327 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
328 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
329 sfVsyncPhaseOffsetNs);
330
Romain Guy11d63f42017-07-20 12:47:14 -0700331 // We should be reading 'persist.sys.sf.color_saturation' here
332 // but since /data may be encrypted, we need to wait until after vold
333 // comes online to attempt to read the property. The property is
334 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800335
336 if (useTrebleTestingOverride()) {
337 // Without the override SurfaceFlinger cannot connect to HIDL
338 // services that are not listed in the manifests. Considered
339 // deriving the setting from the set service name, but it
340 // would be brittle if the name that's not 'default' is used
341 // for production purposes later on.
342 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344}
345
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800346void SurfaceFlinger::onFirstRef()
347{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800348 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351SurfaceFlinger::~SurfaceFlinger()
352{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Dan Stozac7014012014-02-14 15:03:43 -0800355void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356{
357 // the window manager died on us. prepare its eulogy.
358
Andy McFadden13a082e2012-08-24 10:16:42 -0700359 // restore initial conditions (default device unblank, etc)
360 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800361
362 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700363 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800364}
365
Robert Carr1db73f62016-12-21 12:58:51 -0800366static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700367 status_t err = client->initCheck();
368 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 }
Robert Carr1db73f62016-12-21 12:58:51 -0800371 return nullptr;
372}
373
374sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
375 return initClient(new Client(this));
376}
377
378sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
379 const sp<IGraphicBufferProducer>& gbp) {
380 if (authenticateSurfaceTexture(gbp) == false) {
381 return nullptr;
382 }
383 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
384 if (layer == nullptr) {
385 return nullptr;
386 }
387
388 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700391sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
392 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700393{
394 class DisplayToken : public BBinder {
395 sp<SurfaceFlinger> flinger;
396 virtual ~DisplayToken() {
397 // no more references, this display must be terminated
398 Mutex::Autolock _l(flinger->mStateLock);
399 flinger->mCurrentState.displays.removeItem(this);
400 flinger->setTransactionFlags(eDisplayTransactionNeeded);
401 }
402 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700403 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 : flinger(flinger) {
405 }
406 };
407
408 sp<BBinder> token = new DisplayToken(this);
409
410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700411 DisplayDeviceState info;
412 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700413 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700414 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800416 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417 return token;
418}
419
Jesse Hall6c913be2013-08-08 12:15:49 -0700420void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
421 Mutex::Autolock _l(mStateLock);
422
423 ssize_t idx = mCurrentState.displays.indexOfKey(display);
424 if (idx < 0) {
425 ALOGW("destroyDisplay: invalid display token");
426 return;
427 }
428
429 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700430 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 ALOGE("destroyDisplay called for non-virtual display");
432 return;
433 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700434 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700435 mCurrentState.displays.removeItemsAt(idx);
436 setTransactionFlags(eDisplayTransactionNeeded);
437}
438
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700440 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800442 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 }
Jesse Hall692c7232012-11-08 15:41:56 -0800444 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445}
446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447void SurfaceFlinger::bootFinished()
448{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700449 if (mStartPropertySetThread->join() != NO_ERROR) {
450 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 const nsecs_t now = systemTime();
453 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000454 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700455
456 // wait patiently for the window manager death
457 const String16 name("window");
458 sp<IBinder> window(defaultServiceManager()->getService(name));
459 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700460 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700461 }
462
Steven Thomas050b2c82017-03-06 11:45:16 -0800463 if (mVrFlinger) {
464 mVrFlinger->OnBootFinished();
465 }
466
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700467 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700468 // formerly we would just kill the process, but we now ask it to exit so it
469 // can choose where to stop the animation.
470 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700471
472 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
473 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
474 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700475
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700477 readPersistentProperties();
478 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700479 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480}
481
Mathias Agopian3f844832013-08-07 21:24:32 -0700482void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700485 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800487 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
488 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700489 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700490 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491 return true;
492 }
493 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700494 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700495}
496
Lloyd Piquee83f9312018-02-01 12:53:17 -0800497class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 const char* name) :
501 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
505 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 mDispSync(dispSync),
507 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508 mVsyncMutex(),
509 mPhaseOffset(phaseOffset),
510 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700511
Lloyd Piquee83f9312018-02-01 12:53:17 -0800512 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513
Lloyd Piquee83f9312018-02-01 12:53:17 -0800514 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000517 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 static_cast<DispSync::Callback*>(this));
519 if (err != NO_ERROR) {
520 ALOGE("error registering vsync callback: %s (%d)",
521 strerror(-err), err);
522 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700523 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 } else {
525 status_t err = mDispSync->removeEventListener(
526 static_cast<DispSync::Callback*>(this));
527 if (err != NO_ERROR) {
528 ALOGE("error unregistering vsync callback: %s (%d)",
529 strerror(-err), err);
530 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 }
535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 mCallback = callback;
539 }
540
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542 Mutex::Autolock lock(mVsyncMutex);
543
544 // Normalize phaseOffset to [0, period)
545 auto period = mDispSync->getPeriod();
546 phaseOffset %= period;
547 if (phaseOffset < 0) {
548 // If we're here, then phaseOffset is in (-period, 0). After this
549 // operation, it will be in (0, period)
550 phaseOffset += period;
551 }
552 mPhaseOffset = phaseOffset;
553
554 // If we're not enabled, we don't need to mess with the listeners
555 if (!mEnabled) {
556 return;
557 }
558
Dan Stoza84d619e2018-03-28 17:07:36 -0700559 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
560 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700562 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700563 strerror(-err), err);
564 }
565 }
566
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567private:
568 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700572 callback = mCallback;
573
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 if (mTraceVsync) {
575 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700577 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 }
579
Peiyong Lin566a3b42018-01-09 18:22:43 -0800580 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581 callback->onVSyncEvent(when);
582 }
583 }
584
Tim Murray4a4e4a22016-04-19 16:29:23 +0000585 const char* const mName;
586
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587 int mValue;
588
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700590 const String8 mVsyncOnLabel;
591 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700592
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800596 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597
598 Mutex mVsyncMutex; // Protects the following
599 nsecs_t mPhaseOffset;
600 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601};
602
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 InjectVSyncSource() = default;
606 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607
Lloyd Piquee83f9312018-02-01 12:53:17 -0800608 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700609 std::lock_guard<std::mutex> lock(mCallbackMutex);
610 mCallback = callback;
611 }
612
Lloyd Piquee83f9312018-02-01 12:53:17 -0800613 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700615 if (mCallback) {
616 mCallback->onVSyncEvent(when);
617 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618 }
619
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 void setVSyncEnabled(bool) override {}
621 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622
623private:
624 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800625 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700626};
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
633
Thierry Strudel2924d012017-08-14 15:19:37 -0700634 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800639 mEventThreadSource =
640 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
641 true, "app");
642 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
643 "appEventThread");
644 mSfEventThreadSource =
645 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
646 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800648 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
649 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800650 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700651 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800654 getBE().mRenderEngine =
655 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
656 hasWideColorDisplay
657 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
658 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800659 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700660
661 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
662 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800663 getBE().mHwc.reset(
664 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700665 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800666 // Process any initial hotplug and resulting display changes.
667 processDisplayHotplugEventsLocked();
668 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
669 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Lloyd Piquefcd86612017-12-14 17:15:36 -0800671 // make the default display GLContext current so that we can create textures
672 // when creating Layers (which may happens before we render something)
673 getDefaultDisplayDeviceLocked()->makeCurrent();
674
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (useVrFlinger) {
676 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 // This callback is called from the vr flinger dispatch thread. We
678 // need to call signalTransaction(), which requires holding
679 // mStateLock when we're not on the main thread. Acquiring
680 // mStateLock from the vr flinger dispatch thread might trigger a
681 // deadlock in surface flinger (see b/66916578), so post a message
682 // to be handled on the main thread instead.
683 sp<LambdaMessage> message = new LambdaMessage([=]() {
684 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
685 mVrFlingerRequestsDisplay = requestDisplay;
686 signalTransaction();
687 });
688 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
David Sodman105b7dc2017-11-04 20:28:14 -0700690 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
691 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800692 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (!mVrFlinger) {
694 ALOGE("Failed to start vrflinger");
695 }
696 }
697
Lloyd Pique379adc12018-01-22 17:31:47 -0800698 mEventControlThread = std::make_unique<impl::EventControlThread>(
699 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700700
Mathias Agopian92a979a2012-08-02 18:32:23 -0700701 // initialize our drawing state
702 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700703
Andy McFadden13a082e2012-08-24 10:16:42 -0700704 // set initial conditions (e.g. unblank default device)
705 initializeDisplays();
706
David Sodmanbc815282017-11-05 18:57:52 -0800707 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700708
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 // Inform native graphics APIs whether the present timestamp is supported:
710 if (getHwComposer().hasCapability(
711 HWC2::Capability::PresentFenceIsNotReliable)) {
712 mStartPropertySetThread = new StartPropertySetThread(false);
713 } else {
714 mStartPropertySetThread = new StartPropertySetThread(true);
715 }
716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
722 Dataspace::SRGB_LINEAR);
723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700725}
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700728 Mutex::Autolock _l(mStateLock);
729
Romain Guy11d63f42017-07-20 12:47:14 -0700730 char value[PROPERTY_VALUE_MAX];
731
732 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700734 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100736
737 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
739 ALOGV("Display Color Setting is set to %s.",
740 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700741}
742
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Start boot animation service by setting a property mailbox
745 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 if (mStartPropertySetThread->join() != NO_ERROR) {
749 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800758 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800762
Jamie Gennis582270d2011-08-17 18:19:00 -0700763bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800765 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800766 return authenticateSurfaceTextureLocked(bufferProducer);
767}
768
769bool SurfaceFlinger::authenticateSurfaceTextureLocked(
770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800771 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800772 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800773}
774
Brian Anderson6b376712017-04-04 10:51:39 -0700775status_t SurfaceFlinger::getSupportedFrameTimestamps(
776 std::vector<FrameEvent>* outSupported) const {
777 *outSupported = {
778 FrameEvent::REQUESTED_PRESENT,
779 FrameEvent::ACQUIRE,
780 FrameEvent::LATCH,
781 FrameEvent::FIRST_REFRESH_START,
782 FrameEvent::LAST_REFRESH_START,
783 FrameEvent::GPU_COMPOSITION_DONE,
784 FrameEvent::DEQUEUE_READY,
785 FrameEvent::RELEASE,
786 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 ConditionalLock _l(mStateLock,
788 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700789 if (!getHwComposer().hasCapability(
790 HWC2::Capability::PresentFenceIsNotReliable)) {
791 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
792 }
793 return NO_ERROR;
794}
795
Dan Stoza7f7da322014-05-02 15:26:25 -0700796status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
797 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800798 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500802 if (!display.get())
803 return NAME_NOT_FOUND;
804
Jesse Hall692c7232012-11-08 15:41:56 -0800805 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700806 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800807 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700808 type = i;
809 break;
810 }
811 }
812
813 if (type < 0) {
814 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700815 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 // TODO: Not sure if display density should handled by SF any longer
818 class Density {
819 static int getDensityFromProperty(char const* propName) {
820 char property[PROPERTY_VALUE_MAX];
821 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800822 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 density = atoi(property);
824 }
825 return density;
826 }
827 public:
828 static int getEmuDensity() {
829 return getDensityFromProperty("qemu.sf.lcd_density"); }
830 static int getBuildDensity() {
831 return getDensityFromProperty("ro.sf.lcd_density"); }
832 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Steven Thomas6d8110b2017-08-31 18:24:21 -0700836 ConditionalLock _l(mStateLock,
837 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 DisplayInfo info = DisplayInfo();
840
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 float xdpi = hwConfig->getDpiX();
842 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
844 if (type == DisplayDevice::DISPLAY_PRIMARY) {
845 // The density of the device is provided by a build property
846 float density = Density::getBuildDensity() / 160.0f;
847 if (density == 0) {
848 // the build doesn't provide a density -- this is wrong!
849 // use xdpi instead
850 ALOGE("ro.sf.lcd_density must be defined as a build property");
851 density = xdpi / 160.0f;
852 }
853 if (Density::getEmuDensity()) {
854 // if "qemu.sf.lcd_density" is specified, it overrides everything
855 xdpi = ydpi = density = Density::getEmuDensity();
856 density /= 160.0f;
857 }
858 info.density = density;
859
860 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700861 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800862 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 } else {
864 // TODO: where should this value come from?
865 static const int TV_DENSITY = 213;
866 info.density = TV_DENSITY / 160.0f;
867 info.orientation = 0;
868 }
869
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870 info.w = hwConfig->getWidth();
871 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 info.xdpi = xdpi;
873 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900875 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800876
Andy McFadden91b2ca82014-06-13 14:04:23 -0700877 // This is how far in advance a buffer must be queued for
878 // presentation at a given time. If you want a buffer to appear
879 // on the screen at time N, you must submit the buffer before
880 // (N - presentationDeadline).
881 //
882 // Normally it's one full refresh period (to give SF a chance to
883 // latch the buffer), but this can be reduced by configuring a
884 // DispSync offset. Any additional delays introduced by the hardware
885 // composer or panel must be accounted for here.
886 //
887 // We add an additional 1ms to allow for processing time and
888 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800890 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700891
892 // All non-virtual displays are currently considered secure.
893 info.secure = true;
894
Michael Wright28f24d02016-07-12 13:30:53 -0700895 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700896 }
897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 return NO_ERROR;
899}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700900
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800901status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700902 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800903 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700904 return BAD_VALUE;
905 }
906
907 // FIXME for now we always return stats for the primary display
908 memset(stats, 0, sizeof(*stats));
909 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
910 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
911 return NO_ERROR;
912}
913
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800915 if (display == nullptr) {
916 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800917 return BAD_VALUE;
918 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700919
920 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800921 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700922 return device->getActiveConfig();
923 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700924
Dan Stoza24a42e92015-03-09 10:04:11 -0700925 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700926}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700927
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
929 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
930 this);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931 int currentMode = hw->getActiveConfig();
932
933 if (mode == currentMode) {
934 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
935 return;
936 }
937
Dominik Laskowski281644e2018-04-19 15:47:35 -0700938 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700939 ALOGW("Trying to set config for virtual display");
940 return;
941 }
942
943 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700944 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945}
946
947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
948 class MessageSetActiveConfig: public MessageBase {
949 SurfaceFlinger& mFlinger;
950 sp<IBinder> mDisplay;
951 int mMode;
952 public:
953 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
954 int mode) :
955 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
956 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700957 Vector<DisplayInfo> configs;
958 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700959 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700960 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700961 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700962 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700963 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800965 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700967 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700968 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700969 ALOGW("Attempt to set active config = %d for virtual display",
970 mMode);
971 } else {
972 mFlinger.setActiveConfigInternal(hw, mMode);
973 }
974 return true;
975 }
976 };
977 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
978 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700979 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700980}
Michael Wright28f24d02016-07-12 13:30:53 -0700981status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700982 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700983 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
984 return BAD_VALUE;
985 }
986
987 if (!display.get()) {
988 return NAME_NOT_FOUND;
989 }
990
991 int32_t type = NAME_NOT_FOUND;
992 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
993 if (display == mBuiltinDisplays[i]) {
994 type = i;
995 break;
996 }
997 }
998
999 if (type < 0) {
1000 return type;
1001 }
1002
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001004 {
1005 ConditionalLock _l(mStateLock,
1006 std::this_thread::get_id() != mMainThreadId);
1007 modes = getHwComposer().getColorModes(type);
1008 }
Michael Wright28f24d02016-07-12 13:30:53 -07001009 outColorModes->clear();
1010 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1011
1012 return NO_ERROR;
1013}
1014
Peiyong Lina52f0292018-03-14 17:26:31 -07001015ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001016 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001017 if (device != nullptr) {
1018 return device->getActiveColorMode();
1019 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001021}
1022
1023void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001024 ColorMode mode, Dataspace dataSpace) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001027 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001028
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001029 // Natural Mode means it's color managed and the color must be right,
1030 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1031 // Native Mode means the display is not color managed, and whichever
1032 // render intent is picked doesn't matter, thus return
1033 // RenderIntent::COLORIMETRIC as default here.
1034 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1035
1036 // In Auto Color Mode, we want to strech to panel color space, right now
1037 // only the built-in display supports it.
Dominik Laskowski281644e2018-04-19 15:47:35 -07001038 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED && mBuiltinDisplaySupportsEnhance &&
1039 hw->isPrimary()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001040 renderIntent = RenderIntent::ENHANCE;
1041 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042
1043 if (mode == currentMode && dataSpace == currentDataSpace &&
1044 renderIntent == currentRenderIntent) {
1045 return;
1046 }
1047
Dominik Laskowski281644e2018-04-19 15:47:35 -07001048 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001049 ALOGW("Trying to set config for virtual display");
1050 return;
1051 }
1052
1053 hw->setActiveColorMode(mode);
1054 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001055 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001056 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001057
1058 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1059 decodeColorMode(mode).c_str(), mode,
1060 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1061 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001062}
1063
1064
1065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001067 class MessageSetActiveColorMode: public MessageBase {
1068 SurfaceFlinger& mFlinger;
1069 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 public:
1072 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1075 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 mFlinger.getDisplayColorModes(mDisplay, &modes);
1078 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001080 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1081 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return true;
1083 }
1084 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1085 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001088 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001089 ALOGW("Attempt to set active color mode %s %d for virtual display",
1090 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001092 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
1094 return true;
1095 }
1096 };
1097 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1098 postMessageSync(msg);
1099 return NO_ERROR;
1100}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001101
Svetoslavd85084b2014-03-20 10:28:31 -07001102status_t SurfaceFlinger::clearAnimationFrameStats() {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.clearStats();
1105 return NO_ERROR;
1106}
1107
1108status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1109 Mutex::Autolock _l(mStateLock);
1110 mAnimFrameTracker.getStats(outStats);
1111 return NO_ERROR;
1112}
1113
Dan Stozac4f471e2016-03-24 09:31:08 -07001114status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1115 HdrCapabilities* outCapabilities) const {
1116 Mutex::Autolock _l(mStateLock);
1117
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001118 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001119 if (displayDevice == nullptr) {
1120 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1121 return BAD_VALUE;
1122 }
1123
Peiyong Linfb069302018-04-25 14:34:31 -07001124 // At this point the DisplayDeivce should already be set up,
1125 // meaning the luminance information is already queried from
1126 // hardware composer and stored properly.
1127 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1128 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1129 capabilities.getDesiredMaxLuminance(),
1130 capabilities.getDesiredMaxAverageLuminance(),
1131 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001132
1133 return NO_ERROR;
1134}
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1138 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 if (mInjectVSyncs == enable) {
1141 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143
1144 if (enable) {
1145 ALOGV("VSync Injections enabled");
1146 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001147 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001148 mInjectorEventThread =
1149 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1150 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001152 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 } else {
1154 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001155 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 }
1157
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 });
1160 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 return NO_ERROR;
1162}
1163
1164status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 Mutex::Autolock _l(mStateLock);
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 if (!mInjectVSyncs) {
1168 ALOGE("VSync Injections not enabled");
1169 return BAD_VALUE;
1170 }
1171 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1172 ALOGV("Injecting VSync inside SurfaceFlinger");
1173 mVSyncInjector->onInjectSyncEvent(when);
1174 }
1175 return NO_ERROR;
1176}
1177
Lloyd Pique755e3192018-01-31 16:46:15 -08001178status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1179 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001180 IPCThreadState* ipc = IPCThreadState::self();
1181 const int pid = ipc->getCallingPid();
1182 const int uid = ipc->getCallingUid();
1183 if ((uid != AID_SHELL) &&
1184 !PermissionCache::checkPermission(sDump, pid, uid)) {
1185 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1186 return PERMISSION_DENIED;
1187 }
1188
1189 // Try to acquire a lock for 1s, fail gracefully
1190 const status_t err = mStateLock.timedLock(s2ns(1));
1191 const bool locked = (err == NO_ERROR);
1192 if (!locked) {
1193 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1194 return TIMED_OUT;
1195 }
1196
1197 outLayers->clear();
1198 mCurrentState.traverseInZOrder([&](Layer* layer) {
1199 outLayers->push_back(layer->getLayerDebugInfo());
1200 });
1201
1202 mStateLock.unlock();
1203 return NO_ERROR;
1204}
1205
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001206// ----------------------------------------------------------------------------
1207
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001208sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1209 ISurfaceComposer::VsyncSource vsyncSource) {
1210 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1211 return mSFEventThread->createEventConnection();
1212 } else {
1213 return mEventThread->createEventConnection();
1214 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001215}
1216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001218
1219void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001224 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001232 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001237 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001238 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001242 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001243 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244 if (res == NO_ERROR) {
1245 msg->wait();
1246 }
1247 return res;
1248}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001250void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001251 do {
1252 waitForEvent();
1253 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254}
1255
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256void SurfaceFlinger::enableHardwareVsync() {
1257 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1261 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001263 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264}
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 Mutex::Autolock _l(mHWVsyncLock);
1268
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 if (makeAvailable) {
1270 mHWVsyncAvailable = true;
1271 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001272 // Hardware vsync is not currently available, so abort the resync
1273 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 return;
1275 }
1276
David Sodman105b7dc2017-11-04 20:28:14 -07001277 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001278 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279
1280 mPrimaryDispSync.reset();
1281 mPrimaryDispSync.setPeriod(period);
1282
1283 if (!mPrimaryHWVsyncEnabled) {
1284 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001285 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1286 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 mPrimaryHWVsyncEnabled = true;
1288 }
1289}
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 Mutex::Autolock _l(mHWVsyncLock);
1293 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1295 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryDispSync.endResync();
1297 mPrimaryHWVsyncEnabled = false;
1298 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (makeUnavailable) {
1300 mHWVsyncAvailable = false;
1301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304void SurfaceFlinger::resyncWithRateLimit() {
1305 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001306
1307 // No explicit locking is needed here since EventThread holds a lock while calling this method
1308 static nsecs_t sLastResyncAttempted = 0;
1309 const nsecs_t now = systemTime();
1310 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001311 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312 }
Dan Stoza57164302017-05-08 14:03:54 -07001313 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314}
1315
Steven Thomasb02664d2017-07-26 18:48:28 -07001316void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1317 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 return;
1322 }
1323
1324 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 return;
1327 }
1328
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 { // Scope for the lock
1332 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001336 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001337
1338 if (needsHwVsync) {
1339 enableHardwareVsync();
1340 } else {
1341 disableHardwareVsync(false);
1342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343}
1344
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001345void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001346 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1347 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001348}
1349
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1351 HWC2::Connection connection) {
1352 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1353 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354
Lloyd Piqueba04e622017-12-14 17:11:26 -08001355 // Ignore events that do not have the right sequenceId.
1356 if (sequenceId != getBE().mComposerSequenceId) {
1357 return;
1358 }
1359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Only lock if we're not on the main thread. This function is normally
1361 // called on a hwbinder thread, but for the primary display it's called on
1362 // the main thread with the state lock already held, so don't attempt to
1363 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365
Lloyd Pique715a2c12017-12-14 17:18:08 -08001366 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001367
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001368 if (std::this_thread::get_id() == mMainThreadId) {
1369 // Process all pending hot plug events immediately if we are on the main thread.
1370 processDisplayHotplugEventsLocked();
1371 }
1372
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001374}
1375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::onRefreshReceived(int sequenceId,
1377 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001379 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001382 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001383}
1384
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001386 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 getHwComposer().setVsyncEnabled(disp,
1389 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001390}
1391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001393void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 // Clear the drawing state so that the logic inside of
1396 // handleTransactionLocked will fire. It will determine the delta between
1397 // mCurrentState and mDrawingState and re-apply all changes when we make the
1398 // transition.
1399 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001400 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 mDisplays.clear();
1402}
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404void SurfaceFlinger::updateVrFlinger() {
1405 if (!mVrFlinger)
1406 return;
1407 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 return;
1410 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 ALOGE("Vr flinger is only supported for remote hardware composer"
1414 " service connections. Ignoring request to transition to vr"
1415 " flinger.");
1416 mVrFlingerRequestsDisplay = false;
1417 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 int currentDisplayPowerMode = getDisplayDeviceLocked(
1423 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001430 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001431 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1432 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001433 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434
David Sodman105b7dc2017-11-04 20:28:14 -07001435 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1436 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001437
1438 if (vrFlingerRequestsDisplay) {
1439 mVrFlinger->GrantDisplayOwnership();
1440 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
1444 mVisibleRegionsDirty = true;
1445 invalidateHwcGeometry();
1446
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1449 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1450 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001453 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 const nsecs_t period = activeConfig->getVsyncPeriod();
1455 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Use phase of 0 since phase is not known.
1458 // Use latency of 0, which will snap to the ideal latency.
1459 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001460
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461 android_atomic_or(1, &mRepaintEverything);
1462 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463}
1464
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001466 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001469 bool frameMissed = !mHadClientComposition &&
1470 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001471 (mPreviousPresentFence->getSignalTime() ==
1472 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001473 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001474 if (mPropagateBackpressure && frameMissed) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001475 mTimeStats.incrementMissedFrames(true);
Dan Stoza50182882016-07-08 12:02:20 -07001476 signalLayerUpdate();
1477 break;
1478 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001479 if (frameMissed) {
1480 mTimeStats.incrementMissedFrames(false);
1481 }
Dan Stoza50182882016-07-08 12:02:20 -07001482
Steven Thomas050b2c82017-03-06 11:45:16 -08001483 // Now that we're going to make it to the handleMessageTransaction()
1484 // call below it's safe to call updateVrFlinger(), which will
1485 // potentially trigger a display handoff.
1486 updateVrFlinger();
1487
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 bool refreshNeeded = handleMessageTransaction();
1489 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001490 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001492 // Signal a refresh if a transaction modified the window state,
1493 // a new buffer was latched, or if HWC has requested a full
1494 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 signalRefresh();
1496 }
1497 break;
1498 }
1499 case MessageQueue::REFRESH: {
1500 handleMessageRefresh();
1501 break;
1502 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001503 }
1504}
1505
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001507 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001509 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001513}
1514
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001517 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518}
1519
1520void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001522
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001523 mRefreshPending = false;
1524
Chia-I Wu30505fb2018-03-26 16:20:31 -07001525 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001526
Chia-I Wu30505fb2018-03-26 16:20:31 -07001527 preComposition(refreshStartTime);
1528 rebuildLayerStacks();
1529 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001530 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001531 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001532 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001533 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001534 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001535
David Sodman105b7dc2017-11-04 20:28:14 -07001536 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001537
1538 mHadClientComposition = false;
1539 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1540 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1541 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001542 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001543 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001544 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001545
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549void SurfaceFlinger::doDebugFlashRegions()
1550{
1551 // is debugging enabled
1552 if (CC_LIKELY(!mDebugRegion))
1553 return;
1554
1555 const bool repaintEverything = mRepaintEverything;
1556 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1557 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001558 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 // transform the dirty region into this screen's coordinate space
1560 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1561 if (!dirtyRegion.isEmpty()) {
1562 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001563 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564
1565 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001567 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001568 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1569
Mathias Agopianda27af92012-09-13 18:17:13 -07001570 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 }
1572 }
1573 }
1574
1575 postFramebuffer();
1576
1577 if (mDebugRegion > 1) {
1578 usleep(mDebugRegion * 1000);
1579 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001580
Dan Stoza9e56aa02015-11-02 13:00:03 -08001581 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001582 auto& displayDevice = mDisplays[displayId];
1583 if (!displayDevice->isDisplayOn()) {
1584 continue;
1585 }
1586
David Sodman105b7dc2017-11-04 20:28:14 -07001587 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1588 ALOGE_IF(result != NO_ERROR,
1589 "prepareFrame for display %zd failed:"
1590 " %d (%s)",
1591 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001592 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593}
1594
Adrian Roos1e1a1282017-11-01 19:05:31 +01001595void SurfaceFlinger::doTracing(const char* where) {
1596 ATRACE_CALL();
1597 ATRACE_NAME(where);
1598 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001599 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001600 }
1601}
1602
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001603void SurfaceFlinger::logLayerStats() {
1604 ATRACE_CALL();
1605 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1606 int32_t hwcId = -1;
1607 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1608 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1609 if (displayDevice->isPrimary()) {
1610 hwcId = displayDevice->getHwcDisplayId();
1611 break;
1612 }
1613 }
1614 if (hwcId < 0) {
1615 ALOGE("LayerStats: Hmmm, no primary display?");
1616 return;
1617 }
1618 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1619 }
1620}
1621
Chia-I Wu30505fb2018-03-26 16:20:31 -07001622void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001624 ATRACE_CALL();
1625 ALOGV("preComposition");
1626
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001628 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001629 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630 needExtraInvalidate = true;
1631 }
Robert Carr2047fae2016-11-28 14:09:09 -08001632 });
1633
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634 if (needExtraInvalidate) {
1635 signalLayerUpdate();
1636 }
1637}
1638
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639void SurfaceFlinger::updateCompositorTiming(
1640 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1641 std::shared_ptr<FenceTime>& presentFenceTime) {
1642 // Update queue of past composite+present times and determine the
1643 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001644 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001646 while (!getBE().mCompositePresentTimes.empty()) {
1647 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 // Cached values should have been updated before calling this method,
1649 // which helps avoid duplicate syscalls.
1650 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1651 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1652 break;
1653 }
1654 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001655 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 }
1657
1658 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001659 while (getBE().mCompositePresentTimes.size() > 16) {
1660 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 }
1662
Brian Andersond0010582017-03-07 13:20:31 -08001663 setCompositorTimingSnapped(
1664 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1665}
1666
1667void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1668 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 // Integer division and modulo round toward 0 not -inf, so we need to
1670 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001671 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1673 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1674
Brian Andersond0010582017-03-07 13:20:31 -08001675 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1676 if (idealLatency <= 0) {
1677 idealLatency = vsyncInterval;
1678 }
1679
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 // Snap the latency to a value that removes scheduling jitter from the
1681 // composition and present times, which often have >1ms of jitter.
1682 // Reducing jitter is important if an app attempts to extrapolate
1683 // something (such as user input) to an accurate diasplay time.
1684 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1685 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001686 nsecs_t bias = vsyncInterval / 2;
1687 int64_t extraVsyncs =
1688 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1689 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1690 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691
David Sodman99974d22017-11-28 12:04:33 -08001692 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1693 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1694 getBE().mCompositorTiming.interval = vsyncInterval;
1695 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696}
1697
Chia-I Wu30505fb2018-03-26 16:20:31 -07001698void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 ATRACE_CALL();
1701 ALOGV("postComposition");
1702
Brian Anderson3546a3f2016-07-14 11:51:14 -07001703 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001704 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001705 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001706 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001707 }
1708
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001709 // |mStateLock| not needed as we are on the main thread
1710 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711
David Sodman73beded2017-11-15 11:56:06 -08001712 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001714 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715 glCompositionDoneFenceTime =
1716 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001717 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718 } else {
1719 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1720 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721
David Sodman73beded2017-11-15 11:56:06 -08001722 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001723 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001724 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001725 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1728 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1729
Chia-I Wu30505fb2018-03-26 16:20:31 -07001730 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 // when we started doing work for this frame, but that should be okay
1732 // since updateCompositorTiming has snapping logic.
1733 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001734 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001735 CompositorTiming compositorTiming;
1736 {
David Sodman99974d22017-11-28 12:04:33 -08001737 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1738 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001739 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740
Robert Carr2047fae2016-11-28 14:09:09 -08001741 mDrawingState.traverseInZOrder([&](Layer* layer) {
1742 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001743 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001744 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001745 recordBufferingStats(layer->getName().string(),
1746 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001747 }
Robert Carr2047fae2016-11-28 14:09:09 -08001748 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001749
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001750 if (presentFenceTime->isValid()) {
1751 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001752 enableHardwareVsync();
1753 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001754 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001755 }
1756 }
1757
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001758 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001759 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001760 enableHardwareVsync();
1761 }
1762 }
1763
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001764 if (mAnimCompositionPending) {
1765 mAnimCompositionPending = false;
1766
Brian Anderson4e606e32017-03-16 15:34:57 -07001767 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001769 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001770 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001771 // The HWC doesn't support present fences, so use the refresh
1772 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001773 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001774 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775 mAnimFrameTracker.setActualPresentTime(presentTime);
1776 }
1777 mAnimFrameTracker.advanceFrame();
1778 }
Dan Stozab90cf072015-03-05 11:05:59 -08001779
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001780 mTimeStats.incrementTotalFrames();
1781 if (mHadClientComposition) {
1782 mTimeStats.incrementClientCompositionFrames();
1783 }
1784
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001785 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1786 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001787 return;
1788 }
1789
1790 nsecs_t currentTime = systemTime();
1791 if (mHasPoweredOff) {
1792 mHasPoweredOff = false;
1793 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001794 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001795 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001796 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1797 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001798 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001799 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001800 }
David Sodman4a36e932017-11-07 14:29:47 -08001801 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001802 }
David Sodman4a36e932017-11-07 14:29:47 -08001803 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804}
1805
1806void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 ATRACE_CALL();
1808 ALOGV("rebuildLayerStacks");
1809
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001812 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 mVisibleRegionsDirty = false;
1814 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001815
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1817 Region opaqueRegion;
1818 Region dirtyRegion;
1819 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001820 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1822 const Transform& tr(displayDevice->getTransform());
1823 const Rect bounds(displayDevice->getBounds());
1824 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001825 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001826
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001828 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001829 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1830 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001831 Region drawRegion(tr.transform(
1832 layer->visibleNonTransparentRegion));
1833 drawRegion.andSelf(bounds);
1834 if (!drawRegion.isEmpty()) {
1835 layersSortedByZ.add(layer);
1836 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001837 // Clear out the HWC layer if this layer was
1838 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001839 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001840 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001841 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001842 } else {
1843 // WM changes displayDevice->layerStack upon sleep/awake.
1844 // Here we make sure we delete the HWC layers even if
1845 // WM changed their layer stack.
1846 hwcLayerDestroyed = layer->destroyHwcLayer(
1847 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001848 }
1849
1850 // If a layer is not going to get a release fence because
1851 // it is invisible, but it is also going to release its
1852 // old buffer, add it to the list of layers needing
1853 // fences.
1854 if (hwcLayerDestroyed) {
1855 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1856 mLayersWithQueuedFrames.cend(), layer);
1857 if (found != mLayersWithQueuedFrames.cend()) {
1858 layersNeedingFences.add(layer);
1859 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001860 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 });
1862 }
1863 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001864 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 displayDevice->undefinedRegion.set(bounds);
1866 displayDevice->undefinedRegion.subtractSelf(
1867 tr.transform(opaqueRegion));
1868 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001870 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001872
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873// Returns a dataspace that fits all visible layers. The returned dataspace
1874// can only be one of
1875//
1876// - Dataspace::V0_SRGB
1877// - Dataspace::DISPLAY_P3
1878// - Dataspace::V0_SCRGB_LINEAR
1879// TODO(b/73825729) Add BT2020 data space.
1880ui::Dataspace SurfaceFlinger::getBestDataspace(
1881 const sp<const DisplayDevice>& displayDevice) const {
1882 Dataspace bestDataspace = Dataspace::V0_SRGB;
1883 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1884 switch (layer->getDataSpace()) {
1885 case Dataspace::V0_SCRGB:
1886 case Dataspace::V0_SCRGB_LINEAR:
1887 // return immediately
1888 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001889 case Dataspace::DISPLAY_P3:
1890 bestDataspace = Dataspace::DISPLAY_P3;
1891 break;
1892 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1893 // since SurfaceFlinger simulates HDR support now, it should honor
1894 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895 case Dataspace::BT2020_PQ:
1896 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001897 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898 return Dataspace::V0_SCRGB_LINEAR;
1899 }
1900 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001901 case Dataspace::BT2020_HLG:
1902 case Dataspace::BT2020_ITU_HLG:
1903 if (!displayDevice->hasHLGSupport()) {
1904 return Dataspace::V0_SCRGB_LINEAR;
1905 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906 break;
1907 default:
1908 break;
1909 }
Romain Guy54f154a2017-10-24 21:40:32 +01001910 }
1911
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001913}
1914
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915// Pick the ColorMode / Dataspace for the display device.
1916// TODO(b/73825729) Add BT2020 color mode.
1917void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1918 ColorMode* outMode, Dataspace* outDataSpace) const {
1919 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1920 *outMode = ColorMode::NATIVE;
1921 *outDataSpace = Dataspace::UNKNOWN;
1922 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001923 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001924
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925 switch (getBestDataspace(displayDevice)) {
1926 case Dataspace::DISPLAY_P3:
1927 case Dataspace::V0_SCRGB_LINEAR:
1928 *outMode = ColorMode::DISPLAY_P3;
1929 *outDataSpace = Dataspace::DISPLAY_P3;
1930 break;
1931 default:
1932 *outMode = ColorMode::SRGB;
1933 *outDataSpace = Dataspace::V0_SRGB;
1934 break;
1935 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001936}
1937
Chia-I Wu30505fb2018-03-26 16:20:31 -07001938void SurfaceFlinger::setUpHWComposer() {
1939 ATRACE_CALL();
1940 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941
Jesse Hall028dc8f2013-08-20 16:35:32 -07001942 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001943 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001944 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1945 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1946
1947 // If nothing has changed (!dirty), don't recompose.
1948 // If something changed, but we don't currently have any visible layers,
1949 // and didn't when we last did a composition, then skip it this time.
1950 // The second rule does two things:
1951 // - When all layers are removed from a display, we'll emit one black
1952 // frame, then nothing more until we get new layers.
1953 // - When a display is created with a private layer stack, we won't
1954 // emit any black frames until a layer is added to the layer stack.
1955 bool mustRecompose = dirty && !(empty && wasEmpty);
1956
Dominik Laskowski281644e2018-04-19 15:47:35 -07001957 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001958 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1959 mustRecompose ? "doing" : "skipping",
1960 dirty ? "+" : "-",
1961 empty ? "+" : "-",
1962 wasEmpty ? "+" : "-");
1963
Dan Stoza71433162014-02-04 16:22:36 -08001964 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001965
1966 if (mustRecompose) {
1967 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1968 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001969 }
1970
Chia-I Wu30505fb2018-03-26 16:20:31 -07001971 // build the h/w work list
1972 if (CC_UNLIKELY(mGeometryInvalid)) {
1973 mGeometryInvalid = false;
1974 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1975 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1976 const auto hwcId = displayDevice->getHwcDisplayId();
1977 if (hwcId >= 0) {
1978 const Vector<sp<Layer>>& currentLayers(
1979 displayDevice->getVisibleLayersSortedByZ());
1980 for (size_t i = 0; i < currentLayers.size(); i++) {
1981 const auto& layer = currentLayers[i];
1982 if (!layer->hasHwcLayer(hwcId)) {
1983 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1984 layer->forceClientComposition(hwcId);
1985 continue;
1986 }
1987 }
1988
1989 layer->setGeometry(displayDevice, i);
1990 if (mDebugDisableHWC || mDebugRegion) {
1991 layer->forceClientComposition(hwcId);
1992 }
1993 }
1994 }
1995 }
1996 }
1997
Chia-I Wu30505fb2018-03-26 16:20:31 -07001998 // Set the per-frame data
1999 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2000 auto& displayDevice = mDisplays[displayId];
2001 const auto hwcId = displayDevice->getHwcDisplayId();
2002
2003 if (hwcId < 0) {
2004 continue;
2005 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002006 if (mDrawingState.colorMatrixChanged) {
2007 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2008 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002009 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2010 "display %zd: %d", displayId, result);
2011 }
2012 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002013 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2014 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002015 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002016 layer->forceClientComposition(hwcId);
2017 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002018 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2019 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2020 !displayDevice->hasHLGSupport()) {
2021 layer->forceClientComposition(hwcId);
2022 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002023
2024 if (layer->getForceClientComposition(hwcId)) {
2025 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2026 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2027 continue;
2028 }
2029
2030 layer->setPerFrameData(displayDevice);
2031 }
2032
2033 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002034 ColorMode colorMode;
2035 Dataspace dataSpace;
2036 pickColorMode(displayDevice, &colorMode, &dataSpace);
2037 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002038 }
2039 }
2040
Chia-I Wu28f320b2018-05-03 11:02:56 -07002041 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002042
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002044 auto& displayDevice = mDisplays[displayId];
2045 if (!displayDevice->isDisplayOn()) {
2046 continue;
2047 }
2048
David Sodman105b7dc2017-11-04 20:28:14 -07002049 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2051 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002052 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002054
Mathias Agopiancd60f992012-08-16 16:28:27 -07002055void SurfaceFlinger::doComposition() {
2056 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 ALOGV("doComposition");
2058
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002059 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002060 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002061 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002062 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002063 // transform the dirty region into this screen's coordinate space
2064 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002065
2066 // repaint the framebuffer (if needed)
2067 doDisplayComposition(hw, dirtyRegion);
2068
Mathias Agopiancd60f992012-08-16 16:28:27 -07002069 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002070 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002071 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002072 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002073 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002074}
2075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002076void SurfaceFlinger::postFramebuffer()
2077{
Mathias Agopian841cde52012-03-01 15:44:37 -08002078 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002080
Mathias Agopiana44b0412011-10-16 18:46:35 -07002081 const nsecs_t now = systemTime();
2082 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002083
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2085 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002086 if (!displayDevice->isDisplayOn()) {
2087 continue;
2088 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 const auto hwcId = displayDevice->getHwcDisplayId();
2090 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002091 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002092 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002093 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002094 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002095 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002096 // The layer buffer from the previous frame (if any) is released
2097 // by HWC only when the release fence from this frame (if any) is
2098 // signaled. Always get the release fence from HWC first.
2099 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002100 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002101
2102 // If the layer was client composited in the previous frame, we
2103 // need to merge with the previous client target acquire fence.
2104 // Since we do not track that, always merge with the current
2105 // client target acquire fence when it is available, even though
2106 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002108 releaseFence = Fence::merge("LayerRelease", releaseFence,
2109 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002110 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002111
David Sodmanb8af7922017-12-21 15:17:55 -08002112 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002113 }
Chia-I Wu83806892017-11-16 10:50:20 -08002114
2115 // We've got a list of layers needing fences, that are disjoint with
2116 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2117 // supply them with the present fence.
2118 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002119 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002120 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002121 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002122 }
2123 }
2124
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002126 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002127 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002128 }
2129
Mathias Agopiana44b0412011-10-16 18:46:35 -07002130 mLastSwapBufferTime = systemTime() - now;
2131 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002132
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002133 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002134 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2135 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2136 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2137 logFrameStats();
2138 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140}
2141
Mathias Agopian87baae12012-07-31 12:38:26 -07002142void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143{
Mathias Agopian841cde52012-03-01 15:44:37 -08002144 ATRACE_CALL();
2145
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002146 // here we keep a copy of the drawing state (that is the state that's
2147 // going to be overwritten by handleTransactionLocked()) outside of
2148 // mStateLock so that the side-effects of the State assignment
2149 // don't happen with mStateLock held (which can cause deadlocks).
2150 State drawingState(mDrawingState);
2151
Mathias Agopianca4d3602011-05-19 15:38:14 -07002152 Mutex::Autolock _l(mStateLock);
2153 const nsecs_t now = systemTime();
2154 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155
Mathias Agopianca4d3602011-05-19 15:38:14 -07002156 // Here we're guaranteed that some transaction flags are set
2157 // so we can call handleTransactionLocked() unconditionally.
2158 // We call getTransactionFlags(), which will also clear the flags,
2159 // with mStateLock held to guarantee that mCurrentState won't change
2160 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002161
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002162 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002163 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002164 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002165
Mathias Agopianca4d3602011-05-19 15:38:14 -07002166 mLastTransactionTime = systemTime() - now;
2167 mDebugInTransaction = 0;
2168 invalidateHwcGeometry();
2169 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002170}
2171
Lloyd Pique715a2c12017-12-14 17:18:08 -08002172DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002173 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002174 // Figure out whether the event is for the primary display or an
2175 // external display by matching the Hwc display id against one for a
2176 // connected display. If we did not find a match, we then check what
2177 // displays are not already connected to determine the type. If we don't
2178 // have a connected primary display, we assume the new display is meant to
2179 // be the primary display, and then if we don't have an external display,
2180 // we assume it is that.
2181 const auto primaryDisplayId =
2182 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2183 const auto externalDisplayId =
2184 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2185 if (primaryDisplayId && primaryDisplayId == display) {
2186 return DisplayDevice::DISPLAY_PRIMARY;
2187 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002188 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002189 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2190 return DisplayDevice::DISPLAY_PRIMARY;
2191 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2192 return DisplayDevice::DISPLAY_EXTERNAL;
2193 }
2194
2195 return DisplayDevice::DISPLAY_ID_INVALID;
2196}
2197
Lloyd Piqueba04e622017-12-14 17:11:26 -08002198void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2199 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002200 auto displayType = determineDisplayType(event.display, event.connection);
2201 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2202 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2203 continue;
2204 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002205
2206 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2207 ALOGE("External displays are not supported by the vr hardware composer.");
2208 continue;
2209 }
2210
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002211 const auto displayId =
2212 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2213 if (displayId) {
2214 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2215 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216
2217 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002218 if (!mBuiltinDisplays[displayType].get()) {
2219 ALOGV("Creating built in display %d", displayType);
2220 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002221 DisplayDeviceState info;
2222 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002223 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2224 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002225 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002226 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2227 mInterceptor->saveDisplayCreation(info);
2228 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002229 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002230 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002231
Lloyd Piquefcd86612017-12-14 17:15:36 -08002232 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2233 if (idx >= 0) {
2234 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002235 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002236 mCurrentState.displays.removeItemsAt(idx);
2237 }
2238 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002239 }
2240
2241 processDisplayChangesLocked();
2242 }
2243
2244 mPendingHotplugEvents.clear();
2245}
2246
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2248 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2249 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250 bool hasWideColorGamut = false;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002252 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 for (ColorMode colorMode : modes) {
2254 switch (colorMode) {
2255 case ColorMode::DISPLAY_P3:
2256 case ColorMode::ADOBE_RGB:
2257 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261 default:
2262 break;
2263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002264
2265 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2266 colorMode);
2267 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2268 for (auto intent : renderIntents) {
2269 if (intent == RenderIntent::ENHANCE) {
2270 mBuiltinDisplaySupportsEnhance = true;
2271 break;
2272 }
2273 }
2274 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275 }
2276 }
2277
Peiyong Lin62665892018-04-16 11:07:44 -07002278 HdrCapabilities hdrCapabilities;
2279 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280
2281 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2282 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2283
2284 /*
2285 * Create our display's surface
2286 */
2287 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2288 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002289 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 renderSurface->setNativeWindow(nativeWindow.get());
2291 const int displayWidth = renderSurface->queryWidth();
2292 const int displayHeight = renderSurface->queryHeight();
2293
2294 // Make sure that composition can never be stalled by a virtual display
2295 // consumer that isn't processing buffers fast enough. We have to do this
2296 // in two places:
2297 // * Here, in case the display is composed entirely by HWC.
2298 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2299 // window's swap interval in eglMakeCurrent, so they'll override the
2300 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002301 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002302 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2303 }
2304
2305 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002306 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002307
2308 sp<DisplayDevice> hw =
2309 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2310 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002311 hasWideColorGamut, hdrCapabilities,
2312 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2313 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314
2315 if (maxFrameBufferAcquiredBuffers >= 3) {
2316 nativeWindowSurface->preallocateBuffers();
2317 }
2318
2319 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2321 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326 hw->setLayerStack(state.layerStack);
2327 hw->setProjection(state.orientation, state.viewport, state.frame);
2328 hw->setDisplayName(state.displayName);
2329
2330 return hw;
2331}
2332
Lloyd Pique347200f2017-12-14 17:00:15 -08002333void SurfaceFlinger::processDisplayChangesLocked() {
2334 // here we take advantage of Vector's copy-on-write semantics to
2335 // improve performance by skipping the transaction entirely when
2336 // know that the lists are identical
2337 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2338 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2339 if (!curr.isIdenticalTo(draw)) {
2340 mVisibleRegionsDirty = true;
2341 const size_t cc = curr.size();
2342 size_t dc = draw.size();
2343
2344 // find the displays that were removed
2345 // (ie: in drawing state but not in current state)
2346 // also handle displays that changed
2347 // (ie: displays that are in both lists)
2348 for (size_t i = 0; i < dc;) {
2349 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2350 if (j < 0) {
2351 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002352 // Call makeCurrent() on the primary display so we can
2353 // be sure that nothing associated with this display
2354 // is current.
2355 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2356 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2357 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2358 if (hw != nullptr) hw->disconnect(getHwComposer());
2359 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2360 mEventThread->onHotplugReceived(draw[i].type, false);
2361 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002362 } else {
2363 // this display is in both lists. see if something changed.
2364 const DisplayDeviceState& state(curr[j]);
2365 const wp<IBinder>& display(curr.keyAt(j));
2366 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2367 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2368 if (state_binder != draw_binder) {
2369 // changing the surface is like destroying and
2370 // recreating the DisplayDevice, so we just remove it
2371 // from the drawing state, so that it get re-added
2372 // below.
2373 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2374 if (hw != nullptr) hw->disconnect(getHwComposer());
2375 mDisplays.removeItem(display);
2376 mDrawingState.displays.removeItemsAt(i);
2377 dc--;
2378 // at this point we must loop to the next item
2379 continue;
2380 }
2381
2382 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2383 if (disp != nullptr) {
2384 if (state.layerStack != draw[i].layerStack) {
2385 disp->setLayerStack(state.layerStack);
2386 }
2387 if ((state.orientation != draw[i].orientation) ||
2388 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2389 disp->setProjection(state.orientation, state.viewport, state.frame);
2390 }
2391 if (state.width != draw[i].width || state.height != draw[i].height) {
2392 disp->setDisplaySize(state.width, state.height);
2393 }
2394 }
2395 }
2396 ++i;
2397 }
2398
2399 // find displays that were added
2400 // (ie: in current state but not in drawing state)
2401 for (size_t i = 0; i < cc; i++) {
2402 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2403 const DisplayDeviceState& state(curr[i]);
2404
2405 sp<DisplaySurface> dispSurface;
2406 sp<IGraphicBufferProducer> producer;
2407 sp<IGraphicBufferProducer> bqProducer;
2408 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002409 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002410
2411 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002412 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002413 // Virtual displays without a surface are dormant:
2414 // they have external state (layer stack, projection,
2415 // etc.) but no internal state (i.e. a DisplayDevice).
2416 if (state.surface != nullptr) {
2417 // Allow VR composer to use virtual displays.
2418 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2419 int width = 0;
2420 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2421 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2422 int height = 0;
2423 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2424 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2425 int intFormat = 0;
2426 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2427 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002428 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002429
2430 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2431 }
2432
2433 // TODO: Plumb requested format back up to consumer
2434
2435 sp<VirtualDisplaySurface> vds =
2436 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2437 bqProducer, bqConsumer,
2438 state.displayName);
2439
2440 dispSurface = vds;
2441 producer = vds;
2442 }
2443 } else {
2444 ALOGE_IF(state.surface != nullptr,
2445 "adding a supported display, but rendering "
2446 "surface is provided (%p), ignoring it",
2447 state.surface.get());
2448
2449 hwcId = state.type;
2450 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2451 producer = bqProducer;
2452 }
2453
2454 const wp<IBinder>& display(curr.keyAt(i));
2455 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002456 mDisplays.add(display,
2457 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2458 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002459 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002460 mEventThread->onHotplugReceived(state.type, true);
2461 }
2462 }
2463 }
2464 }
2465 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466
2467 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002468}
2469
Mathias Agopian87baae12012-07-31 12:38:26 -07002470void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002471{
Dan Stoza7dde5992015-05-22 09:51:44 -07002472 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002473 mCurrentState.traverseInZOrder([](Layer* layer) {
2474 layer->notifyAvailableFrames();
2475 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477 /*
2478 * Traversal of the children
2479 * (perform the transaction for each of them if needed)
2480 */
2481
Mathias Agopian3559b072012-08-15 13:46:03 -07002482 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002483 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002485 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486
2487 const uint32_t flags = layer->doTransaction(0);
2488 if (flags & Layer::eVisibleRegion)
2489 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002490 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 }
2492
2493 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002494 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 */
2496
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002499 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002503 // The transform hint might have changed for some layers
2504 // (either because a display has changed, or because a layer
2505 // as changed).
2506 //
2507 // Walk through all the layers in currentLayers,
2508 // and update their transform hint.
2509 //
2510 // If a layer is visible only on a single display, then that
2511 // display is used to calculate the hint, otherwise we use the
2512 // default display.
2513 //
2514 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2515 // the hint is set before we acquire a buffer from the surface texture.
2516 //
2517 // NOTE: layer transactions have taken place already, so we use their
2518 // drawing state. However, SurfaceFlinger's own transaction has not
2519 // happened yet, so we must use the current state layer list
2520 // (soon to become the drawing state list).
2521 //
2522 sp<const DisplayDevice> disp;
2523 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002524 bool first = true;
2525 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002526 // NOTE: we rely on the fact that layers are sorted by
2527 // layerStack first (so we don't have to traverse the list
2528 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002530 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002531 currentlayerStack = layerStack;
2532 // figure out if this layerstack is mirrored
2533 // (more than one display) if so, pick the default display,
2534 // if not, pick the only display it's on.
2535 disp.clear();
2536 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2537 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002538 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002539 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002540 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002541 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002542 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002543 break;
2544 }
2545 }
2546 }
2547 }
Chet Haase91d25932013-04-11 15:24:55 -07002548
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002549 if (disp == nullptr) {
2550 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2551 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002552
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002553 // could be null when this layer is using a layerStack
2554 // that is not visible on any display. Also can occur at
2555 // screen off/on times.
2556 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002557 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002558
2559 // disp can be null if there is no display available at all to get
2560 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002561 if (disp != nullptr) {
2562 layer->updateTransformHint(disp);
2563 }
Robert Carr2047fae2016-11-28 14:09:09 -08002564
2565 first = false;
2566 });
Mathias Agopian84300952012-11-21 16:02:13 -08002567 }
2568
2569
Mathias Agopian3559b072012-08-15 13:46:03 -07002570 /*
2571 * Perform our own transaction if needed
2572 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573
2574 if (mLayersAdded) {
2575 mLayersAdded = false;
2576 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002577 mVisibleRegionsDirty = true;
2578 }
2579
2580 // some layers might have been removed, so
2581 // we need to update the regions they're exposing.
2582 if (mLayersRemoved) {
2583 mLayersRemoved = false;
2584 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002585 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 // this layer is not visible anymore
2588 // TODO: we could traverse the tree from front to back and
2589 // compute the actual visible region
2590 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 Region visibleReg;
2592 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002593 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002594 }
Robert Carr2047fae2016-11-28 14:09:09 -08002595 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 }
2597
2598 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002599
2600 updateCursorAsync();
2601}
2602
2603void SurfaceFlinger::updateCursorAsync()
2604{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2606 auto& displayDevice = mDisplays[displayId];
2607 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002608 continue;
2609 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610
2611 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2612 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002613 }
2614 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002615}
2616
2617void SurfaceFlinger::commitTransaction()
2618{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002619 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002620 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002621 for (const auto& l : mLayersPendingRemoval) {
2622 recordBufferingStats(l->getName().string(),
2623 l->getOccupancyHistory(true));
2624 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002625 }
2626 mLayersPendingRemoval.clear();
2627 }
2628
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002629 // If this transaction is part of a window animation then the next frame
2630 // we composite should be considered an animation as well.
2631 mAnimCompositionPending = mAnimTransactionPending;
2632
Mathias Agopian4fec8732012-06-29 14:12:52 -07002633 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002634 // clear the "changed" flags in current state
2635 mCurrentState.colorMatrixChanged = false;
2636
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637 mDrawingState.traverseInZOrder([](Layer* layer) {
2638 layer->commitChildList();
2639 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002640 mTransactionPending = false;
2641 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643}
2644
Chia-I Wuab0c3192017-08-01 11:29:00 -07002645void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002646 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647{
Mathias Agopian841cde52012-03-01 15:44:37 -08002648 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002650
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 Region aboveOpaqueLayers;
2652 Region aboveCoveredLayers;
2653 Region dirty;
2654
Mathias Agopian87baae12012-07-31 12:38:26 -07002655 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Robert Carr2047fae2016-11-28 14:09:09 -08002657 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002659 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660
Jesse Hall01e29052013-02-19 16:13:35 -08002661 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002662 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002663 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002664
Mathias Agopianab028732010-03-16 16:41:46 -07002665 /*
2666 * opaqueRegion: area of a surface that is fully opaque.
2667 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002669
2670 /*
2671 * visibleRegion: area of a surface that is visible on screen
2672 * and not fully transparent. This is essentially the layer's
2673 * footprint minus the opaque regions above it.
2674 * Areas covered by a translucent surface are considered visible.
2675 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002677
2678 /*
2679 * coveredRegion: area of a surface that is covered by all
2680 * visible regions above it (which includes the translucent areas).
2681 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002683
Jesse Halla8026d22012-09-25 13:25:04 -07002684 /*
2685 * transparentRegion: area of a surface that is hinted to be completely
2686 * transparent. This is only used to tell when the layer has no visible
2687 * non-transparent regions and can be removed from the layer list. It
2688 * does not affect the visibleRegion of this layer or any layers
2689 * beneath it. The hint may not be correct if apps don't respect the
2690 * SurfaceView restrictions (which, sadly, some don't).
2691 */
2692 Region transparentRegion;
2693
Mathias Agopianab028732010-03-16 16:41:46 -07002694
2695 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002696 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002697 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002700 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002701 if (!visibleRegion.isEmpty()) {
2702 // Remove the transparent area from the visible region
2703 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002704 if (tr.preserveRects()) {
2705 // transform the transparent region
2706 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002708 // transformation too complex, can't do the
2709 // transparent region optimization.
2710 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711 }
Mathias Agopianab028732010-03-16 16:41:46 -07002712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713
Mathias Agopianab028732010-03-16 16:41:46 -07002714 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002716 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002717 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2718 // the opaque region is the layer's footprint
2719 opaqueRegion = visibleRegion;
2720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 }
2722 }
2723
Robert Carre5f4f692018-01-12 13:12:28 -08002724 if (visibleRegion.isEmpty()) {
2725 layer->clearVisibilityRegions();
2726 return;
2727 }
2728
Mathias Agopianab028732010-03-16 16:41:46 -07002729 // Clip the covered region to the visible region
2730 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2731
2732 // Update aboveCoveredLayers for next (lower) layer
2733 aboveCoveredLayers.orSelf(visibleRegion);
2734
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 // subtract the opaque region covered by the layers above us
2736 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737
2738 // compute this layer's dirty region
2739 if (layer->contentDirty) {
2740 // we need to invalidate the whole region
2741 dirty = visibleRegion;
2742 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 layer->contentDirty = false;
2745 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002746 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002747 * the exposed region consists of two components:
2748 * 1) what's VISIBLE now and was COVERED before
2749 * 2) what's EXPOSED now less what was EXPOSED before
2750 *
2751 * note that (1) is conservative, we start with the whole
2752 * visible region but only keep what used to be covered by
2753 * something -- which mean it may have been exposed.
2754 *
2755 * (2) handles areas that were not covered by anything but got
2756 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002757 */
Mathias Agopianab028732010-03-16 16:41:46 -07002758 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 const Region oldVisibleRegion = layer->visibleRegion;
2760 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002761 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2762 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 }
2764 dirty.subtractSelf(aboveOpaqueLayers);
2765
2766 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002767 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768
Mathias Agopianab028732010-03-16 16:41:46 -07002769 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002771
Jesse Halla8026d22012-09-25 13:25:04 -07002772 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 layer->setVisibleRegion(visibleRegion);
2774 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002775 layer->setVisibleNonTransparentRegion(
2776 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002777 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
Mathias Agopian87baae12012-07-31 12:38:26 -07002779 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780}
2781
Chia-I Wuab0c3192017-08-01 11:29:00 -07002782void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002783 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002784 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002785 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002786 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002787 }
2788 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002789}
2790
Dan Stoza6b9454d2014-11-07 16:00:59 -08002791bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 ALOGV("handlePageFlip");
2794
Brian Andersond6927fb2016-07-23 23:37:30 -07002795 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Mathias Agopian4fec8732012-06-29 14:12:52 -07002797 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002799 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002800
2801 // Store the set of layers that need updates. This set must not change as
2802 // buffers are being latched, as this could result in a deadlock.
2803 // Example: Two producers share the same command stream and:
2804 // 1.) Layer 0 is latched
2805 // 2.) Layer 0 gets a new frame
2806 // 2.) Layer 1 gets a new frame
2807 // 3.) Layer 1 is latched.
2808 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2809 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002811 if (layer->hasQueuedFrame()) {
2812 frameQueued = true;
2813 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002815 } else {
2816 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002818 } else {
2819 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 }
Robert Carr2047fae2016-11-28 14:09:09 -08002821 });
2822
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002824 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002825 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002826 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002827 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002828 newDataLatched = true;
2829 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002830 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002831
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002832 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833
2834 // If we will need to wake up at some time in the future to deal with a
2835 // queued frame that shouldn't be displayed during this vsync period, wake
2836 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002837 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838 signalLayerUpdate();
2839 }
2840
2841 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002842 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843}
2844
Mathias Agopianad456f92011-01-13 17:53:01 -08002845void SurfaceFlinger::invalidateHwcGeometry()
2846{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002848}
2849
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002850
Fabien Sanglard830b8472016-11-30 16:35:58 -08002851void SurfaceFlinger::doDisplayComposition(
2852 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002853 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854{
Dan Stoza71433162014-02-04 16:22:36 -08002855 // We only need to actually compose the display if:
2856 // 1) It is being handled by hardware composer, which may need this to
2857 // keep its virtual display state machine in sync, or
2858 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002859 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002860 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002862 return;
2863 }
2864
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002866 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002867
2868 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002869 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870}
2871
Chia-I Wub02087d2017-11-09 10:19:54 -08002872bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002873{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002875
Chia-I Wub02087d2017-11-09 10:19:54 -08002876 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002877 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002879 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2880 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2881 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2882 HWC2::Capability::SkipClientColorTransform);
2883 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002884
2885 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002886 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2887 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002888 if (applyColorMatrix) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07002889 oldColorMatrix = getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
2890 legacySrgbSaturationMatrix = mDrawingState.colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002891 }
2892
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 if (hasClientComposition) {
2894 ALOGV("hasClientComposition");
2895
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002896 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002897 if (displayDevice->hasWideColorGamut()) {
2898 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002899 }
2900 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002901 getBE().mRenderEngine->setDisplayMaxLuminance(
2902 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002903
Chia-I Wu7f402902017-11-09 12:51:10 -08002904 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002905 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002906 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002907 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002908
2909 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002910 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002911 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2912 }
2913 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002914 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002915
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002916 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002918 // when using overlays, we assume a fully transparent framebuffer
2919 // NOTE: we could reduce how much we need to clear, for instance
2920 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002921 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002922 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002923 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002925 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002926 // we're left with the letterbox region
2927 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002928 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002929
2930 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002932
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002934 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002938 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002939
Dominik Laskowski281644e2018-04-19 15:47:35 -07002940 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002941 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002942 // scissor on the main display. It should never be needed
2943 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 const Rect& bounds(displayDevice->getBounds());
2945 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002946 if (scissor != bounds) {
2947 // scissor doesn't match the screen's dimensions, so we
2948 // need to clear everything outside of it and enable
2949 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002950
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002953 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002954 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002955 }
2956 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002957 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002958
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 /*
2960 * and then, render the layers targeted at the framebuffer
2961 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002962
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 ALOGV("Rendering client layers");
2964 const Transform& displayTransform = displayDevice->getTransform();
2965 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002966 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 bool firstLayer = true;
2968 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002969 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 displayTransform.transform(layer->visibleRegion)));
2971 ALOGV("Layer: %s", layer->getName().string());
2972 ALOGV(" Composition type: %s",
2973 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 switch (layer->getCompositionType(hwcId)) {
2976 case HWC2::Composition::Cursor:
2977 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002978 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002980 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002982 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002984 // never clear the very first layer since we're
2985 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002986 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002987 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002988 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002989 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002991 // Only apply saturation matrix layer that is legacy SRGB dataspace
2992 // when auto color mode is on.
2993 bool restore = false;
2994 mat4 savedMatrix;
2995 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2996 layer->isLegacySrgbDataSpace()) {
2997 savedMatrix =
2998 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
2999 restore = true;
3000 }
chaviwa76b2712017-09-20 12:02:26 -07003001 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003002 if (restore) {
3003 getRenderEngine().setupColorTransform(savedMatrix);
3004 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003005 break;
3006 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003007 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003008 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003009 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003010 } else {
3011 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003012 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003014 }
3015 } else {
3016 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003017 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003018 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003020 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003021 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003022 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003023 }
3024 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003025
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003026 if (applyColorMatrix) {
3027 getRenderEngine().setupColorTransform(oldColorMatrix);
3028 }
3029
Mathias Agopianf45c5102012-10-24 16:29:17 -07003030 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003031 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003032 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033}
3034
Fabien Sanglard830b8472016-11-30 16:35:58 -08003035void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3036 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003037 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003038 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Dan Stoza7d89d062015-04-30 13:29:25 -07003041status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003042 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003043 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003044 const sp<Layer>& lbc,
3045 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003046{
Dan Stoza7d89d062015-04-30 13:29:25 -07003047 // add this layer to the current state list
3048 {
3049 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003051 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3052 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003053 return NO_MEMORY;
3054 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 if (parent == nullptr) {
3056 mCurrentState.layersSortedByZ.add(lbc);
3057 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003058 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003059 ALOGE("addClientLayer called with a removed parent");
3060 return NAME_NOT_FOUND;
3061 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 parent->addChild(lbc);
3063 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003064
Dan Stoza101d8dc2018-02-27 15:42:25 -08003065 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003066 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3067 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3068 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3069 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3070 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 mLayersAdded = true;
3072 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003073 }
3074
Mathias Agopian96f08192010-06-02 23:28:45 -07003075 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003076 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003077
Dan Stoza7d89d062015-04-30 13:29:25 -07003078 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003079}
3080
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003081status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003082 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003083 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3084}
Robert Carr7f9b8992017-03-10 11:08:39 -08003085
chaviwca27f252018-02-06 16:46:39 -08003086status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3087 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003088 if (layer->isPendingRemoval()) {
3089 return NO_ERROR;
3090 }
3091
Robert Carr1f0a16a2016-10-24 16:27:39 -07003092 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003093 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003094 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003095 if (topLevelOnly) {
3096 return NO_ERROR;
3097 }
3098
Chia-I Wu98f1c102017-05-30 14:54:08 -07003099 sp<Layer> ancestor = p;
3100 while (ancestor->getParent() != nullptr) {
3101 ancestor = ancestor->getParent();
3102 }
3103 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3104 ALOGE("removeLayer called with a layer whose parent has been removed");
3105 return NAME_NOT_FOUND;
3106 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003107
3108 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003109 } else {
3110 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003111 }
3112
Robert Carr136e2f62017-02-08 17:54:29 -08003113 // As a matter of normal operation, the LayerCleaner will produce a second
3114 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3115 // so we will succeed in promoting it, but it's already been removed
3116 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3117 // otherwise something has gone wrong and we are leaking the layer.
3118 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003119 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3120 layer->getName().string(),
3121 (p != nullptr) ? p->getName().string() : "no-parent");
3122 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003123 } else if (index < 0) {
3124 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003125 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003126
Chia-I Wuc6657022017-08-15 11:18:17 -07003127 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003128 mLayersPendingRemoval.add(layer);
3129 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003130 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003131 setTransactionFlags(eTransactionNeeded);
3132 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133}
3134
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003135uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003136 return android_atomic_release_load(&mTransactionFlags);
3137}
3138
Mathias Agopian3f844832013-08-07 21:24:32 -07003139uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3141}
3142
Mathias Agopian3f844832013-08-07 21:24:32 -07003143uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003144 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3145}
3146
3147uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3148 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003150 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003152 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153 }
3154 return old;
3155}
3156
chaviwca27f252018-02-06 16:46:39 -08003157bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3158 for (const ComposerState& state : states) {
3159 // Here we need to check that the interface we're given is indeed
3160 // one of our own. A malicious client could give us a nullptr
3161 // IInterface, or one of its own or even one of our own but a
3162 // different type. All these situations would cause us to crash.
3163 if (state.client == nullptr) {
3164 return true;
3165 }
3166
3167 sp<IBinder> binder = IInterface::asBinder(state.client);
3168 if (binder == nullptr) {
3169 return true;
3170 }
3171
3172 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3173 return true;
3174 }
3175 }
3176 return false;
3177}
3178
Mathias Agopian8b33f032012-07-24 20:43:54 -07003179void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003180 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003181 const Vector<DisplayState>& displays,
3182 uint32_t flags)
3183{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003184 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003185 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003186 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003187
chaviwca27f252018-02-06 16:46:39 -08003188 if (containsAnyInvalidClientState(states)) {
3189 return;
3190 }
3191
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 if (flags & eAnimation) {
3193 // For window updates that are part of an animation we must wait for
3194 // previous animation "frames" to be handled.
3195 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003196 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003197 if (CC_UNLIKELY(err != NO_ERROR)) {
3198 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003199 // caller after a few seconds.
3200 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3201 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003202 mAnimTransactionPending = false;
3203 break;
3204 }
3205 }
3206 }
3207
chaviwca27f252018-02-06 16:46:39 -08003208 for (const DisplayState& display : displays) {
3209 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003210 }
3211
chaviwca27f252018-02-06 16:46:39 -08003212 for (const ComposerState& state : states) {
3213 transactionFlags |= setClientStateLocked(state);
3214 }
3215
3216 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3217 // as destroyed should only occur after setting all other states. This is to allow for a
3218 // child re-parent to happen before marking its original parent as destroyed (which would
3219 // then mark the child as destroyed).
3220 for (const ComposerState& state : states) {
3221 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003222 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003223
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003224 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3225 // anyway. This can be used as a flush mechanism for previous async transactions.
3226 // Empty animation transaction can be used to simulate back-pressure, so also force a
3227 // transaction for empty animation transactions.
3228 if (transactionFlags == 0 &&
3229 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003230 transactionFlags = eTransactionNeeded;
3231 }
3232
Mathias Agopian386aa982011-11-07 21:58:03 -08003233 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003234 if (mInterceptor->isEnabled()) {
3235 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003236 }
Irvel468051e2016-06-13 16:44:44 -07003237
Mathias Agopian386aa982011-11-07 21:58:03 -08003238 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003239 const auto start = (flags & eEarlyWakeup)
3240 ? VSyncModulator::TransactionStart::EARLY
3241 : VSyncModulator::TransactionStart::NORMAL;
3242 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003243
3244 // if this is a synchronous transaction, wait for it to take effect
3245 // before returning.
3246 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003247 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003248 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 if (flags & eAnimation) {
3250 mAnimTransactionPending = true;
3251 }
3252 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003253 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3254 if (CC_UNLIKELY(err != NO_ERROR)) {
3255 // just in case something goes wrong in SF, return to the
3256 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003257 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3258 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003259 break;
3260 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 }
3263}
3264
Mathias Agopiane57f2922012-08-09 16:29:12 -07003265uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3266{
Jesse Hall9a143922012-10-04 16:29:19 -07003267 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3268 if (dpyIdx < 0)
3269 return 0;
3270
Mathias Agopiane57f2922012-08-09 16:29:12 -07003271 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003272 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003273 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003274 const uint32_t what = s.what;
3275 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003276 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003277 disp.surface = s.surface;
3278 flags |= eDisplayTransactionNeeded;
3279 }
3280 }
3281 if (what & DisplayState::eLayerStackChanged) {
3282 if (disp.layerStack != s.layerStack) {
3283 disp.layerStack = s.layerStack;
3284 flags |= eDisplayTransactionNeeded;
3285 }
3286 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003287 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 if (disp.orientation != s.orientation) {
3289 disp.orientation = s.orientation;
3290 flags |= eDisplayTransactionNeeded;
3291 }
3292 if (disp.frame != s.frame) {
3293 disp.frame = s.frame;
3294 flags |= eDisplayTransactionNeeded;
3295 }
3296 if (disp.viewport != s.viewport) {
3297 disp.viewport = s.viewport;
3298 flags |= eDisplayTransactionNeeded;
3299 }
3300 }
Michael Lentine47e45402014-07-18 15:34:25 -07003301 if (what & DisplayState::eDisplaySizeChanged) {
3302 if (disp.width != s.width) {
3303 disp.width = s.width;
3304 flags |= eDisplayTransactionNeeded;
3305 }
3306 if (disp.height != s.height) {
3307 disp.height = s.height;
3308 flags |= eDisplayTransactionNeeded;
3309 }
3310 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003311 }
3312 return flags;
3313}
3314
chaviwca27f252018-02-06 16:46:39 -08003315uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3316 const layer_state_t& s = composerState.state;
3317 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3318
Mathias Agopian13127d82013-03-05 17:47:11 -08003319 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003320 if (layer == nullptr) {
3321 return 0;
3322 }
3323
3324 if (layer->isPendingRemoval()) {
3325 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3326 return 0;
3327 }
3328
3329 uint32_t flags = 0;
3330
3331 const uint32_t what = s.what;
3332 bool geometryAppliesWithResize =
3333 what & layer_state_t::eGeometryAppliesWithResize;
3334 if (what & layer_state_t::ePositionChanged) {
3335 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3336 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003337 }
chaviw8b3871a2017-11-01 17:41:01 -07003338 }
3339 if (what & layer_state_t::eLayerChanged) {
3340 // NOTE: index needs to be calculated before we update the state
3341 const auto& p = layer->getParent();
3342 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003343 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003344 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003345 mCurrentState.layersSortedByZ.removeAt(idx);
3346 mCurrentState.layersSortedByZ.add(layer);
3347 // we need traversal (state changed)
3348 // AND transaction (list changed)
3349 flags |= eTransactionNeeded|eTraversalNeeded;
3350 }
chaviw8b3871a2017-11-01 17:41:01 -07003351 } else {
3352 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003353 flags |= eTransactionNeeded|eTraversalNeeded;
3354 }
3355 }
chaviw8b3871a2017-11-01 17:41:01 -07003356 }
3357 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003358 // NOTE: index needs to be calculated before we update the state
3359 const auto& p = layer->getParent();
3360 if (p == nullptr) {
3361 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3362 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3363 mCurrentState.layersSortedByZ.removeAt(idx);
3364 mCurrentState.layersSortedByZ.add(layer);
3365 // we need traversal (state changed)
3366 // AND transaction (list changed)
3367 flags |= eTransactionNeeded|eTraversalNeeded;
3368 }
3369 } else {
3370 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3371 flags |= eTransactionNeeded|eTraversalNeeded;
3372 }
chaviw8b3871a2017-11-01 17:41:01 -07003373 }
3374 }
3375 if (what & layer_state_t::eSizeChanged) {
3376 if (layer->setSize(s.w, s.h)) {
3377 flags |= eTraversalNeeded;
3378 }
3379 }
3380 if (what & layer_state_t::eAlphaChanged) {
3381 if (layer->setAlpha(s.alpha))
3382 flags |= eTraversalNeeded;
3383 }
3384 if (what & layer_state_t::eColorChanged) {
3385 if (layer->setColor(s.color))
3386 flags |= eTraversalNeeded;
3387 }
3388 if (what & layer_state_t::eMatrixChanged) {
3389 if (layer->setMatrix(s.matrix))
3390 flags |= eTraversalNeeded;
3391 }
3392 if (what & layer_state_t::eTransparentRegionChanged) {
3393 if (layer->setTransparentRegionHint(s.transparentRegion))
3394 flags |= eTraversalNeeded;
3395 }
3396 if (what & layer_state_t::eFlagsChanged) {
3397 if (layer->setFlags(s.flags, s.mask))
3398 flags |= eTraversalNeeded;
3399 }
3400 if (what & layer_state_t::eCropChanged) {
3401 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3402 flags |= eTraversalNeeded;
3403 }
3404 if (what & layer_state_t::eFinalCropChanged) {
3405 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3406 flags |= eTraversalNeeded;
3407 }
3408 if (what & layer_state_t::eLayerStackChanged) {
3409 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3410 // We only allow setting layer stacks for top level layers,
3411 // everything else inherits layer stack from its parent.
3412 if (layer->hasParent()) {
3413 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3414 layer->getName().string());
3415 } else if (idx < 0) {
3416 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3417 "that also does not appear in the top level layer list. Something"
3418 " has gone wrong.", layer->getName().string());
3419 } else if (layer->setLayerStack(s.layerStack)) {
3420 mCurrentState.layersSortedByZ.removeAt(idx);
3421 mCurrentState.layersSortedByZ.add(layer);
3422 // we need traversal (state changed)
3423 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003424 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003425 }
3426 }
3427 if (what & layer_state_t::eDeferTransaction) {
3428 if (s.barrierHandle != nullptr) {
3429 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3430 } else if (s.barrierGbp != nullptr) {
3431 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3432 if (authenticateSurfaceTextureLocked(gbp)) {
3433 const auto& otherLayer =
3434 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3435 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3436 } else {
3437 ALOGE("Attempt to defer transaction to to an"
3438 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003439 }
3440 }
chaviw8b3871a2017-11-01 17:41:01 -07003441 // We don't trigger a traversal here because if no other state is
3442 // changed, we don't want this to cause any more work
3443 }
3444 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003445 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003446 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003447 if (!hadParent) {
3448 mCurrentState.layersSortedByZ.remove(layer);
3449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 }
3453 if (what & layer_state_t::eReparentChildren) {
3454 if (layer->reparentChildren(s.reparentHandle)) {
3455 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003456 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 if (what & layer_state_t::eDetachChildren) {
3459 layer->detachChildren();
3460 }
3461 if (what & layer_state_t::eOverrideScalingModeChanged) {
3462 layer->setOverrideScalingMode(s.overrideScalingMode);
3463 // We don't trigger a traversal here because if no other state is
3464 // changed, we don't want this to cause any more work
3465 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003466 return flags;
3467}
3468
chaviwca27f252018-02-06 16:46:39 -08003469void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3470 const layer_state_t& state = composerState.state;
3471 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3472
3473 sp<Layer> layer(client->getLayerUser(state.surface));
3474 if (layer == nullptr) {
3475 return;
3476 }
3477
3478 if (layer->isPendingRemoval()) {
3479 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3480 return;
3481 }
3482
3483 if (state.what & layer_state_t::eDestroySurface) {
3484 removeLayerLocked(mStateLock, layer);
3485 }
3486}
3487
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003488status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003489 const String8& name,
3490 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003491 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003492 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003493 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003495 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003496 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003497 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003499 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003500
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003501 status_t result = NO_ERROR;
3502
3503 sp<Layer> layer;
3504
Cody Northropbc755282017-03-31 12:00:08 -06003505 String8 uniqueName = getUniqueLayerName(name);
3506
Mathias Agopian3165cc22012-08-08 19:42:09 -07003507 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3508 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003509 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003510 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003512
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513 break;
chaviw13fdc492017-06-27 12:40:18 -07003514 case ISurfaceComposerClient::eFXSurfaceColor:
3515 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003516 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003517 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 break;
3519 default:
3520 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 break;
3522 }
3523
Dan Stoza7d89d062015-04-30 13:29:25 -07003524 if (result != NO_ERROR) {
3525 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003527
Chia-I Wuab0c3192017-08-01 11:29:00 -07003528 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3529 // TODO b/64227542
3530 if (windowType == 441731) {
3531 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3532 layer->setPrimaryDisplayOnly();
3533 }
3534
Albert Chaulk479c60c2017-01-27 14:21:34 -05003535 layer->setInfo(windowType, ownerUid);
3536
Robert Carr1f0a16a2016-10-24 16:27:39 -07003537 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003538 if (result != NO_ERROR) {
3539 return result;
3540 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003541 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003542
3543 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003544 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545}
3546
Cody Northropbc755282017-03-31 12:00:08 -06003547String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3548{
3549 bool matchFound = true;
3550 uint32_t dupeCounter = 0;
3551
3552 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3553 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3554
3555 // Loop over layers until we're sure there is no matching name
3556 while (matchFound) {
3557 matchFound = false;
3558 mDrawingState.traverseInZOrder([&](Layer* layer) {
3559 if (layer->getName() == uniqueName) {
3560 matchFound = true;
3561 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3562 }
3563 });
3564 }
3565
3566 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3567
3568 return uniqueName;
3569}
3570
David Sodman0c69cad2017-08-21 12:12:51 -07003571status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003572 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3573 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574{
3575 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003576 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003577 case PIXEL_FORMAT_TRANSPARENT:
3578 case PIXEL_FORMAT_TRANSLUCENT:
3579 format = PIXEL_FORMAT_RGBA_8888;
3580 break;
3581 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003582 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 break;
3584 }
3585
David Sodman0c69cad2017-08-21 12:12:51 -07003586 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3587 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003589 *handle = layer->getHandle();
3590 *gbp = layer->getProducer();
3591 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593
David Sodman0c69cad2017-08-21 12:12:51 -07003594 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596}
3597
chaviw13fdc492017-06-27 12:40:18 -07003598status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003600 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601{
chaviw13fdc492017-06-27 12:40:18 -07003602 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003604 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003605}
3606
Mathias Agopianac9fa422013-02-11 16:40:36 -08003607status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608{
Robert Carr9524cb32017-02-13 11:32:32 -08003609 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003610 status_t err = NO_ERROR;
3611 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003612 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003613 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003614 err = removeLayer(l);
3615 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3616 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003617 }
3618 return err;
3619}
3620
Mathias Agopian13127d82013-03-05 17:47:11 -08003621status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003622{
Mathias Agopian67106042013-03-14 19:18:13 -07003623 // called by ~LayerCleaner() when all references to the IBinder (handle)
3624 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003625 sp<Layer> l = layer.promote();
3626 if (l == nullptr) {
3627 // The layer has already been removed, carry on
3628 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003629 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003630 // If we have a parent, then we can continue to live as long as it does.
3631 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Mathias Agopianb60314a2012-04-10 22:09:54 -07003634// ---------------------------------------------------------------------------
3635
Andy McFadden13a082e2012-08-24 10:16:42 -07003636void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003637 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003638 Vector<ComposerState> state;
3639 Vector<DisplayState> displays;
3640 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003641 d.what = DisplayState::eDisplayProjectionChanged |
3642 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003643 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003644 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003645 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003646 d.frame.makeInvalid();
3647 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003648 d.width = 0;
3649 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003650 displays.add(d);
3651 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003652 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3653 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003654
David Sodman105b7dc2017-11-04 20:28:14 -07003655 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003656 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003657 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003658
Brian Andersond0010582017-03-07 13:20:31 -08003659 // Use phase of 0 since phase is not known.
3660 // Use latency of 0, which will snap to the ideal latency.
3661 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003662}
3663
3664void SurfaceFlinger::initializeDisplays() {
3665 class MessageScreenInitialized : public MessageBase {
3666 SurfaceFlinger* flinger;
3667 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003668 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003669 virtual bool handler() {
3670 flinger->onInitializeDisplays();
3671 return true;
3672 }
3673 };
3674 sp<MessageBase> msg = new MessageScreenInitialized(this);
3675 postMessageAsync(msg); // we may be called from main thread, use async message
3676}
3677
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003678void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003679 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3681 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003682 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003685 return;
3686 }
3687
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003688 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003689 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003690 ALOGW("Trying to set power mode for virtual display");
3691 return;
3692 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003693
Lloyd Pique4dccc412018-01-22 17:21:36 -08003694 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003695 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003696 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3697 if (idx < 0) {
3698 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3699 return;
3700 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003701 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003702 }
3703
Dominik Laskowski281644e2018-04-19 15:47:35 -07003704 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003706 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003708 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709 // FIXME: eventthread only knows about the main display right now
3710 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003711 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003714 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003715 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003716 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003717
3718 struct sched_param param = {0};
3719 param.sched_priority = 1;
3720 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3721 ALOGW("Couldn't set SCHED_FIFO on display on");
3722 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003724 // Turn off the display
3725 struct sched_param param = {0};
3726 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3727 ALOGW("Couldn't set SCHED_OTHER on display off");
3728 }
3729
Dominik Laskowski281644e2018-04-19 15:47:35 -07003730 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003731 disableHardwareVsync(true); // also cancels any in-progress resync
3732
Mathias Agopiancde87a32012-09-13 14:09:01 -07003733 // FIXME: eventthread only knows about the main display right now
3734 mEventThread->onScreenReleased();
3735 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003736
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003737 getHwComposer().setPowerMode(type, mode);
3738 mVisibleRegionsDirty = true;
3739 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003740 } else if (mode == HWC_POWER_MODE_DOZE ||
3741 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003742 // Update display while dozing
3743 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003744 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003745 // FIXME: eventthread only knows about the main display right now
3746 mEventThread->onScreenAcquired();
3747 resyncToHardwareVsync(true);
3748 }
3749 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3750 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003751 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003752 disableHardwareVsync(true); // also cancels any in-progress resync
3753 // FIXME: eventthread only knows about the main display right now
3754 mEventThread->onScreenReleased();
3755 }
3756 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003757 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003758 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003760 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003761 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003762}
3763
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3765 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003766 SurfaceFlinger& mFlinger;
3767 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003768 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003769 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 MessageSetPowerMode(SurfaceFlinger& flinger,
3771 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3772 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003773 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003775 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003777 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003778 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 ALOGW("Attempt to set power mode = %d for virtual display",
3780 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003781 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003782 mFlinger.setPowerModeInternal(
3783 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003784 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785 return true;
3786 }
3787 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003789 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003790}
3791
3792// ---------------------------------------------------------------------------
3793
Lloyd Pique755e3192018-01-31 16:46:15 -08003794status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3795 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003797
Mathias Agopianbd115332013-04-18 16:41:04 -07003798 IPCThreadState* ipc = IPCThreadState::self();
3799 const int pid = ipc->getCallingPid();
3800 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003801
Mathias Agopianbd115332013-04-18 16:41:04 -07003802 if ((uid != AID_SHELL) &&
3803 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003804 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003805 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003807 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003808 // (this would indicate SF is stuck, but we want to be able to
3809 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003810 status_t err = mStateLock.timedLock(s2ns(1));
3811 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003812 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003813 result.appendFormat(
3814 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3815 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003816 }
3817
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818 bool dumpAll = true;
3819 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003820 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003821
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003822 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003823 if ((index < numArgs) &&
3824 (args[index] == String16("--list"))) {
3825 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003827 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003828 }
3829
3830 if ((index < numArgs) &&
3831 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003833 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003834 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003835 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003836
3837 if ((index < numArgs) &&
3838 (args[index] == String16("--latency-clear"))) {
3839 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003841 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003843
3844 if ((index < numArgs) &&
3845 (args[index] == String16("--dispsync"))) {
3846 index++;
3847 mPrimaryDispSync.dump(result);
3848 dumpAll = false;
3849 }
Dan Stozab90cf072015-03-05 11:05:59 -08003850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--static-screen"))) {
3853 index++;
3854 dumpStaticScreenStats(result);
3855 dumpAll = false;
3856 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003857
3858 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003859 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003860 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003861 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003862 dumpAll = false;
3863 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003864
3865 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3866 index++;
3867 dumpWideColorInfo(result);
3868 dumpAll = false;
3869 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--enable-layer-stats"))) {
3873 index++;
3874 mLayerStats.enable();
3875 dumpAll = false;
3876 }
3877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--disable-layer-stats"))) {
3880 index++;
3881 mLayerStats.disable();
3882 dumpAll = false;
3883 }
3884
3885 if ((index < numArgs) &&
3886 (args[index] == String16("--clear-layer-stats"))) {
3887 index++;
3888 mLayerStats.clear();
3889 dumpAll = false;
3890 }
3891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--dump-layer-stats"))) {
3894 index++;
3895 mLayerStats.dump(result);
3896 dumpAll = false;
3897 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--display-identification"))) {
3901 index++;
3902 dumpDisplayIdentificationData(result);
3903 dumpAll = false;
3904 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003905
3906 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3907 index++;
3908 mTimeStats.parseArgs(asProto, args, index, result);
3909 dumpAll = false;
3910 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003912
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003913 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003914 if (asProto) {
3915 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3916 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3917 } else {
3918 dumpAllLocked(args, index, result);
3919 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003920 }
3921
Mathias Agopian9795c422009-08-26 16:36:26 -07003922 if (locked) {
3923 mStateLock.unlock();
3924 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 }
3926 write(fd, result.string(), result.size());
3927 return NO_ERROR;
3928}
3929
Dan Stozac7014012014-02-14 15:03:43 -08003930void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3931 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003932{
Robert Carr2047fae2016-11-28 14:09:09 -08003933 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003934 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003935 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003936}
3937
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003939 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940{
3941 String8 name;
3942 if (index < args.size()) {
3943 name = String8(args[index]);
3944 index++;
3945 }
3946
David Sodman105b7dc2017-11-04 20:28:14 -07003947 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003948 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003949 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003950
3951 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003952 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003953 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003954 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003955 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003956 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003957 }
Robert Carr2047fae2016-11-28 14:09:09 -08003958 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003959 }
3960}
3961
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003963 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964{
3965 String8 name;
3966 if (index < args.size()) {
3967 name = String8(args[index]);
3968 index++;
3969 }
3970
Robert Carr2047fae2016-11-28 14:09:09 -08003971 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003972 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003973 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003974 }
Robert Carr2047fae2016-11-28 14:09:09 -08003975 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003976
Svetoslavd85084b2014-03-20 10:28:31 -07003977 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003978}
3979
Jamie Gennis6547ff42013-07-16 20:12:42 -07003980// This should only be called from the main thread. Otherwise it would need
3981// the lock and should use mCurrentState rather than mDrawingState.
3982void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003983 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003984 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003985 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003986
3987 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3988}
3989
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003990void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003991{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003992 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003993
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003994 if (isLayerTripleBufferingDisabled())
3995 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003996
3997 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003998 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003999 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004000 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004001 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4002 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004003 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004004}
4005
Dan Stozab90cf072015-03-05 11:05:59 -08004006void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4007{
4008 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004009 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4010 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004011 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004012 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004013 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4014 b + 1, bucketTimeSec, percent);
4015 }
David Sodman4a36e932017-11-07 14:29:47 -08004016 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004017 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004018 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004019 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004020 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004021}
4022
Dan Stozae77c7662016-05-13 11:37:28 -07004023void SurfaceFlinger::recordBufferingStats(const char* layerName,
4024 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004025 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4026 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004027 for (const auto& segment : history) {
4028 if (!segment.usedThirdBuffer) {
4029 stats.twoBufferTime += segment.totalTime;
4030 }
4031 if (segment.occupancyAverage < 1.0f) {
4032 stats.doubleBufferedTime += segment.totalTime;
4033 } else if (segment.occupancyAverage < 2.0f) {
4034 stats.tripleBufferedTime += segment.totalTime;
4035 }
4036 ++stats.numSegments;
4037 stats.totalTime += segment.totalTime;
4038 }
4039}
4040
Brian Andersond6927fb2016-07-23 23:37:30 -07004041void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4042 result.appendFormat("Layer frame timestamps:\n");
4043
4044 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4045 const size_t count = currentLayers.size();
4046 for (size_t i=0 ; i<count ; i++) {
4047 currentLayers[i]->dumpFrameEvents(result);
4048 }
4049}
4050
Dan Stozae77c7662016-05-13 11:37:28 -07004051void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4052 result.append("Buffering stats:\n");
4053 result.append(" [Layer name] <Active time> <Two buffer> "
4054 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004055 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004056 typedef std::tuple<std::string, float, float, float> BufferTuple;
4057 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004058 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004059 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004060 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004061 if (stats.numSegments == 0) {
4062 continue;
4063 }
4064 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4065 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4066 stats.totalTime;
4067 float doubleBufferRatio = static_cast<float>(
4068 stats.doubleBufferedTime) / stats.totalTime;
4069 float tripleBufferRatio = static_cast<float>(
4070 stats.tripleBufferedTime) / stats.totalTime;
4071 sorted.insert({activeTime, {name, twoBufferRatio,
4072 doubleBufferRatio, tripleBufferRatio}});
4073 }
4074 for (const auto& sortedPair : sorted) {
4075 float activeTime = sortedPair.first;
4076 const BufferTuple& values = sortedPair.second;
4077 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4078 std::get<0>(values).c_str(), activeTime,
4079 std::get<1>(values), std::get<2>(values),
4080 std::get<3>(values));
4081 }
4082 result.append("\n");
4083}
4084
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004085void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4086 for (size_t d = 0; d < mDisplays.size(); d++) {
4087 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4088 const int32_t hwcId = displayDevice->getHwcDisplayId();
4089 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4090 if (!displayId) {
4091 continue;
4092 }
4093
4094 result.appendFormat("Display %d: ", hwcId);
4095 uint8_t port;
4096 DisplayIdentificationData data;
4097 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4098 result.append("no identification data\n");
4099 continue;
4100 }
4101
4102 if (!isEdid(data)) {
4103 result.append("unknown identification data: ");
4104 for (uint8_t byte : data) {
4105 result.appendFormat("%x ", byte);
4106 }
4107 result.append("\n");
4108 continue;
4109 }
4110
4111 const auto edid = parseEdid(data);
4112 if (!edid) {
4113 result.append("invalid EDID: ");
4114 for (uint8_t byte : data) {
4115 result.appendFormat("%x ", byte);
4116 }
4117 result.append("\n");
4118 continue;
4119 }
4120
4121 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4122 result.append(edid->displayName.data(), edid->displayName.length());
4123 result.append("\"\n");
4124 }
4125 result.append("\n");
4126}
4127
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004128void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4129 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004130 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004131
4132 // TODO: print out if wide-color mode is active or not
4133
4134 for (size_t d = 0; d < mDisplays.size(); d++) {
4135 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4136 int32_t hwcId = displayDevice->getHwcDisplayId();
4137 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4138 continue;
4139 }
4140
4141 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004142 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004143 for (auto&& mode : modes) {
4144 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4145 }
4146
Peiyong Lina52f0292018-03-14 17:26:31 -07004147 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004148 result.appendFormat(" Current color mode: %s (%d)\n",
4149 decodeColorMode(currentMode).c_str(), currentMode);
4150 }
4151 result.append("\n");
4152}
4153
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004154LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004155 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004156 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4157 const State& state = useDrawing ? mDrawingState : mCurrentState;
4158 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004159 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004160 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004161 });
4162
4163 return layersProto;
4164}
4165
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004166LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4167 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004168 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004169
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004170 SizeProto* resolution = layersProto.mutable_resolution();
4171 resolution->set_w(displayDevice->getWidth());
4172 resolution->set_h(displayDevice->getHeight());
4173
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004174 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4175 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4176 layersProto.set_global_transform(
4177 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4178
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004179 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004180 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004181 LayerProto* layerProto = layersProto.add_layers();
4182 layer->writeToProto(layerProto, hwcId);
4183 }
4184 });
4185
4186 return layersProto;
4187}
4188
Mathias Agopian74d211a2013-04-22 16:55:35 +02004189void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4190 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004192 bool colorize = false;
4193 if (index < args.size()
4194 && (args[index] == String16("--color"))) {
4195 colorize = true;
4196 index++;
4197 }
4198
4199 Colorizer colorizer(colorize);
4200
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 // figure out if we're stuck somewhere
4202 const nsecs_t now = systemTime();
4203 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4204 const nsecs_t inTransaction(mDebugInTransaction);
4205 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4206 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4207
4208 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004209 * Dump library configuration.
4210 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211
4212 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004213 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004215 appendSfConfigString(result);
4216 appendUiConfigString(result);
4217 appendGuiConfigString(result);
4218 result.append("\n");
4219
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004220 result.append("\nDisplay identification data:\n");
4221 dumpDisplayIdentificationData(result);
4222
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004223 result.append("\nWide-Color information:\n");
4224 dumpWideColorInfo(result);
4225
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004227 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004229 result.append(SyncFeatures::getInstance().toString());
4230 result.append("\n");
4231
David Sodman105b7dc2017-11-04 20:28:14 -07004232 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004233
Andy McFadden41d67d72014-04-25 16:58:34 -07004234 colorizer.bold(result);
4235 result.append("DispSync configuration: ");
4236 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004237 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4238 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4239 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004240 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004241 result.append("\n");
4242
Dan Stozab90cf072015-03-05 11:05:59 -08004243 // Dump static screen stats
4244 result.append("\n");
4245 dumpStaticScreenStats(result);
4246 result.append("\n");
4247
Dan Stozae77c7662016-05-13 11:37:28 -07004248 dumpBufferingStats(result);
4249
Andy McFadden4803b742012-09-24 19:07:20 -07004250 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 * Dump the visible layer list
4252 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004253 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004254 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004255 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4256 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004258
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004259 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004260 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004261 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004262 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263
4264 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004265 * Dump Display state
4266 */
4267
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004269 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004270 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004271 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4272 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004273 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004274 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004275 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004276
4277 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 * Dump SurfaceFlinger global state
4279 */
4280
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004281 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004282 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004283 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
Mathias Agopian888c8222012-08-04 21:10:38 -07004285 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004286 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004287
David Sodmanbc815282017-11-05 18:57:52 -08004288 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004290 if (hw) {
4291 hw->undefinedRegion.dump(result, "undefinedRegion");
4292 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4293 hw->getOrientation(), hw->isDisplayOn());
4294 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004295 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004296 " last eglSwapBuffers() time: %f us\n"
4297 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004298 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299 " refresh-rate : %f fps\n"
4300 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004301 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004302 " gpu_to_cpu_unsupported : %d\n"
4303 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304 mLastSwapBufferTime/1000.0,
4305 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004306 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004307 1e9 / activeConfig->getVsyncPeriod(),
4308 activeConfig->getDpiX(),
4309 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004310 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004311
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314
Mathias Agopian74d211a2013-04-22 16:55:35 +02004315 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317
4318 /*
4319 * VSYNC state
4320 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004321 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004322 result.append("\n");
4323
4324 /*
4325 * HWC layer minidump
4326 */
4327 for (size_t d = 0; d < mDisplays.size(); d++) {
4328 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4329 int32_t hwcId = displayDevice->getHwcDisplayId();
4330 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4331 continue;
4332 }
4333
4334 result.appendFormat("Display %d HWC layers:\n", hwcId);
4335 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004336 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004337 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004338 });
Dan Stozae22aec72016-08-01 13:20:59 -07004339 result.append("\n");
4340 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341
4342 /*
4343 * Dump HWComposer state
4344 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004345 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004346 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004347 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004348 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004349 result.appendFormat(" h/w composer %s\n",
4350 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004351 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
4353 /*
4354 * Dump gralloc state
4355 */
4356 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4357 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004358
4359 /*
4360 * Dump VrFlinger state if in use.
4361 */
4362 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4363 result.append("VrFlinger state:\n");
4364 result.append(mVrFlinger->Dump().c_str());
4365 result.append("\n");
4366 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367}
4368
Mathias Agopian13127d82013-03-05 17:47:11 -08004369const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004370SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004371 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004372 wp<IBinder> dpy;
4373 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4374 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4375 dpy = mDisplays.keyAt(i);
4376 break;
4377 }
4378 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004379 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004380 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4381 // Just use the primary display so we have something to return
4382 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4383 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004384 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004385}
4386
Keun young Park63f165f2012-08-31 10:53:36 -07004387bool SurfaceFlinger::startDdmConnection()
4388{
4389 void* libddmconnection_dso =
4390 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4391 if (!libddmconnection_dso) {
4392 return false;
4393 }
4394 void (*DdmConnection_start)(const char* name);
4395 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004396 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004397 if (!DdmConnection_start) {
4398 dlclose(libddmconnection_dso);
4399 return false;
4400 }
4401 (*DdmConnection_start)(getServiceName());
4402 return true;
4403}
4404
Chia-I Wu28f320b2018-05-03 11:02:56 -07004405void SurfaceFlinger::updateColorMatrixLocked() {
4406 mat4 colorMatrix;
4407 if (mGlobalSaturationFactor != 1.0f) {
4408 // Rec.709 luma coefficients
4409 float3 luminance{0.213f, 0.715f, 0.072f};
4410 luminance *= 1.0f - mGlobalSaturationFactor;
4411 mat4 saturationMatrix = mat4(
4412 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4413 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4414 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4415 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4416 );
4417 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4418 } else {
4419 colorMatrix = mClientColorMatrix * mDaltonizer();
4420 }
4421
4422 if (mCurrentState.colorMatrix != colorMatrix) {
4423 mCurrentState.colorMatrix = colorMatrix;
4424 mCurrentState.colorMatrixChanged = true;
4425 setTransactionFlags(eTransactionNeeded);
4426 }
4427}
4428
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004429status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 switch (code) {
4431 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004432 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004433 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004434 case CLEAR_ANIMATION_FRAME_STATS:
4435 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004436 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004437 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004438 case ENABLE_VSYNC_INJECTIONS:
4439 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004440 {
4441 // codes that require permission check
4442 IPCThreadState* ipc = IPCThreadState::self();
4443 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004444 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004445 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004446 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004447 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004448 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004449 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004450 break;
4451 }
Robert Carr1db73f62016-12-21 12:58:51 -08004452 /*
4453 * Calling setTransactionState is safe, because you need to have been
4454 * granted a reference to Client* and Handle* to do anything with it.
4455 *
4456 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4457 */
4458 case SET_TRANSACTION_STATE:
4459 case CREATE_SCOPED_CONNECTION:
4460 {
4461 return OK;
4462 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004463 case CAPTURE_SCREEN:
4464 {
4465 // codes that require permission check
4466 IPCThreadState* ipc = IPCThreadState::self();
4467 const int pid = ipc->getCallingPid();
4468 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004469 if ((uid != AID_GRAPHICS) &&
4470 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004471 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004472 return PERMISSION_DENIED;
4473 }
4474 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 }
chaviwa76b2712017-09-20 12:02:26 -07004476 case CAPTURE_LAYERS: {
4477 IPCThreadState* ipc = IPCThreadState::self();
4478 const int pid = ipc->getCallingPid();
4479 const int uid = ipc->getCallingUid();
4480 if ((uid != AID_GRAPHICS) &&
4481 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4482 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4483 return PERMISSION_DENIED;
4484 }
4485 break;
4486 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004488 return OK;
4489}
4490
4491status_t SurfaceFlinger::onTransact(
4492 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4493{
4494 status_t credentialCheck = CheckTransactCodeCredentials(code);
4495 if (credentialCheck != OK) {
4496 return credentialCheck;
4497 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004499 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4500 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004501 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004502 IPCThreadState* ipc = IPCThreadState::self();
4503 const int uid = ipc->getCallingUid();
4504 if (CC_UNLIKELY(uid != AID_SYSTEM
4505 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004506 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004507 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004508 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004509 return PERMISSION_DENIED;
4510 }
4511 int n;
4512 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004513 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004514 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 return NO_ERROR;
4516 case 1002: // SHOW_UPDATES
4517 n = data.readInt32();
4518 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004519 invalidateHwcGeometry();
4520 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004521 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004523 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004524 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004526 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004527 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004528 setTransactionFlags(
4529 eTransactionNeeded|
4530 eDisplayTransactionNeeded|
4531 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004532 return NO_ERROR;
4533 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004534 case 1006:{ // send empty update
4535 signalRefresh();
4536 return NO_ERROR;
4537 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004538 case 1008: // toggle use of hw composer
4539 n = data.readInt32();
4540 mDebugDisableHWC = n ? 1 : 0;
4541 invalidateHwcGeometry();
4542 repaintEverything();
4543 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004544 case 1009: // toggle use of transform hint
4545 n = data.readInt32();
4546 mDebugDisableTransformHint = n ? 1 : 0;
4547 invalidateHwcGeometry();
4548 repaintEverything();
4549 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004551 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004552 reply->writeInt32(0);
4553 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004554 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004555 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 return NO_ERROR;
4557 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004558 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004559 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004560 return NO_ERROR;
4561 }
4562 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004563 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004564 // daltonize
4565 n = data.readInt32();
4566 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004567 case 1:
4568 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4569 break;
4570 case 2:
4571 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4572 break;
4573 case 3:
4574 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4575 break;
4576 default:
4577 mDaltonizer.setType(ColorBlindnessType::None);
4578 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004579 }
4580 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004581 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004582 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004583 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004584 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004585
4586 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004587 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004588 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004589 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004590 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004591 // apply a color matrix
4592 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004593 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004594 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004595 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004596 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004597 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004598 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004599 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004601 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004602 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004603
4604 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4605 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004606 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004607 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4608 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4609 }
4610
Chia-I Wu28f320b2018-05-03 11:02:56 -07004611 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004612 return NO_ERROR;
4613 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004614 // This is an experimental interface
4615 // Needs to be shifted to proper binder interface when we productize
4616 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004617 n = data.readInt32();
4618 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004619 return NO_ERROR;
4620 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004621 case 1017: {
4622 n = data.readInt32();
4623 mForceFullDamage = static_cast<bool>(n);
4624 return NO_ERROR;
4625 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004626 case 1018: { // Modify Choreographer's phase offset
4627 n = data.readInt32();
4628 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4629 return NO_ERROR;
4630 }
4631 case 1019: { // Modify SurfaceFlinger's phase offset
4632 n = data.readInt32();
4633 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4634 return NO_ERROR;
4635 }
Irvel468051e2016-06-13 16:44:44 -07004636 case 1020: { // Layer updates interceptor
4637 n = data.readInt32();
4638 if (n) {
4639 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004640 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004641 }
4642 else{
4643 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004644 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004645 }
4646 return NO_ERROR;
4647 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004648 case 1021: { // Disable HWC virtual displays
4649 n = data.readInt32();
4650 mUseHwcVirtualDisplays = !n;
4651 return NO_ERROR;
4652 }
Romain Guy0147a172017-06-01 13:53:56 -07004653 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004655 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004656
Chia-I Wu28f320b2018-05-03 11:02:56 -07004657 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004658 return NO_ERROR;
4659 }
Romain Guy54f154a2017-10-24 21:40:32 +01004660 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004661 int32_t value = data.readInt32();
4662 if (value > 2) {
4663 return BAD_VALUE;
4664 }
4665 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4666 return BAD_VALUE;
4667 }
Romain Guy54f154a2017-10-24 21:40:32 +01004668
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004669 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004670 invalidateHwcGeometry();
4671 repaintEverything();
4672 return NO_ERROR;
4673 }
4674 case 1024: { // Is wide color gamut rendering/color management supported?
4675 reply->writeBool(hasWideColorDisplay);
4676 return NO_ERROR;
4677 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004678 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004679 n = data.readInt32();
4680 if (n) {
4681 ALOGV("LayerTracing enabled");
4682 mTracing.enable();
4683 doTracing("tracing.enable");
4684 reply->writeInt32(NO_ERROR);
4685 } else {
4686 ALOGV("LayerTracing disabled");
4687 status_t err = mTracing.disable();
4688 reply->writeInt32(err);
4689 }
4690 return NO_ERROR;
4691 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004692 case 1026: { // Get layer tracing status
4693 reply->writeBool(mTracing.isEnabled());
4694 return NO_ERROR;
4695 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004696 // Is a DisplayColorSetting supported?
4697 case 1027: {
4698 int32_t value = data.readInt32();
4699 switch (value) {
4700 case 0:
4701 reply->writeBool(hasWideColorDisplay);
4702 return NO_ERROR;
4703 case 1:
4704 reply->writeBool(true);
4705 return NO_ERROR;
4706 case 2:
4707 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4708 return NO_ERROR;
4709 default:
4710 return BAD_VALUE;
4711 }
4712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004713 }
4714 }
4715 return err;
4716}
4717
Steven Thomas6d8110b2017-08-31 18:24:21 -07004718void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004719 android_atomic_or(1, &mRepaintEverything);
4720 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004721}
4722
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004723// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4724class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004725public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004726 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4727 ~WindowDisconnector() {
4728 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004729 }
4730
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004731private:
4732 ANativeWindow* mWindow;
4733 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004734};
4735
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004736status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4737 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4738 int32_t minLayerZ, int32_t maxLayerZ,
4739 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004740 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004741 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004742
chaviwa76b2712017-09-20 12:02:26 -07004743 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4744
4745 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004746 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4747
chaviwa76b2712017-09-20 12:02:26 -07004748 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4749
4750 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4751 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004752 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004753}
4754
4755status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004756 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004757 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004758 ATRACE_CALL();
4759
4760 class LayerRenderArea : public RenderArea {
4761 public:
Robert Carr578038f2018-03-09 12:25:24 -08004762 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4763 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004764 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004765 mLayer(layer),
4766 mCrop(crop),
4767 mFlinger(flinger),
4768 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004769 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004770 Rect getBounds() const override {
4771 const Layer::State& layerState(mLayer->getDrawingState());
4772 return Rect(layerState.active.w, layerState.active.h);
4773 }
4774 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4775 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4776 bool isSecure() const override { return false; }
4777 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004778 Rect getSourceCrop() const override {
4779 if (mCrop.isEmpty()) {
4780 return getBounds();
4781 } else {
4782 return mCrop;
4783 }
4784 }
4785 bool getWideColorSupport() const override { return false; }
4786 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004787 float getDisplayMaxLuminance() const override {
4788 return DisplayDevice::sDefaultMaxLumiance;
4789 }
Robert Carr578038f2018-03-09 12:25:24 -08004790
4791 class ReparentForDrawing {
4792 public:
4793 const sp<Layer>& oldParent;
4794 const sp<Layer>& newParent;
4795
4796 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4797 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004798 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004799 }
Robert Carr15eae092018-03-23 13:43:53 -07004800 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004801 };
4802
4803 void render(std::function<void()> drawLayers) override {
4804 if (!mChildrenOnly) {
4805 mTransform = mLayer->getTransform().inverse();
4806 drawLayers();
4807 } else {
4808 Rect bounds = getBounds();
4809 screenshotParentLayer =
4810 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4811 bounds.getWidth(), bounds.getHeight(), 0);
4812
4813 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4814 drawLayers();
4815 }
4816 }
chaviwa76b2712017-09-20 12:02:26 -07004817
chaviwa76b2712017-09-20 12:02:26 -07004818 private:
chaviw7206d492017-11-10 16:16:12 -08004819 const sp<Layer> mLayer;
4820 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004821
4822 // In the "childrenOnly" case we reparent the children to a screenshot
4823 // layer which has no properties set and which does not draw.
4824 sp<ContainerLayer> screenshotParentLayer;
4825 Transform mTransform;
4826
4827 SurfaceFlinger* mFlinger;
4828 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004829 };
4830
4831 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4832 auto parent = layerHandle->owner.promote();
4833
chaviw7206d492017-11-10 16:16:12 -08004834 if (parent == nullptr || parent->isPendingRemoval()) {
4835 ALOGE("captureLayers called with a removed parent");
4836 return NAME_NOT_FOUND;
4837 }
4838
Robert Carr578038f2018-03-09 12:25:24 -08004839 const int uid = IPCThreadState::self()->getCallingUid();
4840 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4841 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4842 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4843 return PERMISSION_DENIED;
4844 }
4845
chaviw7206d492017-11-10 16:16:12 -08004846 Rect crop(sourceCrop);
4847 if (sourceCrop.width() <= 0) {
4848 crop.left = 0;
4849 crop.right = parent->getCurrentState().active.w;
4850 }
4851
4852 if (sourceCrop.height() <= 0) {
4853 crop.top = 0;
4854 crop.bottom = parent->getCurrentState().active.h;
4855 }
4856
4857 int32_t reqWidth = crop.width() * frameScale;
4858 int32_t reqHeight = crop.height() * frameScale;
4859
Robert Carr578038f2018-03-09 12:25:24 -08004860 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004861
Robert Carr578038f2018-03-09 12:25:24 -08004862 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004863 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4864 if (!layer->isVisible()) {
4865 return;
Robert Carr578038f2018-03-09 12:25:24 -08004866 } else if (childrenOnly && layer == parent.get()) {
4867 return;
chaviwa76b2712017-09-20 12:02:26 -07004868 }
4869 visitor(layer);
4870 });
4871 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004872 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004873}
4874
4875status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4876 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004877 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004878 bool useIdentityTransform) {
4879 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004880
chaviwa76b2712017-09-20 12:02:26 -07004881 renderArea.updateDimensions();
4882
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004883 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4884 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4885 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4886 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004887
4888 // This mutex protects syncFd and captureResult for communication of the return values from the
4889 // main thread back to this Binder thread
4890 std::mutex captureMutex;
4891 std::condition_variable captureCondition;
4892 std::unique_lock<std::mutex> captureLock(captureMutex);
4893 int syncFd = -1;
4894 std::optional<status_t> captureResult;
4895
Robert Carr03480e22018-01-04 16:02:06 -08004896 const int uid = IPCThreadState::self()->getCallingUid();
4897 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4898
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004899 sp<LambdaMessage> message = new LambdaMessage([&]() {
4900 // If there is a refresh pending, bug out early and tell the binder thread to try again
4901 // after the refresh.
4902 if (mRefreshPending) {
4903 ATRACE_NAME("Skipping screenshot for now");
4904 std::unique_lock<std::mutex> captureLock(captureMutex);
4905 captureResult = std::make_optional<status_t>(EAGAIN);
4906 captureCondition.notify_one();
4907 return;
4908 }
4909
4910 status_t result = NO_ERROR;
4911 int fd = -1;
4912 {
4913 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004914 renderArea.render([&]() {
4915 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4916 useIdentityTransform, forSystem, &fd);
4917 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004918 }
4919
4920 {
4921 std::unique_lock<std::mutex> captureLock(captureMutex);
4922 syncFd = fd;
4923 captureResult = std::make_optional<status_t>(result);
4924 captureCondition.notify_one();
4925 }
4926 });
4927
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004928 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004929 if (result == NO_ERROR) {
4930 captureCondition.wait(captureLock, [&]() { return captureResult; });
4931 while (*captureResult == EAGAIN) {
4932 captureResult.reset();
4933 result = postMessageAsync(message);
4934 if (result != NO_ERROR) {
4935 return result;
4936 }
4937 captureCondition.wait(captureLock, [&]() { return captureResult; });
4938 }
4939 result = *captureResult;
4940 }
4941
4942 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004943 sync_wait(syncFd, -1);
4944 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004945 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004946
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004947 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004948}
4949
chaviwa76b2712017-09-20 12:02:26 -07004950void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4951 TraverseLayersFunction traverseLayers, bool yswap,
4952 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004953 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004954
Lloyd Pique144e1162017-12-20 16:44:52 -08004955 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004956
4957 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004958 const auto raWidth = renderArea.getWidth();
4959 const auto raHeight = renderArea.getHeight();
4960
4961 const auto reqWidth = renderArea.getReqWidth();
4962 const auto reqHeight = renderArea.getReqHeight();
4963 Rect sourceCrop = renderArea.getSourceCrop();
4964
4965 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4966 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004967
Dan Stozac1879002014-05-22 15:59:05 -07004968 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004969 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004970 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004971 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004972 }
4973
4974 // ensure that sourceCrop is inside screen
4975 if (sourceCrop.left < 0) {
4976 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4977 }
chaviwa76b2712017-09-20 12:02:26 -07004978 if (sourceCrop.right > raWidth) {
4979 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004980 }
4981 if (sourceCrop.top < 0) {
4982 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4983 }
chaviwa76b2712017-09-20 12:02:26 -07004984 if (sourceCrop.bottom > raHeight) {
4985 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004986 }
4987
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004988 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004989 if (renderArea.getWideColorSupport()) {
4990 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004991 }
Peiyong Linfb069302018-04-25 14:34:31 -07004992 engine.setOutputDataSpace(outputDataspace);
4993 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004994
Mathias Agopian180f10d2013-04-10 22:55:41 -07004995 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004996 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004997
4998 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004999 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5000 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005001 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005002
chaviw50da5042018-04-09 13:49:37 -07005003 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005004 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005005 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005006
chaviwa76b2712017-09-20 12:02:26 -07005007 traverseLayers([&](Layer* layer) {
5008 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005009 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005010 if (filtering) layer->setFiltering(false);
5011 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005012}
5013
chaviwa76b2712017-09-20 12:02:26 -07005014status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5015 TraverseLayersFunction traverseLayers,
5016 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005017 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005018 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005019 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005020 ATRACE_CALL();
5021
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005022 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005023
5024 traverseLayers([&](Layer* layer) {
5025 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5026 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005027
Robert Carr03480e22018-01-04 16:02:06 -08005028 // We allow the system server to take screenshots of secure layers for
5029 // use in situations like the Screen-rotation animation and place
5030 // the impetus on WindowManager to not persist them.
5031 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005032 ALOGW("FB is protected: PERMISSION_DENIED");
5033 return PERMISSION_DENIED;
5034 }
5035
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005036 // this binds the given EGLImage as a framebuffer for the
5037 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005038 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005039 if (bufferBond.getStatus() != NO_ERROR) {
5040 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005041 return INVALID_OPERATION;
5042 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005043
Dan Stozaabcda352017-06-01 14:37:39 -07005044 // this will in fact render into our dequeued buffer
5045 // via an FBO, which means we didn't have to create
5046 // an EGLSurface and therefore we're not
5047 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005048 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005049
Dan Stozaabcda352017-06-01 14:37:39 -07005050 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005051 getRenderEngine().finish();
5052 *outSyncFd = -1;
5053
chaviwa76b2712017-09-20 12:02:26 -07005054 const auto reqWidth = renderArea.getReqWidth();
5055 const auto reqHeight = renderArea.getReqHeight();
5056
Dan Stozaabcda352017-06-01 14:37:39 -07005057 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5058 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005059 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005060 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005061 } else {
5062 base::unique_fd syncFd = getRenderEngine().flush();
5063 if (syncFd < 0) {
5064 getRenderEngine().finish();
5065 }
5066 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005067 }
5068
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005069 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005070}
5071
Mathias Agopiand5556842013-09-19 17:08:37 -07005072void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005073 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005074 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005075 for (size_t y = 0; y < h; y++) {
5076 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5077 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005078 if (p[x] != 0xFF000000) return;
5079 }
5080 }
chaviwa76b2712017-09-20 12:02:26 -07005081 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005082
Robert Carr2047fae2016-11-28 14:09:09 -08005083 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005084 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005085 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005086 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5087 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5088 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5089 static_cast<float>(state.color.a));
5090 i++;
5091 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005092 }
5093}
5094
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005095// ---------------------------------------------------------------------------
5096
Dan Stoza412903f2017-04-27 13:42:17 -07005097void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5098 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005099}
5100
Dan Stoza412903f2017-04-27 13:42:17 -07005101void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5102 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005103}
5104
chaviwa76b2712017-09-20 12:02:26 -07005105void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5106 int32_t maxLayerZ,
5107 const LayerVector::Visitor& visitor) {
5108 // We loop through the first level of layers without traversing,
5109 // as we need to interpret min/max layer Z in the top level Z space.
5110 for (const auto& layer : mDrawingState.layersSortedByZ) {
5111 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5112 continue;
5113 }
5114 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005115 // relative layers are traversed in Layer::traverseInZOrder
5116 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005117 continue;
5118 }
5119 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005120 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5121 return;
5122 }
chaviwa76b2712017-09-20 12:02:26 -07005123 if (!layer->isVisible()) {
5124 return;
5125 }
5126 visitor(layer);
5127 });
5128 }
5129}
5130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005131}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005132
Chia-I Wu30505fb2018-03-26 16:20:31 -07005133
Mathias Agopian3f844832013-08-07 21:24:32 -07005134#if defined(__gl_h_)
5135#error "don't include gl/gl.h in this file"
5136#endif
5137
5138#if defined(__gl2_h_)
5139#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005140#endif