blob: e7e3eb3b6c63a502cf4f7100cafd3d3fef481bc5 [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
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002901 needsLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002902 outputDataspace != Dataspace::UNKNOWN &&
2903 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002904
Chia-I Wu7f402902017-11-09 12:51:10 -08002905 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002906 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002908 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002909
2910 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002911 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002912 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2913 }
2914 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002915 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002916
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002917 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002919 // when using overlays, we assume a fully transparent framebuffer
2920 // NOTE: we could reduce how much we need to clear, for instance
2921 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002922 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002923 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002924 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002925 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002926 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002927 // we're left with the letterbox region
2928 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002930
2931 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002933
Mathias Agopianb9494d52012-04-18 02:28:45 -07002934 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002935 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002936 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002938 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002939 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002940
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002942 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002943 // scissor on the main display. It should never be needed
2944 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 const Rect& bounds(displayDevice->getBounds());
2946 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002947 if (scissor != bounds) {
2948 // scissor doesn't match the screen's dimensions, so we
2949 // need to clear everything outside of it and enable
2950 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002951
Mathias Agopianf45c5102012-10-24 16:29:17 -07002952 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002954 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002955 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002956 }
2957 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002958 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002959
Mathias Agopian85d751c2012-08-29 16:59:24 -07002960 /*
2961 * and then, render the layers targeted at the framebuffer
2962 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002963
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964 ALOGV("Rendering client layers");
2965 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 bool firstLayer = true;
2967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2968 const Region clip(bounds.intersect(
2969 displayTransform.transform(layer->visibleRegion)));
2970 ALOGV("Layer: %s", layer->getName().string());
2971 ALOGV(" Composition type: %s",
2972 to_string(layer->getCompositionType(hwcId)).c_str());
2973 if (!clip.isEmpty()) {
2974 switch (layer->getCompositionType(hwcId)) {
2975 case HWC2::Composition::Cursor:
2976 case HWC2::Composition::Device:
2977 case HWC2::Composition::Sideband:
2978 case HWC2::Composition::SolidColor: {
2979 const Layer::State& state(layer->getDrawingState());
2980 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2981 layer->isOpaque(state) && (state.color.a == 1.0f)
2982 && hasClientComposition) {
2983 // never clear the very first layer since we're
2984 // guaranteed the FB is already cleared
2985 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002986 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002987 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002988 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002989 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002990 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002991 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2992 if (!legacyColorMatrixApplied) {
2993 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2994 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002995 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002996 } else if (legacyColorMatrixApplied) {
2997 getRenderEngine().setSaturationMatrix(mat4());
2998 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002999 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003000
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003001 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003002 break;
3003 }
3004 default:
3005 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003006 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003007 } else {
3008 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003009 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003010 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003011 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003012
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003013 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003014 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003015 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003016 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3017 getRenderEngine().setSaturationMatrix(mat4());
3018 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003019
Mathias Agopianf45c5102012-10-24 16:29:17 -07003020 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003021 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003022 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003023}
3024
Fabien Sanglard830b8472016-11-30 16:35:58 -08003025void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3026 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003027 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003028 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029}
3030
Dan Stoza7d89d062015-04-30 13:29:25 -07003031status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003032 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003033 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 const sp<Layer>& lbc,
3035 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003036{
Dan Stoza7d89d062015-04-30 13:29:25 -07003037 // add this layer to the current state list
3038 {
3039 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003041 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3042 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003043 return NO_MEMORY;
3044 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 if (parent == nullptr) {
3046 mCurrentState.layersSortedByZ.add(lbc);
3047 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003048 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003049 ALOGE("addClientLayer called with a removed parent");
3050 return NAME_NOT_FOUND;
3051 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 parent->addChild(lbc);
3053 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003054
Yiwei Zhang243b3782018-05-15 17:40:04 -07003055 if (gbc != nullptr) {
3056 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3057 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3058 mMaxGraphicBufferProducerListSize,
3059 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3060 mGraphicBufferProducerList.size(),
3061 mMaxGraphicBufferProducerListSize, mNumLayers);
3062 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 mLayersAdded = true;
3064 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003065 }
3066
Mathias Agopian96f08192010-06-02 23:28:45 -07003067 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003068 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003069
Dan Stoza7d89d062015-04-30 13:29:25 -07003070 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003071}
3072
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003073status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003074 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003075 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3076}
Robert Carr7f9b8992017-03-10 11:08:39 -08003077
chaviwca27f252018-02-06 16:46:39 -08003078status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3079 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003080 if (layer->isPendingRemoval()) {
3081 return NO_ERROR;
3082 }
3083
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003085 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003086 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003087 if (topLevelOnly) {
3088 return NO_ERROR;
3089 }
3090
Chia-I Wu98f1c102017-05-30 14:54:08 -07003091 sp<Layer> ancestor = p;
3092 while (ancestor->getParent() != nullptr) {
3093 ancestor = ancestor->getParent();
3094 }
3095 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3096 ALOGE("removeLayer called with a layer whose parent has been removed");
3097 return NAME_NOT_FOUND;
3098 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003099
3100 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003101 } else {
3102 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003103 }
3104
Robert Carr136e2f62017-02-08 17:54:29 -08003105 // As a matter of normal operation, the LayerCleaner will produce a second
3106 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3107 // so we will succeed in promoting it, but it's already been removed
3108 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3109 // otherwise something has gone wrong and we are leaking the layer.
3110 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003111 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3112 layer->getName().string(),
3113 (p != nullptr) ? p->getName().string() : "no-parent");
3114 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003115 } else if (index < 0) {
3116 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003117 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118
Chia-I Wuc6657022017-08-15 11:18:17 -07003119 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003120 mLayersPendingRemoval.add(layer);
3121 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003122 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003123 setTransactionFlags(eTransactionNeeded);
3124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125}
3126
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003127uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003128 return android_atomic_release_load(&mTransactionFlags);
3129}
3130
Mathias Agopian3f844832013-08-07 21:24:32 -07003131uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3133}
3134
Mathias Agopian3f844832013-08-07 21:24:32 -07003135uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003136 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3137}
3138
3139uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3140 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003142 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003144 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 }
3146 return old;
3147}
3148
chaviwca27f252018-02-06 16:46:39 -08003149bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3150 for (const ComposerState& state : states) {
3151 // Here we need to check that the interface we're given is indeed
3152 // one of our own. A malicious client could give us a nullptr
3153 // IInterface, or one of its own or even one of our own but a
3154 // different type. All these situations would cause us to crash.
3155 if (state.client == nullptr) {
3156 return true;
3157 }
3158
3159 sp<IBinder> binder = IInterface::asBinder(state.client);
3160 if (binder == nullptr) {
3161 return true;
3162 }
3163
3164 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3165 return true;
3166 }
3167 }
3168 return false;
3169}
3170
Mathias Agopian8b33f032012-07-24 20:43:54 -07003171void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003172 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003173 const Vector<DisplayState>& displays,
3174 uint32_t flags)
3175{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003176 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003177 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003178 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003179
chaviwca27f252018-02-06 16:46:39 -08003180 if (containsAnyInvalidClientState(states)) {
3181 return;
3182 }
3183
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003184 if (flags & eAnimation) {
3185 // For window updates that are part of an animation we must wait for
3186 // previous animation "frames" to be handled.
3187 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003188 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003189 if (CC_UNLIKELY(err != NO_ERROR)) {
3190 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003191 // caller after a few seconds.
3192 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3193 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003194 mAnimTransactionPending = false;
3195 break;
3196 }
3197 }
3198 }
3199
chaviwca27f252018-02-06 16:46:39 -08003200 for (const DisplayState& display : displays) {
3201 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003202 }
3203
chaviwca27f252018-02-06 16:46:39 -08003204 for (const ComposerState& state : states) {
3205 transactionFlags |= setClientStateLocked(state);
3206 }
3207
3208 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3209 // as destroyed should only occur after setting all other states. This is to allow for a
3210 // child re-parent to happen before marking its original parent as destroyed (which would
3211 // then mark the child as destroyed).
3212 for (const ComposerState& state : states) {
3213 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003214 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003215
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003216 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3217 // anyway. This can be used as a flush mechanism for previous async transactions.
3218 // Empty animation transaction can be used to simulate back-pressure, so also force a
3219 // transaction for empty animation transactions.
3220 if (transactionFlags == 0 &&
3221 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003222 transactionFlags = eTransactionNeeded;
3223 }
3224
Mathias Agopian386aa982011-11-07 21:58:03 -08003225 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003226 if (mInterceptor->isEnabled()) {
3227 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003228 }
Irvel468051e2016-06-13 16:44:44 -07003229
Mathias Agopian386aa982011-11-07 21:58:03 -08003230 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003231 const auto start = (flags & eEarlyWakeup)
3232 ? VSyncModulator::TransactionStart::EARLY
3233 : VSyncModulator::TransactionStart::NORMAL;
3234 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003235
3236 // if this is a synchronous transaction, wait for it to take effect
3237 // before returning.
3238 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003239 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003240 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003241 if (flags & eAnimation) {
3242 mAnimTransactionPending = true;
3243 }
3244 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003245 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3246 if (CC_UNLIKELY(err != NO_ERROR)) {
3247 // just in case something goes wrong in SF, return to the
3248 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3250 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003251 break;
3252 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003253 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 }
3255}
3256
Mathias Agopiane57f2922012-08-09 16:29:12 -07003257uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3258{
Jesse Hall9a143922012-10-04 16:29:19 -07003259 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3260 if (dpyIdx < 0)
3261 return 0;
3262
Mathias Agopiane57f2922012-08-09 16:29:12 -07003263 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003264 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003265 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266 const uint32_t what = s.what;
3267 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003268 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003269 disp.surface = s.surface;
3270 flags |= eDisplayTransactionNeeded;
3271 }
3272 }
3273 if (what & DisplayState::eLayerStackChanged) {
3274 if (disp.layerStack != s.layerStack) {
3275 disp.layerStack = s.layerStack;
3276 flags |= eDisplayTransactionNeeded;
3277 }
3278 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003279 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 if (disp.orientation != s.orientation) {
3281 disp.orientation = s.orientation;
3282 flags |= eDisplayTransactionNeeded;
3283 }
3284 if (disp.frame != s.frame) {
3285 disp.frame = s.frame;
3286 flags |= eDisplayTransactionNeeded;
3287 }
3288 if (disp.viewport != s.viewport) {
3289 disp.viewport = s.viewport;
3290 flags |= eDisplayTransactionNeeded;
3291 }
3292 }
Michael Lentine47e45402014-07-18 15:34:25 -07003293 if (what & DisplayState::eDisplaySizeChanged) {
3294 if (disp.width != s.width) {
3295 disp.width = s.width;
3296 flags |= eDisplayTransactionNeeded;
3297 }
3298 if (disp.height != s.height) {
3299 disp.height = s.height;
3300 flags |= eDisplayTransactionNeeded;
3301 }
3302 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003303 }
3304 return flags;
3305}
3306
chaviwca27f252018-02-06 16:46:39 -08003307uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3308 const layer_state_t& s = composerState.state;
3309 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3310
Mathias Agopian13127d82013-03-05 17:47:11 -08003311 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003312 if (layer == nullptr) {
3313 return 0;
3314 }
3315
3316 if (layer->isPendingRemoval()) {
3317 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3318 return 0;
3319 }
3320
3321 uint32_t flags = 0;
3322
3323 const uint32_t what = s.what;
3324 bool geometryAppliesWithResize =
3325 what & layer_state_t::eGeometryAppliesWithResize;
3326 if (what & layer_state_t::ePositionChanged) {
3327 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3328 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003329 }
chaviw8b3871a2017-11-01 17:41:01 -07003330 }
3331 if (what & layer_state_t::eLayerChanged) {
3332 // NOTE: index needs to be calculated before we update the state
3333 const auto& p = layer->getParent();
3334 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003335 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003336 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003337 mCurrentState.layersSortedByZ.removeAt(idx);
3338 mCurrentState.layersSortedByZ.add(layer);
3339 // we need traversal (state changed)
3340 // AND transaction (list changed)
3341 flags |= eTransactionNeeded|eTraversalNeeded;
3342 }
chaviw8b3871a2017-11-01 17:41:01 -07003343 } else {
3344 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003345 flags |= eTransactionNeeded|eTraversalNeeded;
3346 }
3347 }
chaviw8b3871a2017-11-01 17:41:01 -07003348 }
3349 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003350 // NOTE: index needs to be calculated before we update the state
3351 const auto& p = layer->getParent();
3352 if (p == nullptr) {
3353 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3354 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3355 mCurrentState.layersSortedByZ.removeAt(idx);
3356 mCurrentState.layersSortedByZ.add(layer);
3357 // we need traversal (state changed)
3358 // AND transaction (list changed)
3359 flags |= eTransactionNeeded|eTraversalNeeded;
3360 }
3361 } else {
3362 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3363 flags |= eTransactionNeeded|eTraversalNeeded;
3364 }
chaviw8b3871a2017-11-01 17:41:01 -07003365 }
3366 }
3367 if (what & layer_state_t::eSizeChanged) {
3368 if (layer->setSize(s.w, s.h)) {
3369 flags |= eTraversalNeeded;
3370 }
3371 }
3372 if (what & layer_state_t::eAlphaChanged) {
3373 if (layer->setAlpha(s.alpha))
3374 flags |= eTraversalNeeded;
3375 }
3376 if (what & layer_state_t::eColorChanged) {
3377 if (layer->setColor(s.color))
3378 flags |= eTraversalNeeded;
3379 }
3380 if (what & layer_state_t::eMatrixChanged) {
3381 if (layer->setMatrix(s.matrix))
3382 flags |= eTraversalNeeded;
3383 }
3384 if (what & layer_state_t::eTransparentRegionChanged) {
3385 if (layer->setTransparentRegionHint(s.transparentRegion))
3386 flags |= eTraversalNeeded;
3387 }
3388 if (what & layer_state_t::eFlagsChanged) {
3389 if (layer->setFlags(s.flags, s.mask))
3390 flags |= eTraversalNeeded;
3391 }
3392 if (what & layer_state_t::eCropChanged) {
3393 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3394 flags |= eTraversalNeeded;
3395 }
3396 if (what & layer_state_t::eFinalCropChanged) {
3397 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3398 flags |= eTraversalNeeded;
3399 }
3400 if (what & layer_state_t::eLayerStackChanged) {
3401 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3402 // We only allow setting layer stacks for top level layers,
3403 // everything else inherits layer stack from its parent.
3404 if (layer->hasParent()) {
3405 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3406 layer->getName().string());
3407 } else if (idx < 0) {
3408 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3409 "that also does not appear in the top level layer list. Something"
3410 " has gone wrong.", layer->getName().string());
3411 } else if (layer->setLayerStack(s.layerStack)) {
3412 mCurrentState.layersSortedByZ.removeAt(idx);
3413 mCurrentState.layersSortedByZ.add(layer);
3414 // we need traversal (state changed)
3415 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003416 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003417 }
3418 }
3419 if (what & layer_state_t::eDeferTransaction) {
3420 if (s.barrierHandle != nullptr) {
3421 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3422 } else if (s.barrierGbp != nullptr) {
3423 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3424 if (authenticateSurfaceTextureLocked(gbp)) {
3425 const auto& otherLayer =
3426 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3427 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3428 } else {
3429 ALOGE("Attempt to defer transaction to to an"
3430 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003431 }
3432 }
chaviw8b3871a2017-11-01 17:41:01 -07003433 // We don't trigger a traversal here because if no other state is
3434 // changed, we don't want this to cause any more work
3435 }
3436 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003437 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003438 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003439 if (!hadParent) {
3440 mCurrentState.layersSortedByZ.remove(layer);
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003443 }
chaviw8b3871a2017-11-01 17:41:01 -07003444 }
3445 if (what & layer_state_t::eReparentChildren) {
3446 if (layer->reparentChildren(s.reparentHandle)) {
3447 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003448 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 if (what & layer_state_t::eDetachChildren) {
3451 layer->detachChildren();
3452 }
3453 if (what & layer_state_t::eOverrideScalingModeChanged) {
3454 layer->setOverrideScalingMode(s.overrideScalingMode);
3455 // We don't trigger a traversal here because if no other state is
3456 // changed, we don't want this to cause any more work
3457 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003458 return flags;
3459}
3460
chaviwca27f252018-02-06 16:46:39 -08003461void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3462 const layer_state_t& state = composerState.state;
3463 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3464
3465 sp<Layer> layer(client->getLayerUser(state.surface));
3466 if (layer == nullptr) {
3467 return;
3468 }
3469
3470 if (layer->isPendingRemoval()) {
3471 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3472 return;
3473 }
3474
3475 if (state.what & layer_state_t::eDestroySurface) {
3476 removeLayerLocked(mStateLock, layer);
3477 }
3478}
3479
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003480status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003481 const String8& name,
3482 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003483 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003484 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003485 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003487 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003488 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003489 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003490 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003491 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003492
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493 status_t result = NO_ERROR;
3494
3495 sp<Layer> layer;
3496
Cody Northropbc755282017-03-31 12:00:08 -06003497 String8 uniqueName = getUniqueLayerName(name);
3498
Mathias Agopian3165cc22012-08-08 19:42:09 -07003499 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3500 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003501 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003502 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003504
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 break;
chaviw13fdc492017-06-27 12:40:18 -07003506 case ISurfaceComposerClient::eFXSurfaceColor:
3507 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003508 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003509 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003510 break;
3511 default:
3512 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513 break;
3514 }
3515
Dan Stoza7d89d062015-04-30 13:29:25 -07003516 if (result != NO_ERROR) {
3517 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003519
Chia-I Wuab0c3192017-08-01 11:29:00 -07003520 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3521 // TODO b/64227542
3522 if (windowType == 441731) {
3523 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3524 layer->setPrimaryDisplayOnly();
3525 }
3526
Albert Chaulk479c60c2017-01-27 14:21:34 -05003527 layer->setInfo(windowType, ownerUid);
3528
Robert Carr1f0a16a2016-10-24 16:27:39 -07003529 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003530 if (result != NO_ERROR) {
3531 return result;
3532 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003533 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003534
3535 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003536 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537}
3538
Cody Northropbc755282017-03-31 12:00:08 -06003539String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3540{
3541 bool matchFound = true;
3542 uint32_t dupeCounter = 0;
3543
3544 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3545 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3546
3547 // Loop over layers until we're sure there is no matching name
3548 while (matchFound) {
3549 matchFound = false;
3550 mDrawingState.traverseInZOrder([&](Layer* layer) {
3551 if (layer->getName() == uniqueName) {
3552 matchFound = true;
3553 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3554 }
3555 });
3556 }
3557
3558 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3559
3560 return uniqueName;
3561}
3562
David Sodman0c69cad2017-08-21 12:12:51 -07003563status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003564 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3565 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566{
3567 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003568 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003569 case PIXEL_FORMAT_TRANSPARENT:
3570 case PIXEL_FORMAT_TRANSLUCENT:
3571 format = PIXEL_FORMAT_RGBA_8888;
3572 break;
3573 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003574 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575 break;
3576 }
3577
David Sodman0c69cad2017-08-21 12:12:51 -07003578 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3579 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003580 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003581 *handle = layer->getHandle();
3582 *gbp = layer->getProducer();
3583 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003585
David Sodman0c69cad2017-08-21 12:12:51 -07003586 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003587 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588}
3589
chaviw13fdc492017-06-27 12:40:18 -07003590status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003592 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593{
chaviw13fdc492017-06-27 12:40:18 -07003594 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003596 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003597}
3598
Mathias Agopianac9fa422013-02-11 16:40:36 -08003599status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600{
Robert Carr9524cb32017-02-13 11:32:32 -08003601 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003602 status_t err = NO_ERROR;
3603 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003604 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003605 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003606 err = removeLayer(l);
3607 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3608 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003609 }
3610 return err;
3611}
3612
Mathias Agopian13127d82013-03-05 17:47:11 -08003613status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003614{
Mathias Agopian67106042013-03-14 19:18:13 -07003615 // called by ~LayerCleaner() when all references to the IBinder (handle)
3616 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003617 sp<Layer> l = layer.promote();
3618 if (l == nullptr) {
3619 // The layer has already been removed, carry on
3620 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003621 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003622 // If we have a parent, then we can continue to live as long as it does.
3623 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003624}
3625
Mathias Agopianb60314a2012-04-10 22:09:54 -07003626// ---------------------------------------------------------------------------
3627
Andy McFadden13a082e2012-08-24 10:16:42 -07003628void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003629 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003630 Vector<ComposerState> state;
3631 Vector<DisplayState> displays;
3632 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003633 d.what = DisplayState::eDisplayProjectionChanged |
3634 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003635 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003636 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003637 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003638 d.frame.makeInvalid();
3639 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003640 d.width = 0;
3641 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003642 displays.add(d);
3643 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003644 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3645 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003646
David Sodman105b7dc2017-11-04 20:28:14 -07003647 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003648 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003649 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003650
Brian Andersond0010582017-03-07 13:20:31 -08003651 // Use phase of 0 since phase is not known.
3652 // Use latency of 0, which will snap to the ideal latency.
3653 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003654}
3655
3656void SurfaceFlinger::initializeDisplays() {
3657 class MessageScreenInitialized : public MessageBase {
3658 SurfaceFlinger* flinger;
3659 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003660 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003661 virtual bool handler() {
3662 flinger->onInitializeDisplays();
3663 return true;
3664 }
3665 };
3666 sp<MessageBase> msg = new MessageScreenInitialized(this);
3667 postMessageAsync(msg); // we may be called from main thread, use async message
3668}
3669
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003670void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003671 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003672 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3673 this);
3674 int32_t type = hw->getDisplayType();
3675 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003676
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003677 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003678 return;
3679 }
3680
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003681 hw->setPowerMode(mode);
3682 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3683 ALOGW("Trying to set power mode for virtual display");
3684 return;
3685 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003686
Lloyd Pique4d234852018-01-22 17:21:36 -08003687 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003688 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003689 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3690 if (idx < 0) {
3691 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3692 return;
3693 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003694 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003695 }
3696
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003697 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003698 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003700 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3701 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003702 // FIXME: eventthread only knows about the main display right now
3703 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003704 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003708 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003709 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003710
3711 struct sched_param param = {0};
3712 param.sched_priority = 1;
3713 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3714 ALOGW("Couldn't set SCHED_FIFO on display on");
3715 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003716 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003717 // Turn off the display
3718 struct sched_param param = {0};
3719 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3720 ALOGW("Couldn't set SCHED_OTHER on display off");
3721 }
3722
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003723 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3724 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003725 disableHardwareVsync(true); // also cancels any in-progress resync
3726
Mathias Agopiancde87a32012-09-13 14:09:01 -07003727 // FIXME: eventthread only knows about the main display right now
3728 mEventThread->onScreenReleased();
3729 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003730
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 getHwComposer().setPowerMode(type, mode);
3732 mVisibleRegionsDirty = true;
3733 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003734 } else if (mode == HWC_POWER_MODE_DOZE ||
3735 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003736 // Update display while dozing
3737 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003738 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3739 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003740 // FIXME: eventthread only knows about the main display right now
3741 mEventThread->onScreenAcquired();
3742 resyncToHardwareVsync(true);
3743 }
3744 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3745 // Leave display going to doze
3746 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3747 disableHardwareVsync(true); // also cancels any in-progress resync
3748 // FIXME: eventthread only knows about the main display right now
3749 mEventThread->onScreenReleased();
3750 }
3751 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003752 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003753 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003755 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003756 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003757}
3758
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3760 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003761 SurfaceFlinger& mFlinger;
3762 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003764 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 MessageSetPowerMode(SurfaceFlinger& flinger,
3766 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3767 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003768 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003770 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003772 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003773 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 ALOGW("Attempt to set power mode = %d for virtual display",
3775 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003776 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003777 mFlinger.setPowerModeInternal(
3778 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003779 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003780 return true;
3781 }
3782 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003783 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003784 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003785}
3786
3787// ---------------------------------------------------------------------------
3788
Lloyd Pique755e3192018-01-31 16:46:15 -08003789status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3790 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003791 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003792
Mathias Agopianbd115332013-04-18 16:41:04 -07003793 IPCThreadState* ipc = IPCThreadState::self();
3794 const int pid = ipc->getCallingPid();
3795 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003796
Mathias Agopianbd115332013-04-18 16:41:04 -07003797 if ((uid != AID_SHELL) &&
3798 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003799 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003800 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003802 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003803 // (this would indicate SF is stuck, but we want to be able to
3804 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003805 status_t err = mStateLock.timedLock(s2ns(1));
3806 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003807 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003808 result.appendFormat(
3809 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3810 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003811 }
3812
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003813 bool dumpAll = true;
3814 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003815 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003816
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003817 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818 if ((index < numArgs) &&
3819 (args[index] == String16("--list"))) {
3820 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003821 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003822 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003823 }
3824
3825 if ((index < numArgs) &&
3826 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003827 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003828 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003829 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003831
3832 if ((index < numArgs) &&
3833 (args[index] == String16("--latency-clear"))) {
3834 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003835 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003836 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003838
3839 if ((index < numArgs) &&
3840 (args[index] == String16("--dispsync"))) {
3841 index++;
3842 mPrimaryDispSync.dump(result);
3843 dumpAll = false;
3844 }
Dan Stozab90cf072015-03-05 11:05:59 -08003845
3846 if ((index < numArgs) &&
3847 (args[index] == String16("--static-screen"))) {
3848 index++;
3849 dumpStaticScreenStats(result);
3850 dumpAll = false;
3851 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003852
3853 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003854 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003855 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003856 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003857 dumpAll = false;
3858 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003859
3860 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3861 index++;
3862 dumpWideColorInfo(result);
3863 dumpAll = false;
3864 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003865
3866 if ((index < numArgs) &&
3867 (args[index] == String16("--enable-layer-stats"))) {
3868 index++;
3869 mLayerStats.enable();
3870 dumpAll = false;
3871 }
3872
3873 if ((index < numArgs) &&
3874 (args[index] == String16("--disable-layer-stats"))) {
3875 index++;
3876 mLayerStats.disable();
3877 dumpAll = false;
3878 }
3879
3880 if ((index < numArgs) &&
3881 (args[index] == String16("--clear-layer-stats"))) {
3882 index++;
3883 mLayerStats.clear();
3884 dumpAll = false;
3885 }
3886
3887 if ((index < numArgs) &&
3888 (args[index] == String16("--dump-layer-stats"))) {
3889 index++;
3890 mLayerStats.dump(result);
3891 dumpAll = false;
3892 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003893
3894 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3895 index++;
3896 mTimeStats.parseArgs(asProto, args, index, result);
3897 dumpAll = false;
3898 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003900
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003901 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003902 if (asProto) {
3903 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3904 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3905 } else {
3906 dumpAllLocked(args, index, result);
3907 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003908 }
3909
Mathias Agopian9795c422009-08-26 16:36:26 -07003910 if (locked) {
3911 mStateLock.unlock();
3912 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003913 }
3914 write(fd, result.string(), result.size());
3915 return NO_ERROR;
3916}
3917
Dan Stozac7014012014-02-14 15:03:43 -08003918void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3919 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003920{
Robert Carr2047fae2016-11-28 14:09:09 -08003921 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003922 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003923 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003924}
3925
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003927 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003928{
3929 String8 name;
3930 if (index < args.size()) {
3931 name = String8(args[index]);
3932 index++;
3933 }
3934
David Sodman105b7dc2017-11-04 20:28:14 -07003935 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003936 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003937 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003938
3939 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003940 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003941 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003942 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003943 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003944 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003945 }
Robert Carr2047fae2016-11-28 14:09:09 -08003946 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947 }
3948}
3949
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003950void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003951 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003952{
3953 String8 name;
3954 if (index < args.size()) {
3955 name = String8(args[index]);
3956 index++;
3957 }
3958
Robert Carr2047fae2016-11-28 14:09:09 -08003959 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003960 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003961 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962 }
Robert Carr2047fae2016-11-28 14:09:09 -08003963 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003964
Svetoslavd85084b2014-03-20 10:28:31 -07003965 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003966}
3967
Jamie Gennis6547ff42013-07-16 20:12:42 -07003968// This should only be called from the main thread. Otherwise it would need
3969// the lock and should use mCurrentState rather than mDrawingState.
3970void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003971 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003972 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003973 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003974
3975 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3976}
3977
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003978void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003979{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003980 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003981
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003982 if (isLayerTripleBufferingDisabled())
3983 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003984
3985 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003986 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003987 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003988 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003989 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3990 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003991 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003992}
3993
Dan Stozab90cf072015-03-05 11:05:59 -08003994void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3995{
3996 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003997 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3998 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003999 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004000 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004001 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4002 b + 1, bucketTimeSec, percent);
4003 }
David Sodman4a36e932017-11-07 14:29:47 -08004004 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004005 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004006 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004007 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004008 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004009}
4010
Dan Stozae77c7662016-05-13 11:37:28 -07004011void SurfaceFlinger::recordBufferingStats(const char* layerName,
4012 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004013 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4014 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004015 for (const auto& segment : history) {
4016 if (!segment.usedThirdBuffer) {
4017 stats.twoBufferTime += segment.totalTime;
4018 }
4019 if (segment.occupancyAverage < 1.0f) {
4020 stats.doubleBufferedTime += segment.totalTime;
4021 } else if (segment.occupancyAverage < 2.0f) {
4022 stats.tripleBufferedTime += segment.totalTime;
4023 }
4024 ++stats.numSegments;
4025 stats.totalTime += segment.totalTime;
4026 }
4027}
4028
Brian Andersond6927fb2016-07-23 23:37:30 -07004029void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4030 result.appendFormat("Layer frame timestamps:\n");
4031
4032 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4033 const size_t count = currentLayers.size();
4034 for (size_t i=0 ; i<count ; i++) {
4035 currentLayers[i]->dumpFrameEvents(result);
4036 }
4037}
4038
Dan Stozae77c7662016-05-13 11:37:28 -07004039void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4040 result.append("Buffering stats:\n");
4041 result.append(" [Layer name] <Active time> <Two buffer> "
4042 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004043 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004044 typedef std::tuple<std::string, float, float, float> BufferTuple;
4045 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004046 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004047 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004048 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004049 if (stats.numSegments == 0) {
4050 continue;
4051 }
4052 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4053 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4054 stats.totalTime;
4055 float doubleBufferRatio = static_cast<float>(
4056 stats.doubleBufferedTime) / stats.totalTime;
4057 float tripleBufferRatio = static_cast<float>(
4058 stats.tripleBufferedTime) / stats.totalTime;
4059 sorted.insert({activeTime, {name, twoBufferRatio,
4060 doubleBufferRatio, tripleBufferRatio}});
4061 }
4062 for (const auto& sortedPair : sorted) {
4063 float activeTime = sortedPair.first;
4064 const BufferTuple& values = sortedPair.second;
4065 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4066 std::get<0>(values).c_str(), activeTime,
4067 std::get<1>(values), std::get<2>(values),
4068 std::get<3>(values));
4069 }
4070 result.append("\n");
4071}
4072
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004073void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4074 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004075 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004076
4077 // TODO: print out if wide-color mode is active or not
4078
4079 for (size_t d = 0; d < mDisplays.size(); d++) {
4080 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4081 int32_t hwcId = displayDevice->getHwcDisplayId();
4082 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4083 continue;
4084 }
4085
4086 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004087 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004088 for (auto&& mode : modes) {
4089 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4090 }
4091
Peiyong Lina52f0292018-03-14 17:26:31 -07004092 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004093 result.appendFormat(" Current color mode: %s (%d)\n",
4094 decodeColorMode(currentMode).c_str(), currentMode);
4095 }
4096 result.append("\n");
4097}
4098
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004099LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004100 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004101 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4102 const State& state = useDrawing ? mDrawingState : mCurrentState;
4103 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004104 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004105 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004106 });
4107
4108 return layersProto;
4109}
4110
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004111LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4112 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004113 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004114
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004115 SizeProto* resolution = layersProto.mutable_resolution();
4116 resolution->set_w(displayDevice->getWidth());
4117 resolution->set_h(displayDevice->getHeight());
4118
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004119 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4120 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4121 layersProto.set_global_transform(
4122 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4123
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004124 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004125 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004126 LayerProto* layerProto = layersProto.add_layers();
4127 layer->writeToProto(layerProto, hwcId);
4128 }
4129 });
4130
4131 return layersProto;
4132}
4133
Mathias Agopian74d211a2013-04-22 16:55:35 +02004134void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4135 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004137 bool colorize = false;
4138 if (index < args.size()
4139 && (args[index] == String16("--color"))) {
4140 colorize = true;
4141 index++;
4142 }
4143
4144 Colorizer colorizer(colorize);
4145
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146 // figure out if we're stuck somewhere
4147 const nsecs_t now = systemTime();
4148 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4149 const nsecs_t inTransaction(mDebugInTransaction);
4150 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4151 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4152
4153 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004154 * Dump library configuration.
4155 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004156
4157 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004158 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004159 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004160 appendSfConfigString(result);
4161 appendUiConfigString(result);
4162 appendGuiConfigString(result);
4163 result.append("\n");
4164
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004165 result.append("\nWide-Color information:\n");
4166 dumpWideColorInfo(result);
4167
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004168 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004169 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004170 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004171 result.append(SyncFeatures::getInstance().toString());
4172 result.append("\n");
4173
David Sodman105b7dc2017-11-04 20:28:14 -07004174 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004175
Andy McFadden41d67d72014-04-25 16:58:34 -07004176 colorizer.bold(result);
4177 result.append("DispSync configuration: ");
4178 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004179 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4180 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4181 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004182 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004183 result.append("\n");
4184
Dan Stozab90cf072015-03-05 11:05:59 -08004185 // Dump static screen stats
4186 result.append("\n");
4187 dumpStaticScreenStats(result);
4188 result.append("\n");
4189
Dan Stozae77c7662016-05-13 11:37:28 -07004190 dumpBufferingStats(result);
4191
Andy McFadden4803b742012-09-24 19:07:20 -07004192 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004193 * Dump the visible layer list
4194 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004195 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004196 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004197 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4198 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004199 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004200
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004201 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004202 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004203 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004204 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004205
4206 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004207 * Dump Display state
4208 */
4209
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004210 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004211 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004213 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4214 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004215 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004216 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004217 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004218
4219 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220 * Dump SurfaceFlinger global state
4221 */
4222
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004223 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004224 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004225 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004226
Mathias Agopian888c8222012-08-04 21:10:38 -07004227 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004228 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004229
David Sodmanbc815282017-11-05 18:57:52 -08004230 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004232 if (hw) {
4233 hw->undefinedRegion.dump(result, "undefinedRegion");
4234 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4235 hw->getOrientation(), hw->isDisplayOn());
4236 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004237 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004238 " last eglSwapBuffers() time: %f us\n"
4239 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004240 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004241 " refresh-rate : %f fps\n"
4242 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004243 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004244 " gpu_to_cpu_unsupported : %d\n"
4245 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 mLastSwapBufferTime/1000.0,
4247 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004248 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004249 1e9 / activeConfig->getVsyncPeriod(),
4250 activeConfig->getDpiX(),
4251 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004252 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004253
Mathias Agopian74d211a2013-04-22 16:55:35 +02004254 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004255 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259
4260 /*
4261 * VSYNC state
4262 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004263 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004264 result.append("\n");
4265
4266 /*
4267 * HWC layer minidump
4268 */
4269 for (size_t d = 0; d < mDisplays.size(); d++) {
4270 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4271 int32_t hwcId = displayDevice->getHwcDisplayId();
4272 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4273 continue;
4274 }
4275
4276 result.appendFormat("Display %d HWC layers:\n", hwcId);
4277 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004278 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004279 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004280 });
Dan Stozae22aec72016-08-01 13:20:59 -07004281 result.append("\n");
4282 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004283
4284 /*
4285 * Dump HWComposer state
4286 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004288 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004290 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004291 result.appendFormat(" h/w composer %s\n",
4292 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004293 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004294
4295 /*
4296 * Dump gralloc state
4297 */
4298 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4299 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004300
4301 /*
4302 * Dump VrFlinger state if in use.
4303 */
4304 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4305 result.append("VrFlinger state:\n");
4306 result.append(mVrFlinger->Dump().c_str());
4307 result.append("\n");
4308 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004309}
4310
Mathias Agopian13127d82013-03-05 17:47:11 -08004311const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004312SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004313 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004314 wp<IBinder> dpy;
4315 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4316 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4317 dpy = mDisplays.keyAt(i);
4318 break;
4319 }
4320 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004321 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004322 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4323 // Just use the primary display so we have something to return
4324 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4325 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004326 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004327}
4328
Keun young Park63f165f2012-08-31 10:53:36 -07004329bool SurfaceFlinger::startDdmConnection()
4330{
4331 void* libddmconnection_dso =
4332 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4333 if (!libddmconnection_dso) {
4334 return false;
4335 }
4336 void (*DdmConnection_start)(const char* name);
4337 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004338 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004339 if (!DdmConnection_start) {
4340 dlclose(libddmconnection_dso);
4341 return false;
4342 }
4343 (*DdmConnection_start)(getServiceName());
4344 return true;
4345}
4346
Chia-I Wu28f320b2018-05-03 11:02:56 -07004347void SurfaceFlinger::updateColorMatrixLocked() {
4348 mat4 colorMatrix;
4349 if (mGlobalSaturationFactor != 1.0f) {
4350 // Rec.709 luma coefficients
4351 float3 luminance{0.213f, 0.715f, 0.072f};
4352 luminance *= 1.0f - mGlobalSaturationFactor;
4353 mat4 saturationMatrix = mat4(
4354 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4355 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4356 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4357 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4358 );
4359 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4360 } else {
4361 colorMatrix = mClientColorMatrix * mDaltonizer();
4362 }
4363
4364 if (mCurrentState.colorMatrix != colorMatrix) {
4365 mCurrentState.colorMatrix = colorMatrix;
4366 mCurrentState.colorMatrixChanged = true;
4367 setTransactionFlags(eTransactionNeeded);
4368 }
4369}
4370
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004371status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 switch (code) {
4373 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004374 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004375 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004376 case CLEAR_ANIMATION_FRAME_STATS:
4377 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004378 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004379 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004380 case ENABLE_VSYNC_INJECTIONS:
4381 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004382 {
4383 // codes that require permission check
4384 IPCThreadState* ipc = IPCThreadState::self();
4385 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004386 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004387 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004388 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004389 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004390 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004391 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004392 break;
4393 }
Robert Carr1db73f62016-12-21 12:58:51 -08004394 /*
4395 * Calling setTransactionState is safe, because you need to have been
4396 * granted a reference to Client* and Handle* to do anything with it.
4397 *
4398 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4399 */
4400 case SET_TRANSACTION_STATE:
4401 case CREATE_SCOPED_CONNECTION:
4402 {
4403 return OK;
4404 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004405 case CAPTURE_SCREEN:
4406 {
4407 // codes that require permission check
4408 IPCThreadState* ipc = IPCThreadState::self();
4409 const int pid = ipc->getCallingPid();
4410 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004411 if ((uid != AID_GRAPHICS) &&
4412 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004413 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004414 return PERMISSION_DENIED;
4415 }
4416 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004417 }
chaviwa76b2712017-09-20 12:02:26 -07004418 case CAPTURE_LAYERS: {
4419 IPCThreadState* ipc = IPCThreadState::self();
4420 const int pid = ipc->getCallingPid();
4421 const int uid = ipc->getCallingUid();
4422 if ((uid != AID_GRAPHICS) &&
4423 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4424 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4425 return PERMISSION_DENIED;
4426 }
4427 break;
4428 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004429 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004430 return OK;
4431}
4432
4433status_t SurfaceFlinger::onTransact(
4434 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4435{
4436 status_t credentialCheck = CheckTransactCodeCredentials(code);
4437 if (credentialCheck != OK) {
4438 return credentialCheck;
4439 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004440
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4442 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004443 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004444 IPCThreadState* ipc = IPCThreadState::self();
4445 const int uid = ipc->getCallingUid();
4446 if (CC_UNLIKELY(uid != AID_SYSTEM
4447 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004448 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004449 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004450 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004451 return PERMISSION_DENIED;
4452 }
4453 int n;
4454 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004455 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004456 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004457 return NO_ERROR;
4458 case 1002: // SHOW_UPDATES
4459 n = data.readInt32();
4460 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004461 invalidateHwcGeometry();
4462 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004463 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004465 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004466 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004467 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004468 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004469 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004470 setTransactionFlags(
4471 eTransactionNeeded|
4472 eDisplayTransactionNeeded|
4473 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004474 return NO_ERROR;
4475 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004476 case 1006:{ // send empty update
4477 signalRefresh();
4478 return NO_ERROR;
4479 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004480 case 1008: // toggle use of hw composer
4481 n = data.readInt32();
4482 mDebugDisableHWC = n ? 1 : 0;
4483 invalidateHwcGeometry();
4484 repaintEverything();
4485 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004486 case 1009: // toggle use of transform hint
4487 n = data.readInt32();
4488 mDebugDisableTransformHint = n ? 1 : 0;
4489 invalidateHwcGeometry();
4490 repaintEverything();
4491 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004492 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004493 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004494 reply->writeInt32(0);
4495 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004496 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004497 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004498 return NO_ERROR;
4499 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004500 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004501 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004502 return NO_ERROR;
4503 }
4504 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004505 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004506 // daltonize
4507 n = data.readInt32();
4508 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004509 case 1:
4510 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4511 break;
4512 case 2:
4513 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4514 break;
4515 case 3:
4516 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4517 break;
4518 default:
4519 mDaltonizer.setType(ColorBlindnessType::None);
4520 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004521 }
4522 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004523 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004524 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004525 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004526 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004527
4528 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004530 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004531 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004532 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004533 // apply a color matrix
4534 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004535 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004536 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004537 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004538 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004539 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004540 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004541 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004542 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004543 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004544 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004545
4546 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4547 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004548 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004549 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4550 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4551 }
4552
Chia-I Wu28f320b2018-05-03 11:02:56 -07004553 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004554 return NO_ERROR;
4555 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004556 // This is an experimental interface
4557 // Needs to be shifted to proper binder interface when we productize
4558 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004559 n = data.readInt32();
4560 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004561 return NO_ERROR;
4562 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004563 case 1017: {
4564 n = data.readInt32();
4565 mForceFullDamage = static_cast<bool>(n);
4566 return NO_ERROR;
4567 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004568 case 1018: { // Modify Choreographer's phase offset
4569 n = data.readInt32();
4570 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4571 return NO_ERROR;
4572 }
4573 case 1019: { // Modify SurfaceFlinger's phase offset
4574 n = data.readInt32();
4575 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4576 return NO_ERROR;
4577 }
Irvel468051e2016-06-13 16:44:44 -07004578 case 1020: { // Layer updates interceptor
4579 n = data.readInt32();
4580 if (n) {
4581 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004582 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004583 }
4584 else{
4585 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004586 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004587 }
4588 return NO_ERROR;
4589 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004590 case 1021: { // Disable HWC virtual displays
4591 n = data.readInt32();
4592 mUseHwcVirtualDisplays = !n;
4593 return NO_ERROR;
4594 }
Romain Guy0147a172017-06-01 13:53:56 -07004595 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004596 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004597 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004598
Chia-I Wu28f320b2018-05-03 11:02:56 -07004599 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004600 return NO_ERROR;
4601 }
Romain Guy54f154a2017-10-24 21:40:32 +01004602 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004603 int32_t value = data.readInt32();
4604 if (value > 2) {
4605 return BAD_VALUE;
4606 }
4607 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4608 return BAD_VALUE;
4609 }
Romain Guy54f154a2017-10-24 21:40:32 +01004610
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004611 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004612 invalidateHwcGeometry();
4613 repaintEverything();
4614 return NO_ERROR;
4615 }
4616 case 1024: { // Is wide color gamut rendering/color management supported?
4617 reply->writeBool(hasWideColorDisplay);
4618 return NO_ERROR;
4619 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004620 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004621 n = data.readInt32();
4622 if (n) {
4623 ALOGV("LayerTracing enabled");
4624 mTracing.enable();
4625 doTracing("tracing.enable");
4626 reply->writeInt32(NO_ERROR);
4627 } else {
4628 ALOGV("LayerTracing disabled");
4629 status_t err = mTracing.disable();
4630 reply->writeInt32(err);
4631 }
4632 return NO_ERROR;
4633 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004634 case 1026: { // Get layer tracing status
4635 reply->writeBool(mTracing.isEnabled());
4636 return NO_ERROR;
4637 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004638 // Is a DisplayColorSetting supported?
4639 case 1027: {
4640 int32_t value = data.readInt32();
4641 switch (value) {
4642 case 0:
4643 reply->writeBool(hasWideColorDisplay);
4644 return NO_ERROR;
4645 case 1:
4646 reply->writeBool(true);
4647 return NO_ERROR;
4648 case 2:
4649 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4650 return NO_ERROR;
4651 default:
4652 return BAD_VALUE;
4653 }
4654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 }
4656 }
4657 return err;
4658}
4659
Steven Thomas6d8110b2017-08-31 18:24:21 -07004660void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004661 android_atomic_or(1, &mRepaintEverything);
4662 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004663}
4664
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004665// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4666class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004667public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4669 ~WindowDisconnector() {
4670 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004671 }
4672
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004673private:
4674 ANativeWindow* mWindow;
4675 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004676};
4677
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004678status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4679 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4680 int32_t minLayerZ, int32_t maxLayerZ,
4681 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004682 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004683 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004684
chaviwa76b2712017-09-20 12:02:26 -07004685 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4686
4687 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004688 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4689
chaviwa76b2712017-09-20 12:02:26 -07004690 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4691
4692 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4693 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004694 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004695}
4696
4697status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004698 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004699 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004700 ATRACE_CALL();
4701
4702 class LayerRenderArea : public RenderArea {
4703 public:
Robert Carr578038f2018-03-09 12:25:24 -08004704 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4705 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004706 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004707 mLayer(layer),
4708 mCrop(crop),
4709 mFlinger(flinger),
4710 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004711 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004712 Rect getBounds() const override {
4713 const Layer::State& layerState(mLayer->getDrawingState());
4714 return Rect(layerState.active.w, layerState.active.h);
4715 }
4716 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4717 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4718 bool isSecure() const override { return false; }
4719 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004720 Rect getSourceCrop() const override {
4721 if (mCrop.isEmpty()) {
4722 return getBounds();
4723 } else {
4724 return mCrop;
4725 }
4726 }
Robert Carr578038f2018-03-09 12:25:24 -08004727 class ReparentForDrawing {
4728 public:
4729 const sp<Layer>& oldParent;
4730 const sp<Layer>& newParent;
4731
4732 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4733 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004734 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004735 }
Robert Carr15eae092018-03-23 13:43:53 -07004736 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004737 };
4738
4739 void render(std::function<void()> drawLayers) override {
4740 if (!mChildrenOnly) {
4741 mTransform = mLayer->getTransform().inverse();
4742 drawLayers();
4743 } else {
4744 Rect bounds = getBounds();
4745 screenshotParentLayer =
4746 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4747 bounds.getWidth(), bounds.getHeight(), 0);
4748
4749 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4750 drawLayers();
4751 }
4752 }
chaviwa76b2712017-09-20 12:02:26 -07004753
chaviwa76b2712017-09-20 12:02:26 -07004754 private:
chaviw7206d492017-11-10 16:16:12 -08004755 const sp<Layer> mLayer;
4756 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004757
4758 // In the "childrenOnly" case we reparent the children to a screenshot
4759 // layer which has no properties set and which does not draw.
4760 sp<ContainerLayer> screenshotParentLayer;
4761 Transform mTransform;
4762
4763 SurfaceFlinger* mFlinger;
4764 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004765 };
4766
4767 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4768 auto parent = layerHandle->owner.promote();
4769
chaviw7206d492017-11-10 16:16:12 -08004770 if (parent == nullptr || parent->isPendingRemoval()) {
4771 ALOGE("captureLayers called with a removed parent");
4772 return NAME_NOT_FOUND;
4773 }
4774
Robert Carr578038f2018-03-09 12:25:24 -08004775 const int uid = IPCThreadState::self()->getCallingUid();
4776 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4777 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4778 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4779 return PERMISSION_DENIED;
4780 }
4781
chaviw7206d492017-11-10 16:16:12 -08004782 Rect crop(sourceCrop);
4783 if (sourceCrop.width() <= 0) {
4784 crop.left = 0;
4785 crop.right = parent->getCurrentState().active.w;
4786 }
4787
4788 if (sourceCrop.height() <= 0) {
4789 crop.top = 0;
4790 crop.bottom = parent->getCurrentState().active.h;
4791 }
4792
4793 int32_t reqWidth = crop.width() * frameScale;
4794 int32_t reqHeight = crop.height() * frameScale;
4795
Robert Carr578038f2018-03-09 12:25:24 -08004796 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004797
Robert Carr578038f2018-03-09 12:25:24 -08004798 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004799 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4800 if (!layer->isVisible()) {
4801 return;
Robert Carr578038f2018-03-09 12:25:24 -08004802 } else if (childrenOnly && layer == parent.get()) {
4803 return;
chaviwa76b2712017-09-20 12:02:26 -07004804 }
4805 visitor(layer);
4806 });
4807 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004808 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004809}
4810
4811status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4812 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004813 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004814 bool useIdentityTransform) {
4815 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004816
chaviwa76b2712017-09-20 12:02:26 -07004817 renderArea.updateDimensions();
4818
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004819 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4820 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4821 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4822 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004823
4824 // This mutex protects syncFd and captureResult for communication of the return values from the
4825 // main thread back to this Binder thread
4826 std::mutex captureMutex;
4827 std::condition_variable captureCondition;
4828 std::unique_lock<std::mutex> captureLock(captureMutex);
4829 int syncFd = -1;
4830 std::optional<status_t> captureResult;
4831
Robert Carr03480e22018-01-04 16:02:06 -08004832 const int uid = IPCThreadState::self()->getCallingUid();
4833 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4834
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004835 sp<LambdaMessage> message = new LambdaMessage([&]() {
4836 // If there is a refresh pending, bug out early and tell the binder thread to try again
4837 // after the refresh.
4838 if (mRefreshPending) {
4839 ATRACE_NAME("Skipping screenshot for now");
4840 std::unique_lock<std::mutex> captureLock(captureMutex);
4841 captureResult = std::make_optional<status_t>(EAGAIN);
4842 captureCondition.notify_one();
4843 return;
4844 }
4845
4846 status_t result = NO_ERROR;
4847 int fd = -1;
4848 {
4849 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004850 renderArea.render([&]() {
4851 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4852 useIdentityTransform, forSystem, &fd);
4853 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004854 }
4855
4856 {
4857 std::unique_lock<std::mutex> captureLock(captureMutex);
4858 syncFd = fd;
4859 captureResult = std::make_optional<status_t>(result);
4860 captureCondition.notify_one();
4861 }
4862 });
4863
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004864 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004865 if (result == NO_ERROR) {
4866 captureCondition.wait(captureLock, [&]() { return captureResult; });
4867 while (*captureResult == EAGAIN) {
4868 captureResult.reset();
4869 result = postMessageAsync(message);
4870 if (result != NO_ERROR) {
4871 return result;
4872 }
4873 captureCondition.wait(captureLock, [&]() { return captureResult; });
4874 }
4875 result = *captureResult;
4876 }
4877
4878 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004879 sync_wait(syncFd, -1);
4880 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004882
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004883 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004884}
4885
chaviwa76b2712017-09-20 12:02:26 -07004886void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4887 TraverseLayersFunction traverseLayers, bool yswap,
4888 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004889 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004890
Lloyd Pique144e1162017-12-20 16:44:52 -08004891 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004892
4893 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004894 const auto raWidth = renderArea.getWidth();
4895 const auto raHeight = renderArea.getHeight();
4896
4897 const auto reqWidth = renderArea.getReqWidth();
4898 const auto reqHeight = renderArea.getReqHeight();
4899 Rect sourceCrop = renderArea.getSourceCrop();
4900
4901 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4902 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004903
Dan Stozac1879002014-05-22 15:59:05 -07004904 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004905 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004906 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004907 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004908 }
4909
4910 // ensure that sourceCrop is inside screen
4911 if (sourceCrop.left < 0) {
4912 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4913 }
chaviwa76b2712017-09-20 12:02:26 -07004914 if (sourceCrop.right > raWidth) {
4915 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004916 }
4917 if (sourceCrop.top < 0) {
4918 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4919 }
chaviwa76b2712017-09-20 12:02:26 -07004920 if (sourceCrop.bottom > raHeight) {
4921 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004922 }
4923
Chia-I Wu36574d92018-05-16 10:54:36 -07004924 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4925 engine.setOutputDataSpace(Dataspace::SRGB);
4926 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004927
Mathias Agopian180f10d2013-04-10 22:55:41 -07004928 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004929 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004930
4931 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004932 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4933 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004934 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004935
chaviw50da5042018-04-09 13:49:37 -07004936 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004937 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004938 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004939
chaviwa76b2712017-09-20 12:02:26 -07004940 traverseLayers([&](Layer* layer) {
4941 if (filtering) layer->setFiltering(true);
4942 layer->draw(renderArea, useIdentityTransform);
4943 if (filtering) layer->setFiltering(false);
4944 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004945}
4946
chaviwa76b2712017-09-20 12:02:26 -07004947status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4948 TraverseLayersFunction traverseLayers,
4949 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004950 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004951 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004952 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004953 ATRACE_CALL();
4954
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004955 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004956
4957 traverseLayers([&](Layer* layer) {
4958 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4959 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004960
Robert Carr03480e22018-01-04 16:02:06 -08004961 // We allow the system server to take screenshots of secure layers for
4962 // use in situations like the Screen-rotation animation and place
4963 // the impetus on WindowManager to not persist them.
4964 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004965 ALOGW("FB is protected: PERMISSION_DENIED");
4966 return PERMISSION_DENIED;
4967 }
4968
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004969 // this binds the given EGLImage as a framebuffer for the
4970 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004971 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004972 if (bufferBond.getStatus() != NO_ERROR) {
4973 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004974 return INVALID_OPERATION;
4975 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004976
Dan Stozaabcda352017-06-01 14:37:39 -07004977 // this will in fact render into our dequeued buffer
4978 // via an FBO, which means we didn't have to create
4979 // an EGLSurface and therefore we're not
4980 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004981 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004982
Dan Stozaabcda352017-06-01 14:37:39 -07004983 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004984 getRenderEngine().finish();
4985 *outSyncFd = -1;
4986
chaviwa76b2712017-09-20 12:02:26 -07004987 const auto reqWidth = renderArea.getReqWidth();
4988 const auto reqHeight = renderArea.getReqHeight();
4989
Dan Stozaabcda352017-06-01 14:37:39 -07004990 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4991 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004992 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004993 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004994 } else {
4995 base::unique_fd syncFd = getRenderEngine().flush();
4996 if (syncFd < 0) {
4997 getRenderEngine().finish();
4998 }
4999 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005000 }
5001
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005002 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005003}
5004
Mathias Agopiand5556842013-09-19 17:08:37 -07005005void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005006 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005007 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005008 for (size_t y = 0; y < h; y++) {
5009 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5010 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005011 if (p[x] != 0xFF000000) return;
5012 }
5013 }
chaviwa76b2712017-09-20 12:02:26 -07005014 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005015
Robert Carr2047fae2016-11-28 14:09:09 -08005016 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005017 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005018 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005019 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5020 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5021 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5022 static_cast<float>(state.color.a));
5023 i++;
5024 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005025 }
5026}
5027
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005028// ---------------------------------------------------------------------------
5029
Dan Stoza412903f2017-04-27 13:42:17 -07005030void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5031 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005032}
5033
Dan Stoza412903f2017-04-27 13:42:17 -07005034void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5035 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005036}
5037
chaviwa76b2712017-09-20 12:02:26 -07005038void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5039 int32_t maxLayerZ,
5040 const LayerVector::Visitor& visitor) {
5041 // We loop through the first level of layers without traversing,
5042 // as we need to interpret min/max layer Z in the top level Z space.
5043 for (const auto& layer : mDrawingState.layersSortedByZ) {
5044 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5045 continue;
5046 }
5047 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005048 // relative layers are traversed in Layer::traverseInZOrder
5049 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005050 continue;
5051 }
5052 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005053 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5054 return;
5055 }
chaviwa76b2712017-09-20 12:02:26 -07005056 if (!layer->isVisible()) {
5057 return;
5058 }
5059 visitor(layer);
5060 });
5061 }
5062}
5063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005065
5066
5067#if defined(__gl_h_)
5068#error "don't include gl/gl.h in this file"
5069#endif
5070
5071#if defined(__gl2_h_)
5072#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005073#endif