blob: fe9a1d0ac19692f6dea7ca6d565e0c523205b4e7 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700109using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700110using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
Steven Thomasb02664d2017-07-26 18:48:28 -0700112namespace {
113class ConditionalLock {
114public:
115 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
116 if (lock) {
117 mMutex.lock();
118 }
119 }
120 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
121private:
122 Mutex& mMutex;
123 bool mLocked;
124};
125} // namespace anonymous
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127// ---------------------------------------------------------------------------
128
Mathias Agopian99b49842011-06-27 16:05:52 -0700129const String16 sHardwareTest("android.permission.HARDWARE_TEST");
130const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
131const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
132const String16 sDump("android.permission.DUMP");
133
134// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800135int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
136int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800143// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600144bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700145
Kalle Raitaa099a242017-01-11 11:17:29 -0800146
147std::string getHwcServiceName() {
148 char value[PROPERTY_VALUE_MAX] = {};
149 property_get("debug.sf.hwc_service_name", value, "default");
150 ALOGI("Using HWComposer service: '%s'", value);
151 return std::string(value);
152}
153
154bool useTrebleTestingOverride() {
155 char value[PROPERTY_VALUE_MAX] = {};
156 property_get("debug.sf.treble_testing_override", value, "false");
157 ALOGI("Treble testing override: '%s'", value);
158 return std::string(value) == "true";
159}
160
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800161DisplayColorSetting toDisplayColorSetting(int value) {
162 switch(value) {
163 case 0:
164 return DisplayColorSetting::MANAGED;
165 case 1:
166 return DisplayColorSetting::UNMANAGED;
167 case 2:
168 return DisplayColorSetting::ENHANCED;
169 default:
170 return DisplayColorSetting::MANAGED;
171 }
172}
173
174std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
175 switch(displayColorSetting) {
176 case DisplayColorSetting::MANAGED:
177 return std::string("Natural Mode");
178 case DisplayColorSetting::UNMANAGED:
179 return std::string("Saturated Mode");
180 case DisplayColorSetting::ENHANCED:
181 return std::string("Auto Color Mode");
182 }
183 return std::string("Unknown Display Color Setting");
184}
185
Lloyd Pique09594832018-01-22 17:48:03 -0800186NativeWindowSurface::~NativeWindowSurface() = default;
187
188namespace impl {
189
190class NativeWindowSurface final : public android::NativeWindowSurface {
191public:
192 static std::unique_ptr<android::NativeWindowSurface> create(
193 const sp<IGraphicBufferProducer>& producer) {
194 return std::make_unique<NativeWindowSurface>(producer);
195 }
196
197 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
198 : surface(new Surface(producer, false)) {}
199
200 ~NativeWindowSurface() override = default;
201
202private:
203 sp<ANativeWindow> getNativeWindow() const override { return surface; }
204
205 void preallocateBuffers() override { surface->allocateBuffers(); }
206
207 sp<Surface> surface;
208};
209
210} // namespace impl
211
David Sodmanbc815282017-11-05 18:57:52 -0800212SurfaceFlingerBE::SurfaceFlingerBE()
213 : mHwcServiceName(getHwcServiceName()),
214 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800215 mFrameBuckets(),
216 mTotalTime(0),
217 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800218 mComposerSequenceId(0) {
219}
220
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800221SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700224 mTransactionPending(false),
225 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700226 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700227 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700228 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800230 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800233 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700236 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700237 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700238 mDebugInSwapBuffers(0),
239 mLastSwapBufferTime(0),
240 mDebugInTransaction(0),
241 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700242 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700243 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000244 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700245 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700246 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800247 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700249 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800251 mCreateBufferQueue(&BufferQueue::createBufferQueue),
252 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800253
254SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800256
257 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
258 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
259
260 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
261 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
262
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800263 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
264 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700266 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
267 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
268
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700269 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
271
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800272 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
276 useVrFlinger = getBool< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::useVrFlinger>(false);
278
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
281
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282 hasWideColorDisplay =
283 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
284
David Sodman99974d22017-11-28 12:04:33 -0800285 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287 // debugging stuff...
288 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700289
Mathias Agopianb4b17302013-03-20 18:36:41 -0700290 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700291 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293 property_get("debug.sf.showupdates", value, "0");
294 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700295
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296 property_get("debug.sf.ddms", value, "0");
297 mDebugDDMS = atoi(value);
298 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700299 if (!startDdmConnection()) {
300 // start failed, and DDMS debugging not enabled
301 mDebugDDMS = 0;
302 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700303 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700304 ALOGI_IF(mDebugRegion, "showupdates enabled");
305 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700306
307 property_get("debug.sf.disable_backpressure", value, "0");
308 mPropagateBackpressure = !atoi(value);
309 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700310
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800311 property_get("debug.sf.enable_hwc_vds", value, "0");
312 mUseHwcVirtualDisplays = atoi(value);
313 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800314
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800315 property_get("ro.sf.disable_triple_buffer", value, "1");
316 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800317 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700318
Yiwei Zhang243b3782018-05-15 17:40:04 -0700319 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
321 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
322
Dan Stoza2713c302018-03-28 17:07:36 -0700323 property_get("debug.sf.early_phase_offset_ns", value, "0");
324 const int earlyWakeupOffsetOffsetNs = atoi(value);
325 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
326 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
327 sfVsyncPhaseOffsetNs);
328
Romain Guy11d63f42017-07-20 12:47:14 -0700329 // We should be reading 'persist.sys.sf.color_saturation' here
330 // but since /data may be encrypted, we need to wait until after vold
331 // comes online to attempt to read the property. The property is
332 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800333
334 if (useTrebleTestingOverride()) {
335 // Without the override SurfaceFlinger cannot connect to HIDL
336 // services that are not listed in the manifests. Considered
337 // deriving the setting from the set service name, but it
338 // would be brittle if the name that's not 'default' is used
339 // for production purposes later on.
340 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
341 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342}
343
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800344void SurfaceFlinger::onFirstRef()
345{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800346 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349SurfaceFlinger::~SurfaceFlinger()
350{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351}
352
Dan Stozac7014012014-02-14 15:03:43 -0800353void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800354{
355 // the window manager died on us. prepare its eulogy.
356
Andy McFadden13a082e2012-08-24 10:16:42 -0700357 // restore initial conditions (default device unblank, etc)
358 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800359
360 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700361 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800362}
363
Robert Carr1db73f62016-12-21 12:58:51 -0800364static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700365 status_t err = client->initCheck();
366 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800367 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 }
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return nullptr;
370}
371
372sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
373 return initClient(new Client(this));
374}
375
376sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
377 const sp<IGraphicBufferProducer>& gbp) {
378 if (authenticateSurfaceTexture(gbp) == false) {
379 return nullptr;
380 }
381 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
382 if (layer == nullptr) {
383 return nullptr;
384 }
385
386 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387}
388
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700389sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
390 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700391{
392 class DisplayToken : public BBinder {
393 sp<SurfaceFlinger> flinger;
394 virtual ~DisplayToken() {
395 // no more references, this display must be terminated
396 Mutex::Autolock _l(flinger->mStateLock);
397 flinger->mCurrentState.displays.removeItem(this);
398 flinger->setTransactionFlags(eDisplayTransactionNeeded);
399 }
400 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700401 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402 : flinger(flinger) {
403 }
404 };
405
406 sp<BBinder> token = new DisplayToken(this);
407
408 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700409 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700410 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700411 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800412 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 return token;
414}
415
Jesse Hall6c913be2013-08-08 12:15:49 -0700416void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
417 Mutex::Autolock _l(mStateLock);
418
419 ssize_t idx = mCurrentState.displays.indexOfKey(display);
420 if (idx < 0) {
421 ALOGW("destroyDisplay: invalid display token");
422 return;
423 }
424
425 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
426 if (!info.isVirtualDisplay()) {
427 ALOGE("destroyDisplay called for non-virtual display");
428 return;
429 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800430 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 mCurrentState.displays.removeItemsAt(idx);
432 setTransactionFlags(eDisplayTransactionNeeded);
433}
434
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700436 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800438 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 }
Jesse Hall692c7232012-11-08 15:41:56 -0800440 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441}
442
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443void SurfaceFlinger::bootFinished()
444{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700445 if (mStartPropertySetThread->join() != NO_ERROR) {
446 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800447 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448 const nsecs_t now = systemTime();
449 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000450 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700451
452 // wait patiently for the window manager death
453 const String16 name("window");
454 sp<IBinder> window(defaultServiceManager()->getService(name));
455 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700456 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700457 }
458
Steven Thomas050b2c82017-03-06 11:45:16 -0800459 if (mVrFlinger) {
460 mVrFlinger->OnBootFinished();
461 }
462
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700463 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700464 // formerly we would just kill the process, but we now ask it to exit so it
465 // can choose where to stop the animation.
466 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700467
468 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
469 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
470 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700471
Thierry Strudel2924d012017-08-14 15:19:37 -0700472 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700473 readPersistentProperties();
474 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700475 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800476}
477
Mathias Agopian3f844832013-08-07 21:24:32 -0700478void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700479 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800480 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700481 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700482 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800483 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
484 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700485 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700486 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700487 return true;
488 }
489 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700490 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491}
492
Lloyd Piquee83f9312018-02-01 12:53:17 -0800493class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000496 const char* name) :
497 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
501 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700502 mDispSync(dispSync),
503 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 mVsyncMutex(),
505 mPhaseOffset(phaseOffset),
506 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700507
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509
Lloyd Piquee83f9312018-02-01 12:53:17 -0800510 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000513 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 static_cast<DispSync::Callback*>(this));
515 if (err != NO_ERROR) {
516 ALOGE("error registering vsync callback: %s (%d)",
517 strerror(-err), err);
518 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 } else {
521 status_t err = mDispSync->removeEventListener(
522 static_cast<DispSync::Callback*>(this));
523 if (err != NO_ERROR) {
524 ALOGE("error unregistering vsync callback: %s (%d)",
525 strerror(-err), err);
526 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700527 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700529 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 }
531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 mCallback = callback;
535 }
536
Lloyd Piquee83f9312018-02-01 12:53:17 -0800537 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 Mutex::Autolock lock(mVsyncMutex);
539
540 // Normalize phaseOffset to [0, period)
541 auto period = mDispSync->getPeriod();
542 phaseOffset %= period;
543 if (phaseOffset < 0) {
544 // If we're here, then phaseOffset is in (-period, 0). After this
545 // operation, it will be in (0, period)
546 phaseOffset += period;
547 }
548 mPhaseOffset = phaseOffset;
549
550 // If we're not enabled, we don't need to mess with the listeners
551 if (!mEnabled) {
552 return;
553 }
554
Dan Stoza2713c302018-03-28 17:07:36 -0700555 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
556 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700557 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700558 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 strerror(-err), err);
560 }
561 }
562
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563private:
564 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 callback = mCallback;
569
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700570 if (mTraceVsync) {
571 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700572 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 }
575
Peiyong Lin566a3b42018-01-09 18:22:43 -0800576 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 callback->onVSyncEvent(when);
578 }
579 }
580
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 const char* const mName;
582
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 int mValue;
584
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700585 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700586 const String8 mVsyncOnLabel;
587 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700588
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700590
591 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593
594 Mutex mVsyncMutex; // Protects the following
595 nsecs_t mPhaseOffset;
596 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597};
598
Lloyd Piquee83f9312018-02-01 12:53:17 -0800599class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700600public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 InjectVSyncSource() = default;
602 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700603
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605 std::lock_guard<std::mutex> lock(mCallbackMutex);
606 mCallback = callback;
607 }
608
Lloyd Piquee83f9312018-02-01 12:53:17 -0800609 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700610 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700611 if (mCallback) {
612 mCallback->onVSyncEvent(when);
613 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 }
615
Lloyd Piquee83f9312018-02-01 12:53:17 -0800616 void setVSyncEnabled(bool) override {}
617 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618
619private:
620 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622};
623
Wei Wangf9b05ee2017-07-19 20:59:39 -0700624// Do not call property_set on main thread which will be blocked by init
625// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700627 ALOGI( "SurfaceFlinger's main thread ready to run. "
628 "Initializing graphics H/W...");
629
Thierry Strudel2924d012017-08-14 15:19:37 -0700630 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900631
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800635 mEventThreadSource =
636 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
637 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800638 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
639 [this]() { resyncWithRateLimit(); },
640 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
644 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800645
Lloyd Pique24b0a482018-03-09 18:52:26 -0800646 mSFEventThread =
647 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
648 [this]() { resyncWithRateLimit(); },
649 [this](nsecs_t timestamp) {
650 mInterceptor->saveVSyncEvent(timestamp);
651 },
652 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800653 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700654 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800657 getBE().mRenderEngine =
658 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
659 hasWideColorDisplay
660 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
661 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800662 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700663
664 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
665 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800666 getBE().mHwc.reset(
667 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700668 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
671 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
672 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800673
Lloyd Piquefcd86612017-12-14 17:15:36 -0800674 // make the default display GLContext current so that we can create textures
675 // when creating Layers (which may happens before we render something)
676 getDefaultDisplayDeviceLocked()->makeCurrent();
677
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 if (useVrFlinger) {
679 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700680 // This callback is called from the vr flinger dispatch thread. We
681 // need to call signalTransaction(), which requires holding
682 // mStateLock when we're not on the main thread. Acquiring
683 // mStateLock from the vr flinger dispatch thread might trigger a
684 // deadlock in surface flinger (see b/66916578), so post a message
685 // to be handled on the main thread instead.
686 sp<LambdaMessage> message = new LambdaMessage([=]() {
687 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
688 mVrFlingerRequestsDisplay = requestDisplay;
689 signalTransaction();
690 });
691 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
David Sodman105b7dc2017-11-04 20:28:14 -0700693 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
694 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800695 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (!mVrFlinger) {
697 ALOGE("Failed to start vrflinger");
698 }
699 }
700
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800701 mEventControlThread = std::make_unique<impl::EventControlThread>(
702 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700703
Mathias Agopian92a979a2012-08-02 18:32:23 -0700704 // initialize our drawing state
705 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700706
Andy McFadden13a082e2012-08-24 10:16:42 -0700707 // set initial conditions (e.g. unblank default device)
708 initializeDisplays();
709
David Sodmanbc815282017-11-05 18:57:52 -0800710 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700711
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 // Inform native graphics APIs whether the present timestamp is supported:
713 if (getHwComposer().hasCapability(
714 HWC2::Capability::PresentFenceIsNotReliable)) {
715 mStartPropertySetThread = new StartPropertySetThread(false);
716 } else {
717 mStartPropertySetThread = new StartPropertySetThread(true);
718 }
719
720 if (mStartPropertySetThread->Start() != NO_ERROR) {
721 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800724 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
725 Dataspace::SRGB_LINEAR);
726
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700728}
729
Romain Guy11d63f42017-07-20 12:47:14 -0700730void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 Mutex::Autolock _l(mStateLock);
732
Romain Guy11d63f42017-07-20 12:47:14 -0700733 char value[PROPERTY_VALUE_MAX];
734
735 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800736 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700737 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100739
740 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
742 ALOGV("Display Color Setting is set to %s.",
743 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700744}
745
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Start boot animation service by setting a property mailbox
748 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700749 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700751 if (mStartPropertySetThread->join() != NO_ERROR) {
752 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800753 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754}
755
Mathias Agopian875d8e12013-06-07 15:35:48 -0700756size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800757 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700758}
759
Mathias Agopian875d8e12013-06-07 15:35:48 -0700760size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800761 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700762}
763
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800764// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800765
Jamie Gennis582270d2011-08-17 18:19:00 -0700766bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800768 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800769 return authenticateSurfaceTextureLocked(bufferProducer);
770}
771
772bool SurfaceFlinger::authenticateSurfaceTextureLocked(
773 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800774 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800775 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800776}
777
Brian Anderson6b376712017-04-04 10:51:39 -0700778status_t SurfaceFlinger::getSupportedFrameTimestamps(
779 std::vector<FrameEvent>* outSupported) const {
780 *outSupported = {
781 FrameEvent::REQUESTED_PRESENT,
782 FrameEvent::ACQUIRE,
783 FrameEvent::LATCH,
784 FrameEvent::FIRST_REFRESH_START,
785 FrameEvent::LAST_REFRESH_START,
786 FrameEvent::GPU_COMPOSITION_DONE,
787 FrameEvent::DEQUEUE_READY,
788 FrameEvent::RELEASE,
789 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700790 ConditionalLock _l(mStateLock,
791 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700792 if (!getHwComposer().hasCapability(
793 HWC2::Capability::PresentFenceIsNotReliable)) {
794 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
795 }
796 return NO_ERROR;
797}
798
Dan Stoza7f7da322014-05-02 15:26:25 -0700799status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
800 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800801 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 return BAD_VALUE;
803 }
804
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500805 if (!display.get())
806 return NAME_NOT_FOUND;
807
Jesse Hall692c7232012-11-08 15:41:56 -0800808 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700809 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800810 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700811 type = i;
812 break;
813 }
814 }
815
816 if (type < 0) {
817 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 // TODO: Not sure if display density should handled by SF any longer
821 class Density {
822 static int getDensityFromProperty(char const* propName) {
823 char property[PROPERTY_VALUE_MAX];
824 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 density = atoi(property);
827 }
828 return density;
829 }
830 public:
831 static int getEmuDensity() {
832 return getDensityFromProperty("qemu.sf.lcd_density"); }
833 static int getBuildDensity() {
834 return getDensityFromProperty("ro.sf.lcd_density"); }
835 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Steven Thomas6d8110b2017-08-31 18:24:21 -0700839 ConditionalLock _l(mStateLock,
840 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 DisplayInfo info = DisplayInfo();
843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 float xdpi = hwConfig->getDpiX();
845 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
847 if (type == DisplayDevice::DISPLAY_PRIMARY) {
848 // The density of the device is provided by a build property
849 float density = Density::getBuildDensity() / 160.0f;
850 if (density == 0) {
851 // the build doesn't provide a density -- this is wrong!
852 // use xdpi instead
853 ALOGE("ro.sf.lcd_density must be defined as a build property");
854 density = xdpi / 160.0f;
855 }
856 if (Density::getEmuDensity()) {
857 // if "qemu.sf.lcd_density" is specified, it overrides everything
858 xdpi = ydpi = density = Density::getEmuDensity();
859 density /= 160.0f;
860 }
861 info.density = density;
862
863 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700864 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800865 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 } else {
867 // TODO: where should this value come from?
868 static const int TV_DENSITY = 213;
869 info.density = TV_DENSITY / 160.0f;
870 info.orientation = 0;
871 }
872
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.w = hwConfig->getWidth();
874 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 info.xdpi = xdpi;
876 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900878 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879
Andy McFadden91b2ca82014-06-13 14:04:23 -0700880 // This is how far in advance a buffer must be queued for
881 // presentation at a given time. If you want a buffer to appear
882 // on the screen at time N, you must submit the buffer before
883 // (N - presentationDeadline).
884 //
885 // Normally it's one full refresh period (to give SF a chance to
886 // latch the buffer), but this can be reduced by configuring a
887 // DispSync offset. Any additional delays introduced by the hardware
888 // composer or panel must be accounted for here.
889 //
890 // We add an additional 1ms to allow for processing time and
891 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800893 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894
895 // All non-virtual displays are currently considered secure.
896 info.secure = true;
897
Michael Wright28f24d02016-07-12 13:30:53 -0700898 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 return NO_ERROR;
902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800904status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800906 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
910 // FIXME for now we always return stats for the primary display
911 memset(stats, 0, sizeof(*stats));
912 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
913 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
914 return NO_ERROR;
915}
916
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700917int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800918 if (display == nullptr) {
919 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800920 return BAD_VALUE;
921 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700922
923 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800924 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700925 return device->getActiveConfig();
926 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700927
Dan Stoza24a42e92015-03-09 10:04:11 -0700928 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700929}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700930
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
932 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
933 this);
934 int32_t type = hw->getDisplayType();
935 int currentMode = hw->getActiveConfig();
936
937 if (mode == currentMode) {
938 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
939 return;
940 }
941
942 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
943 ALOGW("Trying to set config for virtual display");
944 return;
945 }
946
947 hw->setActiveConfig(mode);
948 getHwComposer().setActiveConfig(type, mode);
949}
950
951status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
952 class MessageSetActiveConfig: public MessageBase {
953 SurfaceFlinger& mFlinger;
954 sp<IBinder> mDisplay;
955 int mMode;
956 public:
957 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
958 int mode) :
959 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
960 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700961 Vector<DisplayInfo> configs;
962 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700963 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700964 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700966 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700967 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800969 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700971 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
973 ALOGW("Attempt to set active config = %d for virtual display",
974 mMode);
975 } else {
976 mFlinger.setActiveConfigInternal(hw, mMode);
977 }
978 return true;
979 }
980 };
981 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
982 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700983 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700984}
Michael Wright28f24d02016-07-12 13:30:53 -0700985status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700986 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700987 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
988 return BAD_VALUE;
989 }
990
991 if (!display.get()) {
992 return NAME_NOT_FOUND;
993 }
994
995 int32_t type = NAME_NOT_FOUND;
996 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
997 if (display == mBuiltinDisplays[i]) {
998 type = i;
999 break;
1000 }
1001 }
1002
1003 if (type < 0) {
1004 return type;
1005 }
1006
Peiyong Lina52f0292018-03-14 17:26:31 -07001007 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001008 {
1009 ConditionalLock _l(mStateLock,
1010 std::this_thread::get_id() != mMainThreadId);
1011 modes = getHwComposer().getColorModes(type);
1012 }
Michael Wright28f24d02016-07-12 13:30:53 -07001013 outColorModes->clear();
1014 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1015
1016 return NO_ERROR;
1017}
1018
Peiyong Lina52f0292018-03-14 17:26:31 -07001019ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001020 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001021 if (device != nullptr) {
1022 return device->getActiveColorMode();
1023 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001025}
1026
1027void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001028 ColorMode mode, Dataspace dataSpace,
1029 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001030 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001031 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001032 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001033 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001034
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 if (mode == currentMode && dataSpace == currentDataSpace &&
1036 renderIntent == currentRenderIntent) {
1037 return;
1038 }
1039
1040 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1041 ALOGW("Trying to set config for virtual display");
1042 return;
1043 }
1044
1045 hw->setActiveColorMode(mode);
1046 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001047 hw->setActiveRenderIntent(renderIntent);
1048 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1049
1050 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1051 decodeColorMode(mode).c_str(), mode,
1052 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1053 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001054}
1055
1056
1057status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 class MessageSetActiveColorMode: public MessageBase {
1060 SurfaceFlinger& mFlinger;
1061 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001062 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 public:
1064 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001066 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1067 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 mFlinger.getDisplayColorModes(mDisplay, &modes);
1070 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001071 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001072 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1073 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001074 return true;
1075 }
1076 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1077 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001078 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1079 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001080 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001081 ALOGW("Attempt to set active color mode %s %d for virtual display",
1082 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001083 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001084 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1085 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001086 }
1087 return true;
1088 }
1089 };
1090 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1091 postMessageSync(msg);
1092 return NO_ERROR;
1093}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001094
Svetoslavd85084b2014-03-20 10:28:31 -07001095status_t SurfaceFlinger::clearAnimationFrameStats() {
1096 Mutex::Autolock _l(mStateLock);
1097 mAnimFrameTracker.clearStats();
1098 return NO_ERROR;
1099}
1100
1101status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1102 Mutex::Autolock _l(mStateLock);
1103 mAnimFrameTracker.getStats(outStats);
1104 return NO_ERROR;
1105}
1106
Dan Stozac4f471e2016-03-24 09:31:08 -07001107status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1108 HdrCapabilities* outCapabilities) const {
1109 Mutex::Autolock _l(mStateLock);
1110
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001111 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001112 if (displayDevice == nullptr) {
1113 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1114 return BAD_VALUE;
1115 }
1116
Peiyong Linfb069302018-04-25 14:34:31 -07001117 // At this point the DisplayDeivce should already be set up,
1118 // meaning the luminance information is already queried from
1119 // hardware composer and stored properly.
1120 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1121 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1122 capabilities.getDesiredMaxLuminance(),
1123 capabilities.getDesiredMaxAverageLuminance(),
1124 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001125
1126 return NO_ERROR;
1127}
1128
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001130 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1131 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001132
Chia-I Wu90f669f2017-10-05 14:24:41 -07001133 if (mInjectVSyncs == enable) {
1134 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001135 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001136
1137 if (enable) {
1138 ALOGV("VSync Injections enabled");
1139 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001140 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001141 mInjectorEventThread = std::make_unique<
1142 impl::EventThread>(mVSyncInjector.get(),
1143 [this]() { resyncWithRateLimit(); },
1144 impl::EventThread::InterceptVSyncsCallback(),
1145 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001147 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 } else {
1149 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001150 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 }
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 });
1155 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 return NO_ERROR;
1157}
1158
1159status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 Mutex::Autolock _l(mStateLock);
1161
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001162 if (!mInjectVSyncs) {
1163 ALOGE("VSync Injections not enabled");
1164 return BAD_VALUE;
1165 }
1166 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1167 ALOGV("Injecting VSync inside SurfaceFlinger");
1168 mVSyncInjector->onInjectSyncEvent(when);
1169 }
1170 return NO_ERROR;
1171}
1172
Lloyd Pique755e3192018-01-31 16:46:15 -08001173status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1174 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001175 IPCThreadState* ipc = IPCThreadState::self();
1176 const int pid = ipc->getCallingPid();
1177 const int uid = ipc->getCallingUid();
1178 if ((uid != AID_SHELL) &&
1179 !PermissionCache::checkPermission(sDump, pid, uid)) {
1180 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1181 return PERMISSION_DENIED;
1182 }
1183
1184 // Try to acquire a lock for 1s, fail gracefully
1185 const status_t err = mStateLock.timedLock(s2ns(1));
1186 const bool locked = (err == NO_ERROR);
1187 if (!locked) {
1188 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1189 return TIMED_OUT;
1190 }
1191
1192 outLayers->clear();
1193 mCurrentState.traverseInZOrder([&](Layer* layer) {
1194 outLayers->push_back(layer->getLayerDebugInfo());
1195 });
1196
1197 mStateLock.unlock();
1198 return NO_ERROR;
1199}
1200
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001201// ----------------------------------------------------------------------------
1202
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001203sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1204 ISurfaceComposer::VsyncSource vsyncSource) {
1205 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1206 return mSFEventThread->createEventConnection();
1207 } else {
1208 return mEventThread->createEventConnection();
1209 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001210}
1211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001212// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213
1214void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001215 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001219 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001220}
1221
1222void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001223 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001227 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001232 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001237 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001238 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239 if (res == NO_ERROR) {
1240 msg->wait();
1241 }
1242 return res;
1243}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001245void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001246 do {
1247 waitForEvent();
1248 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249}
1250
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251void SurfaceFlinger::enableHardwareVsync() {
1252 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1256 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001258 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259}
1260
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 Mutex::Autolock _l(mHWVsyncLock);
1263
Jesse Hall948fe0c2013-10-14 12:56:09 -07001264 if (makeAvailable) {
1265 mHWVsyncAvailable = true;
1266 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001267 // Hardware vsync is not currently available, so abort the resync
1268 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 return;
1270 }
1271
David Sodman105b7dc2017-11-04 20:28:14 -07001272 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001273 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274
1275 mPrimaryDispSync.reset();
1276 mPrimaryDispSync.setPeriod(period);
1277
1278 if (!mPrimaryHWVsyncEnabled) {
1279 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001280 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1281 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 mPrimaryHWVsyncEnabled = true;
1283 }
1284}
1285
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 Mutex::Autolock _l(mHWVsyncLock);
1288 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1290 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 mPrimaryDispSync.endResync();
1292 mPrimaryHWVsyncEnabled = false;
1293 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001294 if (makeUnavailable) {
1295 mHWVsyncAvailable = false;
1296 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297}
1298
Tim Murray4a4e4a22016-04-19 16:29:23 +00001299void SurfaceFlinger::resyncWithRateLimit() {
1300 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001301
1302 // No explicit locking is needed here since EventThread holds a lock while calling this method
1303 static nsecs_t sLastResyncAttempted = 0;
1304 const nsecs_t now = systemTime();
1305 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001306 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001307 }
Dan Stoza57164302017-05-08 14:03:54 -07001308 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001309}
1310
Steven Thomasb02664d2017-07-26 18:48:28 -07001311void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1312 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001313 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001314 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001315 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 return;
1317 }
1318
1319 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001321 return;
1322 }
1323
Jamie Gennisd1700752013-10-14 12:22:52 -07001324 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 { // Scope for the lock
1327 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001331 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001332
1333 if (needsHwVsync) {
1334 enableHardwareVsync();
1335 } else {
1336 disableHardwareVsync(false);
1337 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001338}
1339
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001340void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001341 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1342 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343}
1344
Lloyd Pique715a2c12017-12-14 17:18:08 -08001345void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1346 HWC2::Connection connection) {
1347 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1348 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349
Lloyd Piqueba04e622017-12-14 17:11:26 -08001350 // Ignore events that do not have the right sequenceId.
1351 if (sequenceId != getBE().mComposerSequenceId) {
1352 return;
1353 }
1354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 // Only lock if we're not on the main thread. This function is normally
1356 // called on a hwbinder thread, but for the primary display it's called on
1357 // the main thread with the state lock already held, so don't attempt to
1358 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001359 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360
Lloyd Pique715a2c12017-12-14 17:18:08 -08001361 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001362
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001363 if (std::this_thread::get_id() == mMainThreadId) {
1364 // Process all pending hot plug events immediately if we are on the main thread.
1365 processDisplayHotplugEventsLocked();
1366 }
1367
Lloyd Piqueba04e622017-12-14 17:11:26 -08001368 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001369}
1370
Steven Thomasb02664d2017-07-26 18:48:28 -07001371void SurfaceFlinger::onRefreshReceived(int sequenceId,
1372 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001374 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001377 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001378}
1379
Dan Stoza9e56aa02015-11-02 13:00:03 -08001380void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001381 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383 getHwComposer().setVsyncEnabled(disp,
1384 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001385}
1386
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001388void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 // Clear the drawing state so that the logic inside of
1391 // handleTransactionLocked will fire. It will determine the delta between
1392 // mCurrentState and mDrawingState and re-apply all changes when we make the
1393 // transition.
1394 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001395 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396 mDisplays.clear();
1397}
1398
Steven Thomas050b2c82017-03-06 11:45:16 -08001399void SurfaceFlinger::updateVrFlinger() {
1400 if (!mVrFlinger)
1401 return;
1402 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001403 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 return;
1405 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406
David Sodman105b7dc2017-11-04 20:28:14 -07001407 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 ALOGE("Vr flinger is only supported for remote hardware composer"
1409 " service connections. Ignoring request to transition to vr"
1410 " flinger.");
1411 mVrFlingerRequestsDisplay = false;
1412 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001413 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001414
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 int currentDisplayPowerMode = getDisplayDeviceLocked(
1418 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001426 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1427 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001428 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
David Sodman105b7dc2017-11-04 20:28:14 -07001430 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1431 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001432
1433 if (vrFlingerRequestsDisplay) {
1434 mVrFlinger->GrantDisplayOwnership();
1435 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001436 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438
1439 mVisibleRegionsDirty = true;
1440 invalidateHwcGeometry();
1441
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1444 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1445 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001448 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 const nsecs_t period = activeConfig->getVsyncPeriod();
1450 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Use phase of 0 since phase is not known.
1453 // Use latency of 0, which will snap to the ideal latency.
1454 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001455
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456 android_atomic_or(1, &mRepaintEverything);
1457 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001458}
1459
Mathias Agopian4fec8732012-06-29 14:12:52 -07001460void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001461 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001462 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001464 bool frameMissed = !mHadClientComposition &&
1465 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001466 (mPreviousPresentFence->getSignalTime() ==
1467 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001468 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001469 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001470 mTimeStats.incrementMissedFrames();
1471 if (mPropagateBackpressure) {
1472 signalLayerUpdate();
1473 break;
1474 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001475 }
Dan Stoza50182882016-07-08 12:02:20 -07001476
Steven Thomas050b2c82017-03-06 11:45:16 -08001477 // Now that we're going to make it to the handleMessageTransaction()
1478 // call below it's safe to call updateVrFlinger(), which will
1479 // potentially trigger a display handoff.
1480 updateVrFlinger();
1481
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482 bool refreshNeeded = handleMessageTransaction();
1483 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001484 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001486 // Signal a refresh if a transaction modified the window state,
1487 // a new buffer was latched, or if HWC has requested a full
1488 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 signalRefresh();
1490 }
1491 break;
1492 }
1493 case MessageQueue::REFRESH: {
1494 handleMessageRefresh();
1495 break;
1496 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001497 }
1498}
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001501 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001503 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512}
1513
1514void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001517 mRefreshPending = false;
1518
Pablo Ceballos40845df2016-01-25 17:41:15 -08001519 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Brian Andersond6927fb2016-07-23 23:37:30 -07001521 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001522 rebuildLayerStacks();
1523 setUpHWComposer();
1524 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001525 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001526 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001527 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001528 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001529
David Sodman105b7dc2017-11-04 20:28:14 -07001530 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001531
1532 mHadClientComposition = false;
1533 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1534 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1535 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001536 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001537 }
Dan Stoza2713c302018-03-28 17:07:36 -07001538 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001539
Dan Stoza9e56aa02015-11-02 13:00:03 -08001540 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543void SurfaceFlinger::doDebugFlashRegions()
1544{
1545 // is debugging enabled
1546 if (CC_LIKELY(!mDebugRegion))
1547 return;
1548
1549 const bool repaintEverything = mRepaintEverything;
1550 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1551 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001552 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 // transform the dirty region into this screen's coordinate space
1554 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1555 if (!dirtyRegion.isEmpty()) {
1556 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001557 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558
1559 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001561 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001562 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1563
Mathias Agopianda27af92012-09-13 18:17:13 -07001564 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 }
1566 }
1567 }
1568
1569 postFramebuffer();
1570
1571 if (mDebugRegion > 1) {
1572 usleep(mDebugRegion * 1000);
1573 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001574
Dan Stoza9e56aa02015-11-02 13:00:03 -08001575 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001576 auto& displayDevice = mDisplays[displayId];
1577 if (!displayDevice->isDisplayOn()) {
1578 continue;
1579 }
1580
David Sodman105b7dc2017-11-04 20:28:14 -07001581 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1582 ALOGE_IF(result != NO_ERROR,
1583 "prepareFrame for display %zd failed:"
1584 " %d (%s)",
1585 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001586 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587}
1588
Adrian Roos1e1a1282017-11-01 19:05:31 +01001589void SurfaceFlinger::doTracing(const char* where) {
1590 ATRACE_CALL();
1591 ATRACE_NAME(where);
1592 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001593 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001594 }
1595}
1596
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001597void SurfaceFlinger::logLayerStats() {
1598 ATRACE_CALL();
1599 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1600 int32_t hwcId = -1;
1601 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1602 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1603 if (displayDevice->isPrimary()) {
1604 hwcId = displayDevice->getHwcDisplayId();
1605 break;
1606 }
1607 }
1608 if (hwcId < 0) {
1609 ALOGE("LayerStats: Hmmm, no primary display?");
1610 return;
1611 }
1612 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1613 }
1614}
1615
Brian Andersond6927fb2016-07-23 23:37:30 -07001616void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 ATRACE_CALL();
1619 ALOGV("preComposition");
1620
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001622 mDrawingState.traverseInZOrder([&](Layer* layer) {
1623 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624 needExtraInvalidate = true;
1625 }
Robert Carr2047fae2016-11-28 14:09:09 -08001626 });
1627
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 if (needExtraInvalidate) {
1629 signalLayerUpdate();
1630 }
1631}
1632
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633void SurfaceFlinger::updateCompositorTiming(
1634 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1635 std::shared_ptr<FenceTime>& presentFenceTime) {
1636 // Update queue of past composite+present times and determine the
1637 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001638 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001640 while (!getBE().mCompositePresentTimes.empty()) {
1641 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 // Cached values should have been updated before calling this method,
1643 // which helps avoid duplicate syscalls.
1644 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1645 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1646 break;
1647 }
1648 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001649 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 }
1651
1652 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001653 while (getBE().mCompositePresentTimes.size() > 16) {
1654 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 }
1656
Brian Andersond0010582017-03-07 13:20:31 -08001657 setCompositorTimingSnapped(
1658 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1659}
1660
1661void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1662 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 // Integer division and modulo round toward 0 not -inf, so we need to
1664 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001665 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1667 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1668
Brian Andersond0010582017-03-07 13:20:31 -08001669 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1670 if (idealLatency <= 0) {
1671 idealLatency = vsyncInterval;
1672 }
1673
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 // Snap the latency to a value that removes scheduling jitter from the
1675 // composition and present times, which often have >1ms of jitter.
1676 // Reducing jitter is important if an app attempts to extrapolate
1677 // something (such as user input) to an accurate diasplay time.
1678 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1679 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001680 nsecs_t bias = vsyncInterval / 2;
1681 int64_t extraVsyncs =
1682 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1683 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1684 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685
David Sodman99974d22017-11-28 12:04:33 -08001686 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1687 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1688 getBE().mCompositorTiming.interval = vsyncInterval;
1689 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690}
1691
1692void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 ATRACE_CALL();
1695 ALOGV("postComposition");
1696
Brian Anderson3546a3f2016-07-14 11:51:14 -07001697 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001698 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001699 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001700 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 }
1702
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001703 // |mStateLock| not needed as we are on the main thread
1704 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705
David Sodman73beded2017-11-15 11:56:06 -08001706 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001708 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709 glCompositionDoneFenceTime =
1710 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001711 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712 } else {
1713 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1714 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715
David Sodman73beded2017-11-15 11:56:06 -08001716 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001717 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001718 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001719 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1722 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1723
1724 // We use the refreshStartTime which might be sampled a little later than
1725 // when we started doing work for this frame, but that should be okay
1726 // since updateCompositorTiming has snapping logic.
1727 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001728 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001729 CompositorTiming compositorTiming;
1730 {
David Sodman99974d22017-11-28 12:04:33 -08001731 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1732 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001733 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001734
Robert Carr2047fae2016-11-28 14:09:09 -08001735 mDrawingState.traverseInZOrder([&](Layer* layer) {
1736 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001737 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001738 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001739 recordBufferingStats(layer->getName().string(),
1740 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001741 }
Robert Carr2047fae2016-11-28 14:09:09 -08001742 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001743
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001744 if (presentFenceTime->isValid()) {
1745 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001746 enableHardwareVsync();
1747 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001748 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001749 }
1750 }
1751
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001752 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001753 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001754 enableHardwareVsync();
1755 }
1756 }
1757
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001758 if (mAnimCompositionPending) {
1759 mAnimCompositionPending = false;
1760
Brian Anderson4e606e32017-03-16 15:34:57 -07001761 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001764 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001765 // The HWC doesn't support present fences, so use the refresh
1766 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001767 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001768 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001769 mAnimFrameTracker.setActualPresentTime(presentTime);
1770 }
1771 mAnimFrameTracker.advanceFrame();
1772 }
Dan Stozab90cf072015-03-05 11:05:59 -08001773
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001774 mTimeStats.incrementTotalFrames();
1775 if (mHadClientComposition) {
1776 mTimeStats.incrementClientCompositionFrames();
1777 }
1778
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001779 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1780 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001781 return;
1782 }
1783
1784 nsecs_t currentTime = systemTime();
1785 if (mHasPoweredOff) {
1786 mHasPoweredOff = false;
1787 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001788 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001790 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1791 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001792 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001793 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001794 }
David Sodman4a36e932017-11-07 14:29:47 -08001795 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001796 }
David Sodman4a36e932017-11-07 14:29:47 -08001797 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001798}
1799
1800void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001801 ATRACE_CALL();
1802 ALOGV("rebuildLayerStacks");
1803
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001805 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001806 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 mVisibleRegionsDirty = false;
1808 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001809
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1811 Region opaqueRegion;
1812 Region dirtyRegion;
1813 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001814 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1816 const Transform& tr(displayDevice->getTransform());
1817 const Rect bounds(displayDevice->getBounds());
1818 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001819 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001822 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001823 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1824 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 Region drawRegion(tr.transform(
1826 layer->visibleNonTransparentRegion));
1827 drawRegion.andSelf(bounds);
1828 if (!drawRegion.isEmpty()) {
1829 layersSortedByZ.add(layer);
1830 } else {
1831 // Clear out the HWC layer if this layer was
1832 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001833 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001834 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001836 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001837 // WM changes displayDevice->layerStack upon sleep/awake.
1838 // Here we make sure we delete the HWC layers even if
1839 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001840 hwcLayerDestroyed = layer->destroyHwcLayer(
1841 displayDevice->getHwcDisplayId());
1842 }
1843
1844 // If a layer is not going to get a release fence because
1845 // it is invisible, but it is also going to release its
1846 // old buffer, add it to the list of layers needing
1847 // fences.
1848 if (hwcLayerDestroyed) {
1849 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1850 mLayersWithQueuedFrames.cend(), layer);
1851 if (found != mLayersWithQueuedFrames.cend()) {
1852 layersNeedingFences.add(layer);
1853 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001854 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 });
1856 }
1857 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001858 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001859 displayDevice->undefinedRegion.set(bounds);
1860 displayDevice->undefinedRegion.subtractSelf(
1861 tr.transform(opaqueRegion));
1862 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001863 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001864 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001866
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001867// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001868// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001869// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001870// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001871// The returned HDR data space is one of
1872// - Dataspace::UNKNOWN
1873// - Dataspace::BT2020_HLG
1874// - Dataspace::BT2020_PQ
1875Dataspace SurfaceFlinger::getBestDataspace(
1876 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1877 Dataspace bestDataSpace = Dataspace::SRGB;
1878 *outHdrDataSpace = Dataspace::UNKNOWN;
1879
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001881 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882 case Dataspace::V0_SCRGB:
1883 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001884 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001885 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001886 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001887 case Dataspace::BT2020_PQ:
1888 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001889 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001890 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001891 case Dataspace::BT2020_HLG:
1892 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001893 // When there's mixed PQ content and HLG content, we set the HDR
1894 // data space to be BT2020_PQ and convert HLG to PQ.
1895 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1896 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001897 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898 break;
1899 default:
1900 break;
1901 }
Romain Guy54f154a2017-10-24 21:40:32 +01001902 }
1903
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001904 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001905}
1906
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001907// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001909 ColorMode* outMode, Dataspace* outDataSpace,
1910 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1912 *outMode = ColorMode::NATIVE;
1913 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001914 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001916 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001917
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001918 Dataspace hdrDataSpace;
1919 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1920
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001921 RenderIntent intent = mDisplayColorSetting == DisplayColorSetting::ENHANCED ?
1922 RenderIntent::ENHANCE : RenderIntent::COLORIMETRIC;
1923
1924 // respect hdrDataSpace only when there is modern HDR support
1925 if (hdrDataSpace != Dataspace::UNKNOWN && displayDevice->hasModernHdrSupport(hdrDataSpace)) {
1926 bestDataSpace = hdrDataSpace;
1927 intent = mDisplayColorSetting == DisplayColorSetting::ENHANCED ?
1928 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001929 }
1930
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001931 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001932}
1933
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 ATRACE_CALL();
1936 ALOGV("setUpHWComposer");
1937
Jesse Hall028dc8f2013-08-20 16:35:32 -07001938 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001939 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001940 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1941 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1942
1943 // If nothing has changed (!dirty), don't recompose.
1944 // If something changed, but we don't currently have any visible layers,
1945 // and didn't when we last did a composition, then skip it this time.
1946 // The second rule does two things:
1947 // - When all layers are removed from a display, we'll emit one black
1948 // frame, then nothing more until we get new layers.
1949 // - When a display is created with a private layer stack, we won't
1950 // emit any black frames until a layer is added to the layer stack.
1951 bool mustRecompose = dirty && !(empty && wasEmpty);
1952
1953 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1954 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1955 mustRecompose ? "doing" : "skipping",
1956 dirty ? "+" : "-",
1957 empty ? "+" : "-",
1958 wasEmpty ? "+" : "-");
1959
Dan Stoza71433162014-02-04 16:22:36 -08001960 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001961
1962 if (mustRecompose) {
1963 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1964 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001965 }
1966
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 // build the h/w work list
1968 if (CC_UNLIKELY(mGeometryInvalid)) {
1969 mGeometryInvalid = false;
1970 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1971 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1972 const auto hwcId = displayDevice->getHwcDisplayId();
1973 if (hwcId >= 0) {
1974 const Vector<sp<Layer>>& currentLayers(
1975 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001976 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001977 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001978 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001979 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001982 }
1983 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001984
Robert Carrae060832016-11-28 10:51:00 -08001985 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001986 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001987 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001988 }
1989 }
1990 }
1991 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 }
Riley Andrews03414a12014-07-01 14:22:59 -07001993
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 // Set the per-frame data
1995 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1996 auto& displayDevice = mDisplays[displayId];
1997 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001998
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 if (hwcId < 0) {
2000 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002001 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002002 if (mDrawingState.colorMatrixChanged) {
2003 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2004 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002005 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2006 "display %zd: %d", displayId, result);
2007 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07002009 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2010 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002011 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002012 layer->forceClientComposition(hwcId);
2013 }
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07002014 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2015 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002016 !displayDevice->hasHLGSupport()) {
2017 layer->forceClientComposition(hwcId);
2018 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002019
chaviwc9232ed2017-11-14 15:31:15 -08002020 if (layer->getForceClientComposition(hwcId)) {
2021 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2022 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2023 continue;
2024 }
2025
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 layer->setPerFrameData(displayDevice);
2027 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002028
2029 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002030 ColorMode colorMode;
2031 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002032 RenderIntent renderIntent;
2033 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2034 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002035 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 }
2037
Chia-I Wu28f320b2018-05-03 11:02:56 -07002038 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002039
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002041 auto& displayDevice = mDisplays[displayId];
2042 if (!displayDevice->isDisplayOn()) {
2043 continue;
2044 }
2045
David Sodman105b7dc2017-11-04 20:28:14 -07002046 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2048 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002049 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002050}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002051
Mathias Agopiancd60f992012-08-16 16:28:27 -07002052void SurfaceFlinger::doComposition() {
2053 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 ALOGV("doComposition");
2055
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002056 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002057 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002058 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002059 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002060 // transform the dirty region into this screen's coordinate space
2061 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002062
2063 // repaint the framebuffer (if needed)
2064 doDisplayComposition(hw, dirtyRegion);
2065
Mathias Agopiancd60f992012-08-16 16:28:27 -07002066 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002067 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002068 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002069 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002070 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002071}
2072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002073void SurfaceFlinger::postFramebuffer()
2074{
Mathias Agopian841cde52012-03-01 15:44:37 -08002075 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002077
Mathias Agopiana44b0412011-10-16 18:46:35 -07002078 const nsecs_t now = systemTime();
2079 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002080
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2082 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002083 if (!displayDevice->isDisplayOn()) {
2084 continue;
2085 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 const auto hwcId = displayDevice->getHwcDisplayId();
2087 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002088 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002089 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002090 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002091 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002093 // The layer buffer from the previous frame (if any) is released
2094 // by HWC only when the release fence from this frame (if any) is
2095 // signaled. Always get the release fence from HWC first.
2096 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002097 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002098
2099 // If the layer was client composited in the previous frame, we
2100 // need to merge with the previous client target acquire fence.
2101 // Since we do not track that, always merge with the current
2102 // client target acquire fence when it is available, even though
2103 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002105 releaseFence = Fence::merge("LayerRelease", releaseFence,
2106 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002107 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002108
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 layer->onLayerDisplayed(releaseFence);
2110 }
Chia-I Wu83806892017-11-16 10:50:20 -08002111
2112 // We've got a list of layers needing fences, that are disjoint with
2113 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2114 // supply them with the present fence.
2115 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002116 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002117 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2118 layer->onLayerDisplayed(presentFence);
2119 }
2120 }
2121
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002123 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002124 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002125 }
2126
Mathias Agopiana44b0412011-10-16 18:46:35 -07002127 mLastSwapBufferTime = systemTime() - now;
2128 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002129
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002130 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002131 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2132 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2133 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2134 logFrameStats();
2135 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137}
2138
Mathias Agopian87baae12012-07-31 12:38:26 -07002139void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140{
Mathias Agopian841cde52012-03-01 15:44:37 -08002141 ATRACE_CALL();
2142
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002143 // here we keep a copy of the drawing state (that is the state that's
2144 // going to be overwritten by handleTransactionLocked()) outside of
2145 // mStateLock so that the side-effects of the State assignment
2146 // don't happen with mStateLock held (which can cause deadlocks).
2147 State drawingState(mDrawingState);
2148
Mathias Agopianca4d3602011-05-19 15:38:14 -07002149 Mutex::Autolock _l(mStateLock);
2150 const nsecs_t now = systemTime();
2151 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002152
Mathias Agopianca4d3602011-05-19 15:38:14 -07002153 // Here we're guaranteed that some transaction flags are set
2154 // so we can call handleTransactionLocked() unconditionally.
2155 // We call getTransactionFlags(), which will also clear the flags,
2156 // with mStateLock held to guarantee that mCurrentState won't change
2157 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002158
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002159 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002160 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002161 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002162
Mathias Agopianca4d3602011-05-19 15:38:14 -07002163 mLastTransactionTime = systemTime() - now;
2164 mDebugInTransaction = 0;
2165 invalidateHwcGeometry();
2166 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002167}
2168
Lloyd Pique715a2c12017-12-14 17:18:08 -08002169DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002170 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002171 // Figure out whether the event is for the primary display or an
2172 // external display by matching the Hwc display id against one for a
2173 // connected display. If we did not find a match, we then check what
2174 // displays are not already connected to determine the type. If we don't
2175 // have a connected primary display, we assume the new display is meant to
2176 // be the primary display, and then if we don't have an external display,
2177 // we assume it is that.
2178 const auto primaryDisplayId =
2179 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2180 const auto externalDisplayId =
2181 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2182 if (primaryDisplayId && primaryDisplayId == display) {
2183 return DisplayDevice::DISPLAY_PRIMARY;
2184 } else if (externalDisplayId && externalDisplayId == display) {
2185 return DisplayDevice::DISPLAY_EXTERNAL;
2186 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2187 return DisplayDevice::DISPLAY_PRIMARY;
2188 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2189 return DisplayDevice::DISPLAY_EXTERNAL;
2190 }
2191
2192 return DisplayDevice::DISPLAY_ID_INVALID;
2193}
2194
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2196 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002197 auto displayType = determineDisplayType(event.display, event.connection);
2198 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2199 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2200 continue;
2201 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002202
2203 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2204 ALOGE("External displays are not supported by the vr hardware composer.");
2205 continue;
2206 }
2207
Lloyd Pique715a2c12017-12-14 17:18:08 -08002208 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002209
2210 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002211 if (!mBuiltinDisplays[displayType].get()) {
2212 ALOGV("Creating built in display %d", displayType);
2213 mBuiltinDisplays[displayType] = new BBinder();
2214 // All non-virtual displays are currently considered secure.
2215 DisplayDeviceState info(displayType, true);
2216 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2217 "Built-in Screen" : "External Screen";
2218 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002219 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002220 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002221 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002222 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002223
Lloyd Piquefcd86612017-12-14 17:15:36 -08002224 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2225 if (idx >= 0) {
2226 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002227 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002228 mCurrentState.displays.removeItemsAt(idx);
2229 }
2230 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002231 }
2232
2233 processDisplayChangesLocked();
2234 }
2235
2236 mPendingHotplugEvents.clear();
2237}
2238
Lloyd Pique09594832018-01-22 17:48:03 -08002239sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2240 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2241 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002242 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002243 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002244
Lloyd Pique09594832018-01-22 17:48:03 -08002245 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002246 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002247 for (ColorMode colorMode : modes) {
2248 switch (colorMode) {
2249 case ColorMode::DISPLAY_P3:
2250 case ColorMode::ADOBE_RGB:
2251 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002252 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002253 break;
2254 default:
2255 break;
2256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257
2258 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2259 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002260 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002261 }
2262 }
2263
Peiyong Lin62665892018-04-16 11:07:44 -07002264 HdrCapabilities hdrCapabilities;
2265 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002266
2267 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2268 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2269
2270 /*
2271 * Create our display's surface
2272 */
2273 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2274 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2275 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2276 renderSurface->setNativeWindow(nativeWindow.get());
2277 const int displayWidth = renderSurface->queryWidth();
2278 const int displayHeight = renderSurface->queryHeight();
2279
2280 // Make sure that composition can never be stalled by a virtual display
2281 // consumer that isn't processing buffers fast enough. We have to do this
2282 // in two places:
2283 // * Here, in case the display is composed entirely by HWC.
2284 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2285 // window's swap interval in eglMakeCurrent, so they'll override the
2286 // interval we set here.
2287 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2288 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2289 }
2290
2291 // virtual displays are always considered enabled
2292 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2293 : HWC_POWER_MODE_OFF;
2294
2295 sp<DisplayDevice> hw =
2296 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2297 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002298 hasWideColorGamut, hdrCapabilities,
2299 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002300 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002301
2302 if (maxFrameBufferAcquiredBuffers >= 3) {
2303 nativeWindowSurface->preallocateBuffers();
2304 }
2305
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002306 if (hw->isPrimary() && hw->hasRenderIntent(RenderIntent::ENHANCE)) {
2307 mBuiltinDisplaySupportsEnhance = true;
2308 }
2309
Lloyd Pique09594832018-01-22 17:48:03 -08002310 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2312 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002313 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002314 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002315 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002316 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2317 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002318 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2319 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2320 }
Lloyd Pique09594832018-01-22 17:48:03 -08002321 hw->setLayerStack(state.layerStack);
2322 hw->setProjection(state.orientation, state.viewport, state.frame);
2323 hw->setDisplayName(state.displayName);
2324
2325 return hw;
2326}
2327
Lloyd Pique347200f2017-12-14 17:00:15 -08002328void SurfaceFlinger::processDisplayChangesLocked() {
2329 // here we take advantage of Vector's copy-on-write semantics to
2330 // improve performance by skipping the transaction entirely when
2331 // know that the lists are identical
2332 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2333 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2334 if (!curr.isIdenticalTo(draw)) {
2335 mVisibleRegionsDirty = true;
2336 const size_t cc = curr.size();
2337 size_t dc = draw.size();
2338
2339 // find the displays that were removed
2340 // (ie: in drawing state but not in current state)
2341 // also handle displays that changed
2342 // (ie: displays that are in both lists)
2343 for (size_t i = 0; i < dc;) {
2344 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2345 if (j < 0) {
2346 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002347 // Call makeCurrent() on the primary display so we can
2348 // be sure that nothing associated with this display
2349 // is current.
2350 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2351 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2352 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2353 if (hw != nullptr) hw->disconnect(getHwComposer());
2354 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2355 mEventThread->onHotplugReceived(draw[i].type, false);
2356 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002357 } else {
2358 // this display is in both lists. see if something changed.
2359 const DisplayDeviceState& state(curr[j]);
2360 const wp<IBinder>& display(curr.keyAt(j));
2361 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2362 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2363 if (state_binder != draw_binder) {
2364 // changing the surface is like destroying and
2365 // recreating the DisplayDevice, so we just remove it
2366 // from the drawing state, so that it get re-added
2367 // below.
2368 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2369 if (hw != nullptr) hw->disconnect(getHwComposer());
2370 mDisplays.removeItem(display);
2371 mDrawingState.displays.removeItemsAt(i);
2372 dc--;
2373 // at this point we must loop to the next item
2374 continue;
2375 }
2376
2377 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2378 if (disp != nullptr) {
2379 if (state.layerStack != draw[i].layerStack) {
2380 disp->setLayerStack(state.layerStack);
2381 }
2382 if ((state.orientation != draw[i].orientation) ||
2383 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2384 disp->setProjection(state.orientation, state.viewport, state.frame);
2385 }
2386 if (state.width != draw[i].width || state.height != draw[i].height) {
2387 disp->setDisplaySize(state.width, state.height);
2388 }
2389 }
2390 }
2391 ++i;
2392 }
2393
2394 // find displays that were added
2395 // (ie: in current state but not in drawing state)
2396 for (size_t i = 0; i < cc; i++) {
2397 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2398 const DisplayDeviceState& state(curr[i]);
2399
2400 sp<DisplaySurface> dispSurface;
2401 sp<IGraphicBufferProducer> producer;
2402 sp<IGraphicBufferProducer> bqProducer;
2403 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002404 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002405
2406 int32_t hwcId = -1;
2407 if (state.isVirtualDisplay()) {
2408 // Virtual displays without a surface are dormant:
2409 // they have external state (layer stack, projection,
2410 // etc.) but no internal state (i.e. a DisplayDevice).
2411 if (state.surface != nullptr) {
2412 // Allow VR composer to use virtual displays.
2413 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2414 int width = 0;
2415 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2416 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2417 int height = 0;
2418 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2419 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2420 int intFormat = 0;
2421 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2422 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002423 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002424
2425 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2426 }
2427
2428 // TODO: Plumb requested format back up to consumer
2429
2430 sp<VirtualDisplaySurface> vds =
2431 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2432 bqProducer, bqConsumer,
2433 state.displayName);
2434
2435 dispSurface = vds;
2436 producer = vds;
2437 }
2438 } else {
2439 ALOGE_IF(state.surface != nullptr,
2440 "adding a supported display, but rendering "
2441 "surface is provided (%p), ignoring it",
2442 state.surface.get());
2443
2444 hwcId = state.type;
2445 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2446 producer = bqProducer;
2447 }
2448
2449 const wp<IBinder>& display(curr.keyAt(i));
2450 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002451 mDisplays.add(display,
2452 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2453 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 if (!state.isVirtualDisplay()) {
2455 mEventThread->onHotplugReceived(state.type, true);
2456 }
2457 }
2458 }
2459 }
2460 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002461
2462 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002463}
2464
Mathias Agopian87baae12012-07-31 12:38:26 -07002465void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002466{
Dan Stoza7dde5992015-05-22 09:51:44 -07002467 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002468 mCurrentState.traverseInZOrder([](Layer* layer) {
2469 layer->notifyAvailableFrames();
2470 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 /*
2473 * Traversal of the children
2474 * (perform the transaction for each of them if needed)
2475 */
2476
Mathias Agopian3559b072012-08-15 13:46:03 -07002477 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002478 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002480 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481
2482 const uint32_t flags = layer->doTransaction(0);
2483 if (flags & Layer::eVisibleRegion)
2484 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002485 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 }
2487
2488 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002489 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 */
2491
Mathias Agopiane57f2922012-08-09 16:29:12 -07002492 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002497 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002498 // The transform hint might have changed for some layers
2499 // (either because a display has changed, or because a layer
2500 // as changed).
2501 //
2502 // Walk through all the layers in currentLayers,
2503 // and update their transform hint.
2504 //
2505 // If a layer is visible only on a single display, then that
2506 // display is used to calculate the hint, otherwise we use the
2507 // default display.
2508 //
2509 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2510 // the hint is set before we acquire a buffer from the surface texture.
2511 //
2512 // NOTE: layer transactions have taken place already, so we use their
2513 // drawing state. However, SurfaceFlinger's own transaction has not
2514 // happened yet, so we must use the current state layer list
2515 // (soon to become the drawing state list).
2516 //
2517 sp<const DisplayDevice> disp;
2518 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002519 bool first = true;
2520 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002521 // NOTE: we rely on the fact that layers are sorted by
2522 // layerStack first (so we don't have to traverse the list
2523 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002525 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002526 currentlayerStack = layerStack;
2527 // figure out if this layerstack is mirrored
2528 // (more than one display) if so, pick the default display,
2529 // if not, pick the only display it's on.
2530 disp.clear();
2531 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2532 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002533 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002534 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002535 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002536 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002537 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002538 break;
2539 }
2540 }
2541 }
2542 }
Chet Haase91d25932013-04-11 15:24:55 -07002543
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002544 if (disp == nullptr) {
2545 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2546 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002547
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002548 // could be null when this layer is using a layerStack
2549 // that is not visible on any display. Also can occur at
2550 // screen off/on times.
2551 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002552 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002553
2554 // disp can be null if there is no display available at all to get
2555 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002556 if (disp != nullptr) {
2557 layer->updateTransformHint(disp);
2558 }
Robert Carr2047fae2016-11-28 14:09:09 -08002559
2560 first = false;
2561 });
Mathias Agopian84300952012-11-21 16:02:13 -08002562 }
2563
2564
Mathias Agopian3559b072012-08-15 13:46:03 -07002565 /*
2566 * Perform our own transaction if needed
2567 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002568
2569 if (mLayersAdded) {
2570 mLayersAdded = false;
2571 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002572 mVisibleRegionsDirty = true;
2573 }
2574
2575 // some layers might have been removed, so
2576 // we need to update the regions they're exposing.
2577 if (mLayersRemoved) {
2578 mLayersRemoved = false;
2579 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002580 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002581 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 // this layer is not visible anymore
2583 // TODO: we could traverse the tree from front to back and
2584 // compute the actual visible region
2585 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586 Region visibleReg;
2587 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002588 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002589 }
Robert Carr2047fae2016-11-28 14:09:09 -08002590 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 }
2592
2593 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002594
2595 updateCursorAsync();
2596}
2597
2598void SurfaceFlinger::updateCursorAsync()
2599{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002600 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2601 auto& displayDevice = mDisplays[displayId];
2602 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002603 continue;
2604 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605
2606 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2607 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002608 }
2609 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002610}
2611
2612void SurfaceFlinger::commitTransaction()
2613{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002614 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002615 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002616 for (const auto& l : mLayersPendingRemoval) {
2617 recordBufferingStats(l->getName().string(),
2618 l->getOccupancyHistory(true));
2619 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002620 }
2621 mLayersPendingRemoval.clear();
2622 }
2623
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002624 // If this transaction is part of a window animation then the next frame
2625 // we composite should be considered an animation as well.
2626 mAnimCompositionPending = mAnimTransactionPending;
2627
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002629 // clear the "changed" flags in current state
2630 mCurrentState.colorMatrixChanged = false;
2631
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 mDrawingState.traverseInZOrder([](Layer* layer) {
2633 layer->commitChildList();
2634 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002635 mTransactionPending = false;
2636 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638}
2639
Chia-I Wuab0c3192017-08-01 11:29:00 -07002640void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002641 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642{
Mathias Agopian841cde52012-03-01 15:44:37 -08002643 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 Region aboveOpaqueLayers;
2647 Region aboveCoveredLayers;
2648 Region dirty;
2649
Mathias Agopian87baae12012-07-31 12:38:26 -07002650 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
Robert Carr2047fae2016-11-28 14:09:09 -08002652 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002654 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655
Jesse Hall01e29052013-02-19 16:13:35 -08002656 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002657 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002658 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002659
Mathias Agopianab028732010-03-16 16:41:46 -07002660 /*
2661 * opaqueRegion: area of a surface that is fully opaque.
2662 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002664
2665 /*
2666 * visibleRegion: area of a surface that is visible on screen
2667 * and not fully transparent. This is essentially the layer's
2668 * footprint minus the opaque regions above it.
2669 * Areas covered by a translucent surface are considered visible.
2670 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002672
2673 /*
2674 * coveredRegion: area of a surface that is covered by all
2675 * visible regions above it (which includes the translucent areas).
2676 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002678
Jesse Halla8026d22012-09-25 13:25:04 -07002679 /*
2680 * transparentRegion: area of a surface that is hinted to be completely
2681 * transparent. This is only used to tell when the layer has no visible
2682 * non-transparent regions and can be removed from the layer list. It
2683 * does not affect the visibleRegion of this layer or any layers
2684 * beneath it. The hint may not be correct if apps don't respect the
2685 * SurfaceView restrictions (which, sadly, some don't).
2686 */
2687 Region transparentRegion;
2688
Mathias Agopianab028732010-03-16 16:41:46 -07002689
2690 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002691 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002692 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002696 if (!visibleRegion.isEmpty()) {
2697 // Remove the transparent area from the visible region
2698 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002699 if (tr.preserveRects()) {
2700 // transform the transparent region
2701 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002703 // transformation too complex, can't do the
2704 // transparent region optimization.
2705 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 }
Mathias Agopianab028732010-03-16 16:41:46 -07002707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708
Mathias Agopianab028732010-03-16 16:41:46 -07002709 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002711 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002712 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2713 // the opaque region is the layer's footprint
2714 opaqueRegion = visibleRegion;
2715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 }
2717 }
2718
Robert Carre5f4f692018-01-12 13:12:28 -08002719 if (visibleRegion.isEmpty()) {
2720 layer->clearVisibilityRegions();
2721 return;
2722 }
2723
Mathias Agopianab028732010-03-16 16:41:46 -07002724 // Clip the covered region to the visible region
2725 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2726
2727 // Update aboveCoveredLayers for next (lower) layer
2728 aboveCoveredLayers.orSelf(visibleRegion);
2729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 // subtract the opaque region covered by the layers above us
2731 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732
2733 // compute this layer's dirty region
2734 if (layer->contentDirty) {
2735 // we need to invalidate the whole region
2736 dirty = visibleRegion;
2737 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 layer->contentDirty = false;
2740 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002741 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002742 * the exposed region consists of two components:
2743 * 1) what's VISIBLE now and was COVERED before
2744 * 2) what's EXPOSED now less what was EXPOSED before
2745 *
2746 * note that (1) is conservative, we start with the whole
2747 * visible region but only keep what used to be covered by
2748 * something -- which mean it may have been exposed.
2749 *
2750 * (2) handles areas that were not covered by anything but got
2751 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002752 */
Mathias Agopianab028732010-03-16 16:41:46 -07002753 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002754 const Region oldVisibleRegion = layer->visibleRegion;
2755 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002756 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2757 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 }
2759 dirty.subtractSelf(aboveOpaqueLayers);
2760
2761 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002762 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763
Mathias Agopianab028732010-03-16 16:41:46 -07002764 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002766
Jesse Halla8026d22012-09-25 13:25:04 -07002767 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 layer->setVisibleRegion(visibleRegion);
2769 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002770 layer->setVisibleNonTransparentRegion(
2771 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002772 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Mathias Agopian87baae12012-07-31 12:38:26 -07002774 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775}
2776
Chia-I Wuab0c3192017-08-01 11:29:00 -07002777void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002778 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002779 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002780 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002781 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002782 }
2783 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002784}
2785
Dan Stoza6b9454d2014-11-07 16:00:59 -08002786bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002788 ALOGV("handlePageFlip");
2789
Brian Andersond6927fb2016-07-23 23:37:30 -07002790 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002793 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002794 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002795
2796 // Store the set of layers that need updates. This set must not change as
2797 // buffers are being latched, as this could result in a deadlock.
2798 // Example: Two producers share the same command stream and:
2799 // 1.) Layer 0 is latched
2800 // 2.) Layer 0 gets a new frame
2801 // 2.) Layer 1 gets a new frame
2802 // 3.) Layer 1 is latched.
2803 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2804 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002805 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002806 if (layer->hasQueuedFrame()) {
2807 frameQueued = true;
2808 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002809 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002810 } else {
2811 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002812 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002813 } else {
2814 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002815 }
Robert Carr2047fae2016-11-28 14:09:09 -08002816 });
2817
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002819 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002820 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002821 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002822 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002823 newDataLatched = true;
2824 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002826
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002827 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002828
2829 // If we will need to wake up at some time in the future to deal with a
2830 // queued frame that shouldn't be displayed during this vsync period, wake
2831 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002832 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 signalLayerUpdate();
2834 }
2835
2836 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002837 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838}
2839
Mathias Agopianad456f92011-01-13 17:53:01 -08002840void SurfaceFlinger::invalidateHwcGeometry()
2841{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002843}
2844
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002845
Fabien Sanglard830b8472016-11-30 16:35:58 -08002846void SurfaceFlinger::doDisplayComposition(
2847 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002848 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849{
Dan Stoza71433162014-02-04 16:22:36 -08002850 // We only need to actually compose the display if:
2851 // 1) It is being handled by hardware composer, which may need this to
2852 // keep its virtual display state machine in sync, or
2853 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002854 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002855 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002857 return;
2858 }
2859
Dan Stoza9e56aa02015-11-02 13:00:03 -08002860 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002861 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002862
2863 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002864 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Chia-I Wub02087d2017-11-09 10:19:54 -08002867bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002868{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002870
Chia-I Wub02087d2017-11-09 10:19:54 -08002871 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002872 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002873 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002874 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002875 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002876
Chia-I Wu8e50e692018-05-04 10:12:37 -07002877 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002878 bool needsLegacyColorMatrix = false;
2879 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002880
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 if (hasClientComposition) {
2882 ALOGV("hasClientComposition");
2883
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002884 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002885 if (displayDevice->hasWideColorGamut()) {
2886 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002887 }
2888 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002889 getBE().mRenderEngine->setDisplayMaxLuminance(
2890 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002891
Chia-I Wu8e50e692018-05-04 10:12:37 -07002892 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2893 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2894 HWC2::Capability::SkipClientColorTransform);
2895
2896 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2897 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002898 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002899 }
2900
Chia-I Wubbb44462018-05-21 15:33:27 -07002901 needsLegacyColorMatrix =
2902 (displayDevice->getActiveRenderIntent() == RenderIntent::ENHANCE &&
2903 outputDataspace != Dataspace::UNKNOWN &&
2904 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002905
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002907 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002909 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002910
2911 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002912 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002913 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2914 }
2915 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002916 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002917
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002918 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002919 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002920 // when using overlays, we assume a fully transparent framebuffer
2921 // NOTE: we could reduce how much we need to clear, for instance
2922 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002923 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002925 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002926 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002927 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002928 // we're left with the letterbox region
2929 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002931
2932 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002934
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002936 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002940 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002941
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002943 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002944 // scissor on the main display. It should never be needed
2945 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 const Rect& bounds(displayDevice->getBounds());
2947 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002948 if (scissor != bounds) {
2949 // scissor doesn't match the screen's dimensions, so we
2950 // need to clear everything outside of it and enable
2951 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002952
Mathias Agopianf45c5102012-10-24 16:29:17 -07002953 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002955 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002956 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957 }
2958 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002960
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 /*
2962 * and then, render the layers targeted at the framebuffer
2963 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002964
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 ALOGV("Rendering client layers");
2966 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 bool firstLayer = true;
2968 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2969 const Region clip(bounds.intersect(
2970 displayTransform.transform(layer->visibleRegion)));
2971 ALOGV("Layer: %s", layer->getName().string());
2972 ALOGV(" Composition type: %s",
2973 to_string(layer->getCompositionType(hwcId)).c_str());
2974 if (!clip.isEmpty()) {
2975 switch (layer->getCompositionType(hwcId)) {
2976 case HWC2::Composition::Cursor:
2977 case HWC2::Composition::Device:
2978 case HWC2::Composition::Sideband:
2979 case HWC2::Composition::SolidColor: {
2980 const Layer::State& state(layer->getDrawingState());
2981 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2982 layer->isOpaque(state) && (state.color.a == 1.0f)
2983 && hasClientComposition) {
2984 // never clear the very first layer since we're
2985 // guaranteed the FB is already cleared
2986 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002987 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002988 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002989 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002990 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002992 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2993 if (!legacyColorMatrixApplied) {
2994 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2995 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002996 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002997 } else if (legacyColorMatrixApplied) {
2998 getRenderEngine().setSaturationMatrix(mat4());
2999 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003000 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003001
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003002 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003003 break;
3004 }
3005 default:
3006 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003007 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003008 } else {
3009 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003010 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003011 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003012 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003013
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003014 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003015 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003016 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003017 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3018 getRenderEngine().setSaturationMatrix(mat4());
3019 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003020
Mathias Agopianf45c5102012-10-24 16:29:17 -07003021 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003022 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003023 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024}
3025
Fabien Sanglard830b8472016-11-30 16:35:58 -08003026void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3027 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003028 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003029 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030}
3031
Dan Stoza7d89d062015-04-30 13:29:25 -07003032status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003033 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003034 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 const sp<Layer>& lbc,
3036 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003037{
Dan Stoza7d89d062015-04-30 13:29:25 -07003038 // add this layer to the current state list
3039 {
3040 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003041 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003042 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3043 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003044 return NO_MEMORY;
3045 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003046 if (parent == nullptr) {
3047 mCurrentState.layersSortedByZ.add(lbc);
3048 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003049 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003050 ALOGE("addClientLayer called with a removed parent");
3051 return NAME_NOT_FOUND;
3052 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003053 parent->addChild(lbc);
3054 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003055
Yiwei Zhang243b3782018-05-15 17:40:04 -07003056 if (gbc != nullptr) {
3057 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3058 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3059 mMaxGraphicBufferProducerListSize,
3060 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3061 mGraphicBufferProducerList.size(),
3062 mMaxGraphicBufferProducerListSize, mNumLayers);
3063 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 mLayersAdded = true;
3065 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003066 }
3067
Mathias Agopian96f08192010-06-02 23:28:45 -07003068 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003069 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003070
Dan Stoza7d89d062015-04-30 13:29:25 -07003071 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003072}
3073
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003074status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003075 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003076 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3077}
Robert Carr7f9b8992017-03-10 11:08:39 -08003078
chaviwca27f252018-02-06 16:46:39 -08003079status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3080 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003081 if (layer->isPendingRemoval()) {
3082 return NO_ERROR;
3083 }
3084
Robert Carr1f0a16a2016-10-24 16:27:39 -07003085 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003086 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003087 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003088 if (topLevelOnly) {
3089 return NO_ERROR;
3090 }
3091
Chia-I Wu98f1c102017-05-30 14:54:08 -07003092 sp<Layer> ancestor = p;
3093 while (ancestor->getParent() != nullptr) {
3094 ancestor = ancestor->getParent();
3095 }
3096 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3097 ALOGE("removeLayer called with a layer whose parent has been removed");
3098 return NAME_NOT_FOUND;
3099 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003100
3101 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003102 } else {
3103 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003104 }
3105
Robert Carr136e2f62017-02-08 17:54:29 -08003106 // As a matter of normal operation, the LayerCleaner will produce a second
3107 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3108 // so we will succeed in promoting it, but it's already been removed
3109 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3110 // otherwise something has gone wrong and we are leaking the layer.
3111 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3113 layer->getName().string(),
3114 (p != nullptr) ? p->getName().string() : "no-parent");
3115 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003116 } else if (index < 0) {
3117 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003118 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003119
Chia-I Wuc6657022017-08-15 11:18:17 -07003120 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 mLayersPendingRemoval.add(layer);
3122 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003123 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 setTransactionFlags(eTransactionNeeded);
3125 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126}
3127
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003128uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003129 return android_atomic_release_load(&mTransactionFlags);
3130}
3131
Mathias Agopian3f844832013-08-07 21:24:32 -07003132uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3134}
3135
Mathias Agopian3f844832013-08-07 21:24:32 -07003136uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003137 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3138}
3139
3140uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3141 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003143 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003145 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 }
3147 return old;
3148}
3149
chaviwca27f252018-02-06 16:46:39 -08003150bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3151 for (const ComposerState& state : states) {
3152 // Here we need to check that the interface we're given is indeed
3153 // one of our own. A malicious client could give us a nullptr
3154 // IInterface, or one of its own or even one of our own but a
3155 // different type. All these situations would cause us to crash.
3156 if (state.client == nullptr) {
3157 return true;
3158 }
3159
3160 sp<IBinder> binder = IInterface::asBinder(state.client);
3161 if (binder == nullptr) {
3162 return true;
3163 }
3164
3165 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3166 return true;
3167 }
3168 }
3169 return false;
3170}
3171
Mathias Agopian8b33f032012-07-24 20:43:54 -07003172void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003173 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003174 const Vector<DisplayState>& displays,
3175 uint32_t flags)
3176{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003177 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003178 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003179 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003180
chaviwca27f252018-02-06 16:46:39 -08003181 if (containsAnyInvalidClientState(states)) {
3182 return;
3183 }
3184
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003185 if (flags & eAnimation) {
3186 // For window updates that are part of an animation we must wait for
3187 // previous animation "frames" to be handled.
3188 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003189 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003190 if (CC_UNLIKELY(err != NO_ERROR)) {
3191 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003192 // caller after a few seconds.
3193 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3194 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003195 mAnimTransactionPending = false;
3196 break;
3197 }
3198 }
3199 }
3200
chaviwca27f252018-02-06 16:46:39 -08003201 for (const DisplayState& display : displays) {
3202 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003203 }
3204
chaviwca27f252018-02-06 16:46:39 -08003205 for (const ComposerState& state : states) {
3206 transactionFlags |= setClientStateLocked(state);
3207 }
3208
3209 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3210 // as destroyed should only occur after setting all other states. This is to allow for a
3211 // child re-parent to happen before marking its original parent as destroyed (which would
3212 // then mark the child as destroyed).
3213 for (const ComposerState& state : states) {
3214 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003215 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003216
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003217 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3218 // anyway. This can be used as a flush mechanism for previous async transactions.
3219 // Empty animation transaction can be used to simulate back-pressure, so also force a
3220 // transaction for empty animation transactions.
3221 if (transactionFlags == 0 &&
3222 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003223 transactionFlags = eTransactionNeeded;
3224 }
3225
Mathias Agopian386aa982011-11-07 21:58:03 -08003226 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003227 if (mInterceptor->isEnabled()) {
3228 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003229 }
Irvel468051e2016-06-13 16:44:44 -07003230
Mathias Agopian386aa982011-11-07 21:58:03 -08003231 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003232 const auto start = (flags & eEarlyWakeup)
3233 ? VSyncModulator::TransactionStart::EARLY
3234 : VSyncModulator::TransactionStart::NORMAL;
3235 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003236
3237 // if this is a synchronous transaction, wait for it to take effect
3238 // before returning.
3239 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003240 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003241 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003242 if (flags & eAnimation) {
3243 mAnimTransactionPending = true;
3244 }
3245 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003246 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3247 if (CC_UNLIKELY(err != NO_ERROR)) {
3248 // just in case something goes wrong in SF, return to the
3249 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003250 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3251 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003252 break;
3253 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003254 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255 }
3256}
3257
Mathias Agopiane57f2922012-08-09 16:29:12 -07003258uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3259{
Jesse Hall9a143922012-10-04 16:29:19 -07003260 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3261 if (dpyIdx < 0)
3262 return 0;
3263
Mathias Agopiane57f2922012-08-09 16:29:12 -07003264 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003265 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003266 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003267 const uint32_t what = s.what;
3268 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003269 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003270 disp.surface = s.surface;
3271 flags |= eDisplayTransactionNeeded;
3272 }
3273 }
3274 if (what & DisplayState::eLayerStackChanged) {
3275 if (disp.layerStack != s.layerStack) {
3276 disp.layerStack = s.layerStack;
3277 flags |= eDisplayTransactionNeeded;
3278 }
3279 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003280 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003281 if (disp.orientation != s.orientation) {
3282 disp.orientation = s.orientation;
3283 flags |= eDisplayTransactionNeeded;
3284 }
3285 if (disp.frame != s.frame) {
3286 disp.frame = s.frame;
3287 flags |= eDisplayTransactionNeeded;
3288 }
3289 if (disp.viewport != s.viewport) {
3290 disp.viewport = s.viewport;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 }
Michael Lentine47e45402014-07-18 15:34:25 -07003294 if (what & DisplayState::eDisplaySizeChanged) {
3295 if (disp.width != s.width) {
3296 disp.width = s.width;
3297 flags |= eDisplayTransactionNeeded;
3298 }
3299 if (disp.height != s.height) {
3300 disp.height = s.height;
3301 flags |= eDisplayTransactionNeeded;
3302 }
3303 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003304 }
3305 return flags;
3306}
3307
chaviwca27f252018-02-06 16:46:39 -08003308uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3309 const layer_state_t& s = composerState.state;
3310 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3311
Mathias Agopian13127d82013-03-05 17:47:11 -08003312 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003313 if (layer == nullptr) {
3314 return 0;
3315 }
3316
3317 if (layer->isPendingRemoval()) {
3318 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3319 return 0;
3320 }
3321
3322 uint32_t flags = 0;
3323
3324 const uint32_t what = s.what;
3325 bool geometryAppliesWithResize =
3326 what & layer_state_t::eGeometryAppliesWithResize;
3327 if (what & layer_state_t::ePositionChanged) {
3328 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3329 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003330 }
chaviw8b3871a2017-11-01 17:41:01 -07003331 }
3332 if (what & layer_state_t::eLayerChanged) {
3333 // NOTE: index needs to be calculated before we update the state
3334 const auto& p = layer->getParent();
3335 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003336 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003337 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003338 mCurrentState.layersSortedByZ.removeAt(idx);
3339 mCurrentState.layersSortedByZ.add(layer);
3340 // we need traversal (state changed)
3341 // AND transaction (list changed)
3342 flags |= eTransactionNeeded|eTraversalNeeded;
3343 }
chaviw8b3871a2017-11-01 17:41:01 -07003344 } else {
3345 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003346 flags |= eTransactionNeeded|eTraversalNeeded;
3347 }
3348 }
chaviw8b3871a2017-11-01 17:41:01 -07003349 }
3350 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003351 // NOTE: index needs to be calculated before we update the state
3352 const auto& p = layer->getParent();
3353 if (p == nullptr) {
3354 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3355 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3356 mCurrentState.layersSortedByZ.removeAt(idx);
3357 mCurrentState.layersSortedByZ.add(layer);
3358 // we need traversal (state changed)
3359 // AND transaction (list changed)
3360 flags |= eTransactionNeeded|eTraversalNeeded;
3361 }
3362 } else {
3363 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3364 flags |= eTransactionNeeded|eTraversalNeeded;
3365 }
chaviw8b3871a2017-11-01 17:41:01 -07003366 }
3367 }
3368 if (what & layer_state_t::eSizeChanged) {
3369 if (layer->setSize(s.w, s.h)) {
3370 flags |= eTraversalNeeded;
3371 }
3372 }
3373 if (what & layer_state_t::eAlphaChanged) {
3374 if (layer->setAlpha(s.alpha))
3375 flags |= eTraversalNeeded;
3376 }
3377 if (what & layer_state_t::eColorChanged) {
3378 if (layer->setColor(s.color))
3379 flags |= eTraversalNeeded;
3380 }
3381 if (what & layer_state_t::eMatrixChanged) {
3382 if (layer->setMatrix(s.matrix))
3383 flags |= eTraversalNeeded;
3384 }
3385 if (what & layer_state_t::eTransparentRegionChanged) {
3386 if (layer->setTransparentRegionHint(s.transparentRegion))
3387 flags |= eTraversalNeeded;
3388 }
3389 if (what & layer_state_t::eFlagsChanged) {
3390 if (layer->setFlags(s.flags, s.mask))
3391 flags |= eTraversalNeeded;
3392 }
3393 if (what & layer_state_t::eCropChanged) {
3394 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3395 flags |= eTraversalNeeded;
3396 }
3397 if (what & layer_state_t::eFinalCropChanged) {
3398 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3399 flags |= eTraversalNeeded;
3400 }
3401 if (what & layer_state_t::eLayerStackChanged) {
3402 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3403 // We only allow setting layer stacks for top level layers,
3404 // everything else inherits layer stack from its parent.
3405 if (layer->hasParent()) {
3406 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3407 layer->getName().string());
3408 } else if (idx < 0) {
3409 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3410 "that also does not appear in the top level layer list. Something"
3411 " has gone wrong.", layer->getName().string());
3412 } else if (layer->setLayerStack(s.layerStack)) {
3413 mCurrentState.layersSortedByZ.removeAt(idx);
3414 mCurrentState.layersSortedByZ.add(layer);
3415 // we need traversal (state changed)
3416 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003417 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003418 }
3419 }
3420 if (what & layer_state_t::eDeferTransaction) {
3421 if (s.barrierHandle != nullptr) {
3422 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3423 } else if (s.barrierGbp != nullptr) {
3424 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3425 if (authenticateSurfaceTextureLocked(gbp)) {
3426 const auto& otherLayer =
3427 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3428 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3429 } else {
3430 ALOGE("Attempt to defer transaction to to an"
3431 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003432 }
3433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 // We don't trigger a traversal here because if no other state is
3435 // changed, we don't want this to cause any more work
3436 }
3437 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003438 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003439 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003440 if (!hadParent) {
3441 mCurrentState.layersSortedByZ.remove(layer);
3442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 }
3446 if (what & layer_state_t::eReparentChildren) {
3447 if (layer->reparentChildren(s.reparentHandle)) {
3448 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003449 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003450 }
chaviw8b3871a2017-11-01 17:41:01 -07003451 if (what & layer_state_t::eDetachChildren) {
3452 layer->detachChildren();
3453 }
3454 if (what & layer_state_t::eOverrideScalingModeChanged) {
3455 layer->setOverrideScalingMode(s.overrideScalingMode);
3456 // We don't trigger a traversal here because if no other state is
3457 // changed, we don't want this to cause any more work
3458 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003459 return flags;
3460}
3461
chaviwca27f252018-02-06 16:46:39 -08003462void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3463 const layer_state_t& state = composerState.state;
3464 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3465
3466 sp<Layer> layer(client->getLayerUser(state.surface));
3467 if (layer == nullptr) {
3468 return;
3469 }
3470
3471 if (layer->isPendingRemoval()) {
3472 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3473 return;
3474 }
3475
3476 if (state.what & layer_state_t::eDestroySurface) {
3477 removeLayerLocked(mStateLock, layer);
3478 }
3479}
3480
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003481status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003482 const String8& name,
3483 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003484 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003485 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003486 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003487{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003488 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003489 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003490 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003491 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003492 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003493
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003494 status_t result = NO_ERROR;
3495
3496 sp<Layer> layer;
3497
Cody Northropbc755282017-03-31 12:00:08 -06003498 String8 uniqueName = getUniqueLayerName(name);
3499
Mathias Agopian3165cc22012-08-08 19:42:09 -07003500 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3501 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003502 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003503 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003504 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 break;
chaviw13fdc492017-06-27 12:40:18 -07003507 case ISurfaceComposerClient::eFXSurfaceColor:
3508 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003509 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003510 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 break;
3512 default:
3513 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 break;
3515 }
3516
Dan Stoza7d89d062015-04-30 13:29:25 -07003517 if (result != NO_ERROR) {
3518 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003520
Chia-I Wuab0c3192017-08-01 11:29:00 -07003521 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3522 // TODO b/64227542
3523 if (windowType == 441731) {
3524 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3525 layer->setPrimaryDisplayOnly();
3526 }
3527
Albert Chaulk479c60c2017-01-27 14:21:34 -05003528 layer->setInfo(windowType, ownerUid);
3529
Robert Carr1f0a16a2016-10-24 16:27:39 -07003530 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003531 if (result != NO_ERROR) {
3532 return result;
3533 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003534 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003535
3536 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003537 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538}
3539
Cody Northropbc755282017-03-31 12:00:08 -06003540String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3541{
3542 bool matchFound = true;
3543 uint32_t dupeCounter = 0;
3544
3545 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3546 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3547
3548 // Loop over layers until we're sure there is no matching name
3549 while (matchFound) {
3550 matchFound = false;
3551 mDrawingState.traverseInZOrder([&](Layer* layer) {
3552 if (layer->getName() == uniqueName) {
3553 matchFound = true;
3554 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3555 }
3556 });
3557 }
3558
3559 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3560
3561 return uniqueName;
3562}
3563
David Sodman0c69cad2017-08-21 12:12:51 -07003564status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003565 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3566 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567{
3568 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003569 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 case PIXEL_FORMAT_TRANSPARENT:
3571 case PIXEL_FORMAT_TRANSLUCENT:
3572 format = PIXEL_FORMAT_RGBA_8888;
3573 break;
3574 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003575 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 break;
3577 }
3578
David Sodman0c69cad2017-08-21 12:12:51 -07003579 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3580 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003581 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003582 *handle = layer->getHandle();
3583 *gbp = layer->getProducer();
3584 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003586
David Sodman0c69cad2017-08-21 12:12:51 -07003587 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589}
3590
chaviw13fdc492017-06-27 12:40:18 -07003591status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003592 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003593 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594{
chaviw13fdc492017-06-27 12:40:18 -07003595 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003596 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003598}
3599
Mathias Agopianac9fa422013-02-11 16:40:36 -08003600status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601{
Robert Carr9524cb32017-02-13 11:32:32 -08003602 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003603 status_t err = NO_ERROR;
3604 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003605 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003606 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003607 err = removeLayer(l);
3608 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3609 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003610 }
3611 return err;
3612}
3613
Mathias Agopian13127d82013-03-05 17:47:11 -08003614status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003615{
Mathias Agopian67106042013-03-14 19:18:13 -07003616 // called by ~LayerCleaner() when all references to the IBinder (handle)
3617 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003618 sp<Layer> l = layer.promote();
3619 if (l == nullptr) {
3620 // The layer has already been removed, carry on
3621 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003622 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003623 // If we have a parent, then we can continue to live as long as it does.
3624 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625}
3626
Mathias Agopianb60314a2012-04-10 22:09:54 -07003627// ---------------------------------------------------------------------------
3628
Andy McFadden13a082e2012-08-24 10:16:42 -07003629void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003630 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003631 Vector<ComposerState> state;
3632 Vector<DisplayState> displays;
3633 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003634 d.what = DisplayState::eDisplayProjectionChanged |
3635 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003636 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003637 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003638 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003639 d.frame.makeInvalid();
3640 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003641 d.width = 0;
3642 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003643 displays.add(d);
3644 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003645 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3646 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003647
David Sodman105b7dc2017-11-04 20:28:14 -07003648 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003649 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003650 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003651
Brian Andersond0010582017-03-07 13:20:31 -08003652 // Use phase of 0 since phase is not known.
3653 // Use latency of 0, which will snap to the ideal latency.
3654 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003655}
3656
3657void SurfaceFlinger::initializeDisplays() {
3658 class MessageScreenInitialized : public MessageBase {
3659 SurfaceFlinger* flinger;
3660 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003661 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003662 virtual bool handler() {
3663 flinger->onInitializeDisplays();
3664 return true;
3665 }
3666 };
3667 sp<MessageBase> msg = new MessageScreenInitialized(this);
3668 postMessageAsync(msg); // we may be called from main thread, use async message
3669}
3670
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003671void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003672 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003673 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3674 this);
3675 int32_t type = hw->getDisplayType();
3676 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003677
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003678 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003679 return;
3680 }
3681
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003682 hw->setPowerMode(mode);
3683 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3684 ALOGW("Trying to set power mode for virtual display");
3685 return;
3686 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003687
Lloyd Pique4d234852018-01-22 17:21:36 -08003688 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003689 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003690 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3691 if (idx < 0) {
3692 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3693 return;
3694 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003695 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003696 }
3697
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003698 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003699 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003700 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003701 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3702 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003703 // FIXME: eventthread only knows about the main display right now
3704 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003705 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003708 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003709 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003710 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003711
3712 struct sched_param param = {0};
3713 param.sched_priority = 1;
3714 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3715 ALOGW("Couldn't set SCHED_FIFO on display on");
3716 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003718 // Turn off the display
3719 struct sched_param param = {0};
3720 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3721 ALOGW("Couldn't set SCHED_OTHER on display off");
3722 }
3723
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003724 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3725 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003726 disableHardwareVsync(true); // also cancels any in-progress resync
3727
Mathias Agopiancde87a32012-09-13 14:09:01 -07003728 // FIXME: eventthread only knows about the main display right now
3729 mEventThread->onScreenReleased();
3730 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003732 getHwComposer().setPowerMode(type, mode);
3733 mVisibleRegionsDirty = true;
3734 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003735 } else if (mode == HWC_POWER_MODE_DOZE ||
3736 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003737 // Update display while dozing
3738 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003739 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3740 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003741 // FIXME: eventthread only knows about the main display right now
3742 mEventThread->onScreenAcquired();
3743 resyncToHardwareVsync(true);
3744 }
3745 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3746 // Leave display going to doze
3747 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3748 disableHardwareVsync(true); // also cancels any in-progress resync
3749 // FIXME: eventthread only knows about the main display right now
3750 mEventThread->onScreenReleased();
3751 }
3752 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003753 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003754 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003755 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003756 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003757 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003758}
3759
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003760void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3761 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003762 SurfaceFlinger& mFlinger;
3763 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003765 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 MessageSetPowerMode(SurfaceFlinger& flinger,
3767 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3768 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003769 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003771 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003773 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003774 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 ALOGW("Attempt to set power mode = %d for virtual display",
3776 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003777 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003778 mFlinger.setPowerModeInternal(
3779 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003780 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003781 return true;
3782 }
3783 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003785 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003786}
3787
3788// ---------------------------------------------------------------------------
3789
Lloyd Pique755e3192018-01-31 16:46:15 -08003790status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3791 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003793
Mathias Agopianbd115332013-04-18 16:41:04 -07003794 IPCThreadState* ipc = IPCThreadState::self();
3795 const int pid = ipc->getCallingPid();
3796 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003797
Mathias Agopianbd115332013-04-18 16:41:04 -07003798 if ((uid != AID_SHELL) &&
3799 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003800 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003801 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003803 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003804 // (this would indicate SF is stuck, but we want to be able to
3805 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003806 status_t err = mStateLock.timedLock(s2ns(1));
3807 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003808 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003809 result.appendFormat(
3810 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3811 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003812 }
3813
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003814 bool dumpAll = true;
3815 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003816 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003817
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003819 if ((index < numArgs) &&
3820 (args[index] == String16("--list"))) {
3821 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003822 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003823 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003824 }
3825
3826 if ((index < numArgs) &&
3827 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003828 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003829 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003830 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003832
3833 if ((index < numArgs) &&
3834 (args[index] == String16("--latency-clear"))) {
3835 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003836 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003837 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003838 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003839
3840 if ((index < numArgs) &&
3841 (args[index] == String16("--dispsync"))) {
3842 index++;
3843 mPrimaryDispSync.dump(result);
3844 dumpAll = false;
3845 }
Dan Stozab90cf072015-03-05 11:05:59 -08003846
3847 if ((index < numArgs) &&
3848 (args[index] == String16("--static-screen"))) {
3849 index++;
3850 dumpStaticScreenStats(result);
3851 dumpAll = false;
3852 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003853
3854 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003855 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003856 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003857 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003858 dumpAll = false;
3859 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003860
3861 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3862 index++;
3863 dumpWideColorInfo(result);
3864 dumpAll = false;
3865 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003866
3867 if ((index < numArgs) &&
3868 (args[index] == String16("--enable-layer-stats"))) {
3869 index++;
3870 mLayerStats.enable();
3871 dumpAll = false;
3872 }
3873
3874 if ((index < numArgs) &&
3875 (args[index] == String16("--disable-layer-stats"))) {
3876 index++;
3877 mLayerStats.disable();
3878 dumpAll = false;
3879 }
3880
3881 if ((index < numArgs) &&
3882 (args[index] == String16("--clear-layer-stats"))) {
3883 index++;
3884 mLayerStats.clear();
3885 dumpAll = false;
3886 }
3887
3888 if ((index < numArgs) &&
3889 (args[index] == String16("--dump-layer-stats"))) {
3890 index++;
3891 mLayerStats.dump(result);
3892 dumpAll = false;
3893 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003894
3895 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3896 index++;
3897 mTimeStats.parseArgs(asProto, args, index, result);
3898 dumpAll = false;
3899 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003901
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003902 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003903 if (asProto) {
3904 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3905 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3906 } else {
3907 dumpAllLocked(args, index, result);
3908 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003909 }
3910
Mathias Agopian9795c422009-08-26 16:36:26 -07003911 if (locked) {
3912 mStateLock.unlock();
3913 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914 }
3915 write(fd, result.string(), result.size());
3916 return NO_ERROR;
3917}
3918
Dan Stozac7014012014-02-14 15:03:43 -08003919void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3920 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003921{
Robert Carr2047fae2016-11-28 14:09:09 -08003922 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003924 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925}
3926
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003927void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003928 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929{
3930 String8 name;
3931 if (index < args.size()) {
3932 name = String8(args[index]);
3933 index++;
3934 }
3935
David Sodman105b7dc2017-11-04 20:28:14 -07003936 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003937 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003938 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003939
3940 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003941 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003942 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003943 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003944 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003945 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003946 }
Robert Carr2047fae2016-11-28 14:09:09 -08003947 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003948 }
3949}
3950
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003951void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003952 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953{
3954 String8 name;
3955 if (index < args.size()) {
3956 name = String8(args[index]);
3957 index++;
3958 }
3959
Robert Carr2047fae2016-11-28 14:09:09 -08003960 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003961 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003962 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963 }
Robert Carr2047fae2016-11-28 14:09:09 -08003964 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003965
Svetoslavd85084b2014-03-20 10:28:31 -07003966 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967}
3968
Jamie Gennis6547ff42013-07-16 20:12:42 -07003969// This should only be called from the main thread. Otherwise it would need
3970// the lock and should use mCurrentState rather than mDrawingState.
3971void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003972 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003974 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003975
3976 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3977}
3978
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003979void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003980{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003981 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003982
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003983 if (isLayerTripleBufferingDisabled())
3984 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003985
3986 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003987 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003988 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003989 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003990 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3991 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003992 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003993}
3994
Dan Stozab90cf072015-03-05 11:05:59 -08003995void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3996{
3997 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003998 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3999 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004000 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004001 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004002 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4003 b + 1, bucketTimeSec, percent);
4004 }
David Sodman4a36e932017-11-07 14:29:47 -08004005 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004006 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004007 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004008 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004009 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004010}
4011
Dan Stozae77c7662016-05-13 11:37:28 -07004012void SurfaceFlinger::recordBufferingStats(const char* layerName,
4013 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004014 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4015 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004016 for (const auto& segment : history) {
4017 if (!segment.usedThirdBuffer) {
4018 stats.twoBufferTime += segment.totalTime;
4019 }
4020 if (segment.occupancyAverage < 1.0f) {
4021 stats.doubleBufferedTime += segment.totalTime;
4022 } else if (segment.occupancyAverage < 2.0f) {
4023 stats.tripleBufferedTime += segment.totalTime;
4024 }
4025 ++stats.numSegments;
4026 stats.totalTime += segment.totalTime;
4027 }
4028}
4029
Brian Andersond6927fb2016-07-23 23:37:30 -07004030void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4031 result.appendFormat("Layer frame timestamps:\n");
4032
4033 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4034 const size_t count = currentLayers.size();
4035 for (size_t i=0 ; i<count ; i++) {
4036 currentLayers[i]->dumpFrameEvents(result);
4037 }
4038}
4039
Dan Stozae77c7662016-05-13 11:37:28 -07004040void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4041 result.append("Buffering stats:\n");
4042 result.append(" [Layer name] <Active time> <Two buffer> "
4043 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004044 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004045 typedef std::tuple<std::string, float, float, float> BufferTuple;
4046 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004047 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004048 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004049 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004050 if (stats.numSegments == 0) {
4051 continue;
4052 }
4053 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4054 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4055 stats.totalTime;
4056 float doubleBufferRatio = static_cast<float>(
4057 stats.doubleBufferedTime) / stats.totalTime;
4058 float tripleBufferRatio = static_cast<float>(
4059 stats.tripleBufferedTime) / stats.totalTime;
4060 sorted.insert({activeTime, {name, twoBufferRatio,
4061 doubleBufferRatio, tripleBufferRatio}});
4062 }
4063 for (const auto& sortedPair : sorted) {
4064 float activeTime = sortedPair.first;
4065 const BufferTuple& values = sortedPair.second;
4066 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4067 std::get<0>(values).c_str(), activeTime,
4068 std::get<1>(values), std::get<2>(values),
4069 std::get<3>(values));
4070 }
4071 result.append("\n");
4072}
4073
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004074void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4075 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004076 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004077
4078 // TODO: print out if wide-color mode is active or not
4079
4080 for (size_t d = 0; d < mDisplays.size(); d++) {
4081 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4082 int32_t hwcId = displayDevice->getHwcDisplayId();
4083 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4084 continue;
4085 }
4086
4087 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004088 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004089 for (auto&& mode : modes) {
4090 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4091 }
4092
Peiyong Lina52f0292018-03-14 17:26:31 -07004093 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004094 result.appendFormat(" Current color mode: %s (%d)\n",
4095 decodeColorMode(currentMode).c_str(), currentMode);
4096 }
4097 result.append("\n");
4098}
4099
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004100LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004101 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004102 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4103 const State& state = useDrawing ? mDrawingState : mCurrentState;
4104 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004105 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004106 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004107 });
4108
4109 return layersProto;
4110}
4111
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004112LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4113 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004114 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004115
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004116 SizeProto* resolution = layersProto.mutable_resolution();
4117 resolution->set_w(displayDevice->getWidth());
4118 resolution->set_h(displayDevice->getHeight());
4119
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004120 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4121 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4122 layersProto.set_global_transform(
4123 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4124
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004125 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004126 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004127 LayerProto* layerProto = layersProto.add_layers();
4128 layer->writeToProto(layerProto, hwcId);
4129 }
4130 });
4131
4132 return layersProto;
4133}
4134
Mathias Agopian74d211a2013-04-22 16:55:35 +02004135void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4136 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004137{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004138 bool colorize = false;
4139 if (index < args.size()
4140 && (args[index] == String16("--color"))) {
4141 colorize = true;
4142 index++;
4143 }
4144
4145 Colorizer colorizer(colorize);
4146
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004147 // figure out if we're stuck somewhere
4148 const nsecs_t now = systemTime();
4149 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4150 const nsecs_t inTransaction(mDebugInTransaction);
4151 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4152 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4153
4154 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004155 * Dump library configuration.
4156 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004157
4158 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004159 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004160 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004161 appendSfConfigString(result);
4162 appendUiConfigString(result);
4163 appendGuiConfigString(result);
4164 result.append("\n");
4165
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004166 result.append("\nWide-Color information:\n");
4167 dumpWideColorInfo(result);
4168
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004169 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004170 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004171 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004172 result.append(SyncFeatures::getInstance().toString());
4173 result.append("\n");
4174
David Sodman105b7dc2017-11-04 20:28:14 -07004175 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004176
Andy McFadden41d67d72014-04-25 16:58:34 -07004177 colorizer.bold(result);
4178 result.append("DispSync configuration: ");
4179 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004180 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4181 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4182 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004183 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004184 result.append("\n");
4185
Dan Stozab90cf072015-03-05 11:05:59 -08004186 // Dump static screen stats
4187 result.append("\n");
4188 dumpStaticScreenStats(result);
4189 result.append("\n");
4190
Dan Stozae77c7662016-05-13 11:37:28 -07004191 dumpBufferingStats(result);
4192
Andy McFadden4803b742012-09-24 19:07:20 -07004193 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004194 * Dump the visible layer list
4195 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004196 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004197 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004198 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4199 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004201
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004202 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004203 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004204 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004205 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004206
4207 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004208 * Dump Display state
4209 */
4210
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004212 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004214 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4215 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004216 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004217 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004218 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004219
4220 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004221 * Dump SurfaceFlinger global state
4222 */
4223
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004224 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004225 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227
Mathias Agopian888c8222012-08-04 21:10:38 -07004228 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004229 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004230
David Sodmanbc815282017-11-05 18:57:52 -08004231 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004233 if (hw) {
4234 hw->undefinedRegion.dump(result, "undefinedRegion");
4235 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4236 hw->getOrientation(), hw->isDisplayOn());
4237 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004238 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004239 " last eglSwapBuffers() time: %f us\n"
4240 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004241 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242 " refresh-rate : %f fps\n"
4243 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004244 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004245 " gpu_to_cpu_unsupported : %d\n"
4246 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004247 mLastSwapBufferTime/1000.0,
4248 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004249 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004250 1e9 / activeConfig->getVsyncPeriod(),
4251 activeConfig->getDpiX(),
4252 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004253 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254
Mathias Agopian74d211a2013-04-22 16:55:35 +02004255 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257
Mathias Agopian74d211a2013-04-22 16:55:35 +02004258 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260
4261 /*
4262 * VSYNC state
4263 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004264 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004265 result.append("\n");
4266
4267 /*
4268 * HWC layer minidump
4269 */
4270 for (size_t d = 0; d < mDisplays.size(); d++) {
4271 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4272 int32_t hwcId = displayDevice->getHwcDisplayId();
4273 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4274 continue;
4275 }
4276
4277 result.appendFormat("Display %d HWC layers:\n", hwcId);
4278 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004279 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004280 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004281 });
Dan Stozae22aec72016-08-01 13:20:59 -07004282 result.append("\n");
4283 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
4286 * Dump HWComposer state
4287 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004289 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004291 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004292 result.appendFormat(" h/w composer %s\n",
4293 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004294 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004295
4296 /*
4297 * Dump gralloc state
4298 */
4299 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4300 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004301
4302 /*
4303 * Dump VrFlinger state if in use.
4304 */
4305 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4306 result.append("VrFlinger state:\n");
4307 result.append(mVrFlinger->Dump().c_str());
4308 result.append("\n");
4309 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004310}
4311
Mathias Agopian13127d82013-03-05 17:47:11 -08004312const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004313SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004314 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004315 wp<IBinder> dpy;
4316 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4317 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4318 dpy = mDisplays.keyAt(i);
4319 break;
4320 }
4321 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004322 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004323 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4324 // Just use the primary display so we have something to return
4325 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4326 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004327 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004328}
4329
Keun young Park63f165f2012-08-31 10:53:36 -07004330bool SurfaceFlinger::startDdmConnection()
4331{
4332 void* libddmconnection_dso =
4333 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4334 if (!libddmconnection_dso) {
4335 return false;
4336 }
4337 void (*DdmConnection_start)(const char* name);
4338 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004339 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004340 if (!DdmConnection_start) {
4341 dlclose(libddmconnection_dso);
4342 return false;
4343 }
4344 (*DdmConnection_start)(getServiceName());
4345 return true;
4346}
4347
Chia-I Wu28f320b2018-05-03 11:02:56 -07004348void SurfaceFlinger::updateColorMatrixLocked() {
4349 mat4 colorMatrix;
4350 if (mGlobalSaturationFactor != 1.0f) {
4351 // Rec.709 luma coefficients
4352 float3 luminance{0.213f, 0.715f, 0.072f};
4353 luminance *= 1.0f - mGlobalSaturationFactor;
4354 mat4 saturationMatrix = mat4(
4355 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4356 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4357 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4358 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4359 );
4360 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4361 } else {
4362 colorMatrix = mClientColorMatrix * mDaltonizer();
4363 }
4364
4365 if (mCurrentState.colorMatrix != colorMatrix) {
4366 mCurrentState.colorMatrix = colorMatrix;
4367 mCurrentState.colorMatrixChanged = true;
4368 setTransactionFlags(eTransactionNeeded);
4369 }
4370}
4371
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004372status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004373 switch (code) {
4374 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004375 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004376 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004377 case CLEAR_ANIMATION_FRAME_STATS:
4378 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004379 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004380 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004381 case ENABLE_VSYNC_INJECTIONS:
4382 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004383 {
4384 // codes that require permission check
4385 IPCThreadState* ipc = IPCThreadState::self();
4386 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004387 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004388 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004389 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004390 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004391 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004393 break;
4394 }
Robert Carr1db73f62016-12-21 12:58:51 -08004395 /*
4396 * Calling setTransactionState is safe, because you need to have been
4397 * granted a reference to Client* and Handle* to do anything with it.
4398 *
4399 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4400 */
4401 case SET_TRANSACTION_STATE:
4402 case CREATE_SCOPED_CONNECTION:
4403 {
4404 return OK;
4405 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004406 case CAPTURE_SCREEN:
4407 {
4408 // codes that require permission check
4409 IPCThreadState* ipc = IPCThreadState::self();
4410 const int pid = ipc->getCallingPid();
4411 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004412 if ((uid != AID_GRAPHICS) &&
4413 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004414 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004415 return PERMISSION_DENIED;
4416 }
4417 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004418 }
chaviwa76b2712017-09-20 12:02:26 -07004419 case CAPTURE_LAYERS: {
4420 IPCThreadState* ipc = IPCThreadState::self();
4421 const int pid = ipc->getCallingPid();
4422 const int uid = ipc->getCallingUid();
4423 if ((uid != AID_GRAPHICS) &&
4424 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4425 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4426 return PERMISSION_DENIED;
4427 }
4428 break;
4429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004431 return OK;
4432}
4433
4434status_t SurfaceFlinger::onTransact(
4435 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4436{
4437 status_t credentialCheck = CheckTransactCodeCredentials(code);
4438 if (credentialCheck != OK) {
4439 return credentialCheck;
4440 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004441
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004442 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4443 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004444 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004445 IPCThreadState* ipc = IPCThreadState::self();
4446 const int uid = ipc->getCallingUid();
4447 if (CC_UNLIKELY(uid != AID_SYSTEM
4448 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004449 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004450 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004451 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 return PERMISSION_DENIED;
4453 }
4454 int n;
4455 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004456 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004457 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004458 return NO_ERROR;
4459 case 1002: // SHOW_UPDATES
4460 n = data.readInt32();
4461 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004462 invalidateHwcGeometry();
4463 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004465 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004466 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004467 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004469 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004470 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004471 setTransactionFlags(
4472 eTransactionNeeded|
4473 eDisplayTransactionNeeded|
4474 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004475 return NO_ERROR;
4476 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004477 case 1006:{ // send empty update
4478 signalRefresh();
4479 return NO_ERROR;
4480 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004481 case 1008: // toggle use of hw composer
4482 n = data.readInt32();
4483 mDebugDisableHWC = n ? 1 : 0;
4484 invalidateHwcGeometry();
4485 repaintEverything();
4486 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004487 case 1009: // toggle use of transform hint
4488 n = data.readInt32();
4489 mDebugDisableTransformHint = n ? 1 : 0;
4490 invalidateHwcGeometry();
4491 repaintEverything();
4492 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004494 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004495 reply->writeInt32(0);
4496 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004497 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004498 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004499 return NO_ERROR;
4500 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004501 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004502 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004503 return NO_ERROR;
4504 }
4505 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004506 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004507 // daltonize
4508 n = data.readInt32();
4509 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004510 case 1:
4511 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4512 break;
4513 case 2:
4514 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4515 break;
4516 case 3:
4517 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4518 break;
4519 default:
4520 mDaltonizer.setType(ColorBlindnessType::None);
4521 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004522 }
4523 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004524 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004525 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004526 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004527 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004528
4529 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004530 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004533 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004534 // apply a color matrix
4535 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004536 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004537 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004538 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004539 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004540 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004541 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004542 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004543 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004544 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004545 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004546
4547 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4548 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004549 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004550 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4551 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4552 }
4553
Chia-I Wu28f320b2018-05-03 11:02:56 -07004554 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004555 return NO_ERROR;
4556 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004557 // This is an experimental interface
4558 // Needs to be shifted to proper binder interface when we productize
4559 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004560 n = data.readInt32();
4561 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004562 return NO_ERROR;
4563 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004564 case 1017: {
4565 n = data.readInt32();
4566 mForceFullDamage = static_cast<bool>(n);
4567 return NO_ERROR;
4568 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004569 case 1018: { // Modify Choreographer's phase offset
4570 n = data.readInt32();
4571 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4572 return NO_ERROR;
4573 }
4574 case 1019: { // Modify SurfaceFlinger's phase offset
4575 n = data.readInt32();
4576 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4577 return NO_ERROR;
4578 }
Irvel468051e2016-06-13 16:44:44 -07004579 case 1020: { // Layer updates interceptor
4580 n = data.readInt32();
4581 if (n) {
4582 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004583 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004584 }
4585 else{
4586 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004587 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004588 }
4589 return NO_ERROR;
4590 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004591 case 1021: { // Disable HWC virtual displays
4592 n = data.readInt32();
4593 mUseHwcVirtualDisplays = !n;
4594 return NO_ERROR;
4595 }
Romain Guy0147a172017-06-01 13:53:56 -07004596 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004597 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004598 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004599
Chia-I Wu28f320b2018-05-03 11:02:56 -07004600 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004601 return NO_ERROR;
4602 }
Romain Guy54f154a2017-10-24 21:40:32 +01004603 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004604 int32_t value = data.readInt32();
4605 if (value > 2) {
4606 return BAD_VALUE;
4607 }
4608 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4609 return BAD_VALUE;
4610 }
Romain Guy54f154a2017-10-24 21:40:32 +01004611
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004612 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004613 invalidateHwcGeometry();
4614 repaintEverything();
4615 return NO_ERROR;
4616 }
4617 case 1024: { // Is wide color gamut rendering/color management supported?
4618 reply->writeBool(hasWideColorDisplay);
4619 return NO_ERROR;
4620 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004621 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004622 n = data.readInt32();
4623 if (n) {
4624 ALOGV("LayerTracing enabled");
4625 mTracing.enable();
4626 doTracing("tracing.enable");
4627 reply->writeInt32(NO_ERROR);
4628 } else {
4629 ALOGV("LayerTracing disabled");
4630 status_t err = mTracing.disable();
4631 reply->writeInt32(err);
4632 }
4633 return NO_ERROR;
4634 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004635 case 1026: { // Get layer tracing status
4636 reply->writeBool(mTracing.isEnabled());
4637 return NO_ERROR;
4638 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004639 // Is a DisplayColorSetting supported?
4640 case 1027: {
4641 int32_t value = data.readInt32();
4642 switch (value) {
4643 case 0:
4644 reply->writeBool(hasWideColorDisplay);
4645 return NO_ERROR;
4646 case 1:
4647 reply->writeBool(true);
4648 return NO_ERROR;
4649 case 2:
4650 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4651 return NO_ERROR;
4652 default:
4653 return BAD_VALUE;
4654 }
4655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 }
4657 }
4658 return err;
4659}
4660
Steven Thomas6d8110b2017-08-31 18:24:21 -07004661void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004662 android_atomic_or(1, &mRepaintEverything);
4663 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004664}
4665
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004666// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4667class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004668public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004669 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4670 ~WindowDisconnector() {
4671 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004672 }
4673
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004674private:
4675 ANativeWindow* mWindow;
4676 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004677};
4678
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004679status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4680 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4681 int32_t minLayerZ, int32_t maxLayerZ,
4682 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004683 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004684 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004685
chaviwa76b2712017-09-20 12:02:26 -07004686 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4687
4688 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004689 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4690
chaviwa76b2712017-09-20 12:02:26 -07004691 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4692
4693 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4694 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004695 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004696}
4697
4698status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004699 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004700 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004701 ATRACE_CALL();
4702
4703 class LayerRenderArea : public RenderArea {
4704 public:
Robert Carr578038f2018-03-09 12:25:24 -08004705 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4706 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004707 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004708 mLayer(layer),
4709 mCrop(crop),
4710 mFlinger(flinger),
4711 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004712 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004713 Rect getBounds() const override {
4714 const Layer::State& layerState(mLayer->getDrawingState());
4715 return Rect(layerState.active.w, layerState.active.h);
4716 }
4717 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4718 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4719 bool isSecure() const override { return false; }
4720 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004721 Rect getSourceCrop() const override {
4722 if (mCrop.isEmpty()) {
4723 return getBounds();
4724 } else {
4725 return mCrop;
4726 }
4727 }
Robert Carr578038f2018-03-09 12:25:24 -08004728 class ReparentForDrawing {
4729 public:
4730 const sp<Layer>& oldParent;
4731 const sp<Layer>& newParent;
4732
4733 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4734 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004735 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004736 }
Robert Carr15eae092018-03-23 13:43:53 -07004737 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004738 };
4739
4740 void render(std::function<void()> drawLayers) override {
4741 if (!mChildrenOnly) {
4742 mTransform = mLayer->getTransform().inverse();
4743 drawLayers();
4744 } else {
4745 Rect bounds = getBounds();
4746 screenshotParentLayer =
4747 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4748 bounds.getWidth(), bounds.getHeight(), 0);
4749
4750 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4751 drawLayers();
4752 }
4753 }
chaviwa76b2712017-09-20 12:02:26 -07004754
chaviwa76b2712017-09-20 12:02:26 -07004755 private:
chaviw7206d492017-11-10 16:16:12 -08004756 const sp<Layer> mLayer;
4757 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004758
4759 // In the "childrenOnly" case we reparent the children to a screenshot
4760 // layer which has no properties set and which does not draw.
4761 sp<ContainerLayer> screenshotParentLayer;
4762 Transform mTransform;
4763
4764 SurfaceFlinger* mFlinger;
4765 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004766 };
4767
4768 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4769 auto parent = layerHandle->owner.promote();
4770
chaviw7206d492017-11-10 16:16:12 -08004771 if (parent == nullptr || parent->isPendingRemoval()) {
4772 ALOGE("captureLayers called with a removed parent");
4773 return NAME_NOT_FOUND;
4774 }
4775
Robert Carr578038f2018-03-09 12:25:24 -08004776 const int uid = IPCThreadState::self()->getCallingUid();
4777 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4778 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4779 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4780 return PERMISSION_DENIED;
4781 }
4782
chaviw7206d492017-11-10 16:16:12 -08004783 Rect crop(sourceCrop);
4784 if (sourceCrop.width() <= 0) {
4785 crop.left = 0;
4786 crop.right = parent->getCurrentState().active.w;
4787 }
4788
4789 if (sourceCrop.height() <= 0) {
4790 crop.top = 0;
4791 crop.bottom = parent->getCurrentState().active.h;
4792 }
4793
4794 int32_t reqWidth = crop.width() * frameScale;
4795 int32_t reqHeight = crop.height() * frameScale;
4796
Robert Carr578038f2018-03-09 12:25:24 -08004797 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004798
Robert Carr578038f2018-03-09 12:25:24 -08004799 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004800 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4801 if (!layer->isVisible()) {
4802 return;
Robert Carr578038f2018-03-09 12:25:24 -08004803 } else if (childrenOnly && layer == parent.get()) {
4804 return;
chaviwa76b2712017-09-20 12:02:26 -07004805 }
4806 visitor(layer);
4807 });
4808 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004809 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004810}
4811
4812status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4813 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004814 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004815 bool useIdentityTransform) {
4816 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004817
chaviwa76b2712017-09-20 12:02:26 -07004818 renderArea.updateDimensions();
4819
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004820 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4821 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4822 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4823 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004824
4825 // This mutex protects syncFd and captureResult for communication of the return values from the
4826 // main thread back to this Binder thread
4827 std::mutex captureMutex;
4828 std::condition_variable captureCondition;
4829 std::unique_lock<std::mutex> captureLock(captureMutex);
4830 int syncFd = -1;
4831 std::optional<status_t> captureResult;
4832
Robert Carr03480e22018-01-04 16:02:06 -08004833 const int uid = IPCThreadState::self()->getCallingUid();
4834 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4835
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004836 sp<LambdaMessage> message = new LambdaMessage([&]() {
4837 // If there is a refresh pending, bug out early and tell the binder thread to try again
4838 // after the refresh.
4839 if (mRefreshPending) {
4840 ATRACE_NAME("Skipping screenshot for now");
4841 std::unique_lock<std::mutex> captureLock(captureMutex);
4842 captureResult = std::make_optional<status_t>(EAGAIN);
4843 captureCondition.notify_one();
4844 return;
4845 }
4846
4847 status_t result = NO_ERROR;
4848 int fd = -1;
4849 {
4850 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004851 renderArea.render([&]() {
4852 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4853 useIdentityTransform, forSystem, &fd);
4854 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004855 }
4856
4857 {
4858 std::unique_lock<std::mutex> captureLock(captureMutex);
4859 syncFd = fd;
4860 captureResult = std::make_optional<status_t>(result);
4861 captureCondition.notify_one();
4862 }
4863 });
4864
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004865 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866 if (result == NO_ERROR) {
4867 captureCondition.wait(captureLock, [&]() { return captureResult; });
4868 while (*captureResult == EAGAIN) {
4869 captureResult.reset();
4870 result = postMessageAsync(message);
4871 if (result != NO_ERROR) {
4872 return result;
4873 }
4874 captureCondition.wait(captureLock, [&]() { return captureResult; });
4875 }
4876 result = *captureResult;
4877 }
4878
4879 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004880 sync_wait(syncFd, -1);
4881 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004882 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004883
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004884 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004885}
4886
chaviwa76b2712017-09-20 12:02:26 -07004887void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4888 TraverseLayersFunction traverseLayers, bool yswap,
4889 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004890 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004891
Lloyd Pique144e1162017-12-20 16:44:52 -08004892 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004893
4894 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004895 const auto raWidth = renderArea.getWidth();
4896 const auto raHeight = renderArea.getHeight();
4897
4898 const auto reqWidth = renderArea.getReqWidth();
4899 const auto reqHeight = renderArea.getReqHeight();
4900 Rect sourceCrop = renderArea.getSourceCrop();
4901
4902 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4903 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004904
Dan Stozac1879002014-05-22 15:59:05 -07004905 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004906 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004907 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004908 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004909 }
4910
4911 // ensure that sourceCrop is inside screen
4912 if (sourceCrop.left < 0) {
4913 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4914 }
chaviwa76b2712017-09-20 12:02:26 -07004915 if (sourceCrop.right > raWidth) {
4916 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004917 }
4918 if (sourceCrop.top < 0) {
4919 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4920 }
chaviwa76b2712017-09-20 12:02:26 -07004921 if (sourceCrop.bottom > raHeight) {
4922 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004923 }
4924
Chia-I Wu36574d92018-05-16 10:54:36 -07004925 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4926 engine.setOutputDataSpace(Dataspace::SRGB);
4927 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004928
Mathias Agopian180f10d2013-04-10 22:55:41 -07004929 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004930 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004931
4932 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004933 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4934 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004935 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004936
chaviw50da5042018-04-09 13:49:37 -07004937 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004938 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004939 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004940
chaviwa76b2712017-09-20 12:02:26 -07004941 traverseLayers([&](Layer* layer) {
4942 if (filtering) layer->setFiltering(true);
4943 layer->draw(renderArea, useIdentityTransform);
4944 if (filtering) layer->setFiltering(false);
4945 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004946}
4947
chaviwa76b2712017-09-20 12:02:26 -07004948status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4949 TraverseLayersFunction traverseLayers,
4950 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004951 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004952 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004953 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004954 ATRACE_CALL();
4955
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004956 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004957
4958 traverseLayers([&](Layer* layer) {
4959 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4960 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004961
Robert Carr03480e22018-01-04 16:02:06 -08004962 // We allow the system server to take screenshots of secure layers for
4963 // use in situations like the Screen-rotation animation and place
4964 // the impetus on WindowManager to not persist them.
4965 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004966 ALOGW("FB is protected: PERMISSION_DENIED");
4967 return PERMISSION_DENIED;
4968 }
4969
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004970 // this binds the given EGLImage as a framebuffer for the
4971 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004972 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004973 if (bufferBond.getStatus() != NO_ERROR) {
4974 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004975 return INVALID_OPERATION;
4976 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004977
Dan Stozaabcda352017-06-01 14:37:39 -07004978 // this will in fact render into our dequeued buffer
4979 // via an FBO, which means we didn't have to create
4980 // an EGLSurface and therefore we're not
4981 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004982 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004983
Dan Stozaabcda352017-06-01 14:37:39 -07004984 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004985 getRenderEngine().finish();
4986 *outSyncFd = -1;
4987
chaviwa76b2712017-09-20 12:02:26 -07004988 const auto reqWidth = renderArea.getReqWidth();
4989 const auto reqHeight = renderArea.getReqHeight();
4990
Dan Stozaabcda352017-06-01 14:37:39 -07004991 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4992 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004993 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004994 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004995 } else {
4996 base::unique_fd syncFd = getRenderEngine().flush();
4997 if (syncFd < 0) {
4998 getRenderEngine().finish();
4999 }
5000 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005001 }
5002
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005003 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005004}
5005
Mathias Agopiand5556842013-09-19 17:08:37 -07005006void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005007 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005008 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005009 for (size_t y = 0; y < h; y++) {
5010 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5011 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005012 if (p[x] != 0xFF000000) return;
5013 }
5014 }
chaviwa76b2712017-09-20 12:02:26 -07005015 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005016
Robert Carr2047fae2016-11-28 14:09:09 -08005017 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005018 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005019 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005020 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5021 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5022 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5023 static_cast<float>(state.color.a));
5024 i++;
5025 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005026 }
5027}
5028
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005029// ---------------------------------------------------------------------------
5030
Dan Stoza412903f2017-04-27 13:42:17 -07005031void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5032 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005033}
5034
Dan Stoza412903f2017-04-27 13:42:17 -07005035void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5036 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005037}
5038
chaviwa76b2712017-09-20 12:02:26 -07005039void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5040 int32_t maxLayerZ,
5041 const LayerVector::Visitor& visitor) {
5042 // We loop through the first level of layers without traversing,
5043 // as we need to interpret min/max layer Z in the top level Z space.
5044 for (const auto& layer : mDrawingState.layersSortedByZ) {
5045 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5046 continue;
5047 }
5048 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005049 // relative layers are traversed in Layer::traverseInZOrder
5050 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005051 continue;
5052 }
5053 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005054 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5055 return;
5056 }
chaviwa76b2712017-09-20 12:02:26 -07005057 if (!layer->isVisible()) {
5058 return;
5059 }
5060 visitor(layer);
5061 });
5062 }
5063}
5064
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005066
5067
5068#if defined(__gl_h_)
5069#error "don't include gl/gl.h in this file"
5070#endif
5071
5072#if defined(__gl2_h_)
5073#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005074#endif