blob: 84893a7c2e268e14cbb74a928dbbb8db678adbe4 [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");
638 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800643
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800644 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
645 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800646 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700647 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648
Steven Thomasb02664d2017-07-26 18:48:28 -0700649 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800650 getBE().mRenderEngine =
651 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
652 hasWideColorDisplay
653 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
654 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800655 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700656
657 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
658 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800659 getBE().mHwc.reset(
660 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700661 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800662 // Process any initial hotplug and resulting display changes.
663 processDisplayHotplugEventsLocked();
664 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
665 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800666
Lloyd Piquefcd86612017-12-14 17:15:36 -0800667 // make the default display GLContext current so that we can create textures
668 // when creating Layers (which may happens before we render something)
669 getDefaultDisplayDeviceLocked()->makeCurrent();
670
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 if (useVrFlinger) {
672 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700673 // This callback is called from the vr flinger dispatch thread. We
674 // need to call signalTransaction(), which requires holding
675 // mStateLock when we're not on the main thread. Acquiring
676 // mStateLock from the vr flinger dispatch thread might trigger a
677 // deadlock in surface flinger (see b/66916578), so post a message
678 // to be handled on the main thread instead.
679 sp<LambdaMessage> message = new LambdaMessage([=]() {
680 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
681 mVrFlingerRequestsDisplay = requestDisplay;
682 signalTransaction();
683 });
684 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 };
David Sodman105b7dc2017-11-04 20:28:14 -0700686 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
687 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800688 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 if (!mVrFlinger) {
690 ALOGE("Failed to start vrflinger");
691 }
692 }
693
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800694 mEventControlThread = std::make_unique<impl::EventControlThread>(
695 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700696
Mathias Agopian92a979a2012-08-02 18:32:23 -0700697 // initialize our drawing state
698 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700699
Andy McFadden13a082e2012-08-24 10:16:42 -0700700 // set initial conditions (e.g. unblank default device)
701 initializeDisplays();
702
David Sodmanbc815282017-11-05 18:57:52 -0800703 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700704
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705 // Inform native graphics APIs whether the present timestamp is supported:
706 if (getHwComposer().hasCapability(
707 HWC2::Capability::PresentFenceIsNotReliable)) {
708 mStartPropertySetThread = new StartPropertySetThread(false);
709 } else {
710 mStartPropertySetThread = new StartPropertySetThread(true);
711 }
712
713 if (mStartPropertySetThread->Start() != NO_ERROR) {
714 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800716
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800717 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
718 Dataspace::SRGB_LINEAR);
719
Dan Stoza9e56aa02015-11-02 13:00:03 -0800720 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700721}
722
Romain Guy11d63f42017-07-20 12:47:14 -0700723void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 Mutex::Autolock _l(mStateLock);
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726 char value[PROPERTY_VALUE_MAX];
727
728 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800729 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700730 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100732
733 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
735 ALOGV("Display Color Setting is set to %s.",
736 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800750 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700785 if (!getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
788 }
789 return NO_ERROR;
790}
791
Dan Stoza7f7da322014-05-02 15:26:25 -0700792status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
793 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800794 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 return BAD_VALUE;
796 }
797
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500798 if (!display.get())
799 return NAME_NOT_FOUND;
800
Jesse Hall692c7232012-11-08 15:41:56 -0800801 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700802 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800803 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700804 type = i;
805 break;
806 }
807 }
808
809 if (type < 0) {
810 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700811 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 // TODO: Not sure if display density should handled by SF any longer
814 class Density {
815 static int getDensityFromProperty(char const* propName) {
816 char property[PROPERTY_VALUE_MAX];
817 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800818 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 density = atoi(property);
820 }
821 return density;
822 }
823 public:
824 static int getEmuDensity() {
825 return getDensityFromProperty("qemu.sf.lcd_density"); }
826 static int getBuildDensity() {
827 return getDensityFromProperty("ro.sf.lcd_density"); }
828 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700829
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Steven Thomas6d8110b2017-08-31 18:24:21 -0700832 ConditionalLock _l(mStateLock,
833 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 DisplayInfo info = DisplayInfo();
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 float xdpi = hwConfig->getDpiX();
838 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
840 if (type == DisplayDevice::DISPLAY_PRIMARY) {
841 // The density of the device is provided by a build property
842 float density = Density::getBuildDensity() / 160.0f;
843 if (density == 0) {
844 // the build doesn't provide a density -- this is wrong!
845 // use xdpi instead
846 ALOGE("ro.sf.lcd_density must be defined as a build property");
847 density = xdpi / 160.0f;
848 }
849 if (Density::getEmuDensity()) {
850 // if "qemu.sf.lcd_density" is specified, it overrides everything
851 xdpi = ydpi = density = Density::getEmuDensity();
852 density /= 160.0f;
853 }
854 info.density = density;
855
856 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700857 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800858 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 } else {
860 // TODO: where should this value come from?
861 static const int TV_DENSITY = 213;
862 info.density = TV_DENSITY / 160.0f;
863 info.orientation = 0;
864 }
865
Dan Stoza9e56aa02015-11-02 13:00:03 -0800866 info.w = hwConfig->getWidth();
867 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 info.xdpi = xdpi;
869 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900871 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872
Andy McFadden91b2ca82014-06-13 14:04:23 -0700873 // This is how far in advance a buffer must be queued for
874 // presentation at a given time. If you want a buffer to appear
875 // on the screen at time N, you must submit the buffer before
876 // (N - presentationDeadline).
877 //
878 // Normally it's one full refresh period (to give SF a chance to
879 // latch the buffer), but this can be reduced by configuring a
880 // DispSync offset. Any additional delays introduced by the hardware
881 // composer or panel must be accounted for here.
882 //
883 // We add an additional 1ms to allow for processing time and
884 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800886 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700887
888 // All non-virtual displays are currently considered secure.
889 info.secure = true;
890
Michael Wright28f24d02016-07-12 13:30:53 -0700891 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700892 }
893
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 return NO_ERROR;
895}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700896
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800897status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700898 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800899 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700900 return BAD_VALUE;
901 }
902
903 // FIXME for now we always return stats for the primary display
904 memset(stats, 0, sizeof(*stats));
905 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
906 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
907 return NO_ERROR;
908}
909
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800911 if (display == nullptr) {
912 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800913 return BAD_VALUE;
914 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700915
916 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800917 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700918 return device->getActiveConfig();
919 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700920
Dan Stoza24a42e92015-03-09 10:04:11 -0700921 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700924void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
925 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
926 this);
927 int32_t type = hw->getDisplayType();
928 int currentMode = hw->getActiveConfig();
929
930 if (mode == currentMode) {
931 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
932 return;
933 }
934
935 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
936 ALOGW("Trying to set config for virtual display");
937 return;
938 }
939
940 hw->setActiveConfig(mode);
941 getHwComposer().setActiveConfig(type, mode);
942}
943
944status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
945 class MessageSetActiveConfig: public MessageBase {
946 SurfaceFlinger& mFlinger;
947 sp<IBinder> mDisplay;
948 int mMode;
949 public:
950 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
951 int mode) :
952 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
953 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700954 Vector<DisplayInfo> configs;
955 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700956 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700957 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700958 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700959 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700960 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800962 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700964 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700965 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
966 ALOGW("Attempt to set active config = %d for virtual display",
967 mMode);
968 } else {
969 mFlinger.setActiveConfigInternal(hw, mMode);
970 }
971 return true;
972 }
973 };
974 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
975 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700976 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700977}
Michael Wright28f24d02016-07-12 13:30:53 -0700978status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700979 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
981 return BAD_VALUE;
982 }
983
984 if (!display.get()) {
985 return NAME_NOT_FOUND;
986 }
987
988 int32_t type = NAME_NOT_FOUND;
989 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
990 if (display == mBuiltinDisplays[i]) {
991 type = i;
992 break;
993 }
994 }
995
996 if (type < 0) {
997 return type;
998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
1004 modes = getHwComposer().getColorModes(type);
1005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001013 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001014 if (device != nullptr) {
1015 return device->getActiveColorMode();
1016 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001017 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001018}
1019
1020void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001021 ColorMode mode, Dataspace dataSpace,
1022 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001023 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001025 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001027
Peiyong Lin38e9a562018-04-10 16:24:20 -07001028 if (mode == currentMode && dataSpace == currentDataSpace &&
1029 renderIntent == currentRenderIntent) {
1030 return;
1031 }
1032
1033 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1034 ALOGW("Trying to set config for virtual display");
1035 return;
1036 }
1037
1038 hw->setActiveColorMode(mode);
1039 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001040 hw->setActiveRenderIntent(renderIntent);
1041 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1042
1043 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1044 decodeColorMode(mode).c_str(), mode,
1045 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1046 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001047}
1048
1049
1050status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001051 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001052 class MessageSetActiveColorMode: public MessageBase {
1053 SurfaceFlinger& mFlinger;
1054 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001056 public:
1057 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001059 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1060 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001061 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001062 mFlinger.getDisplayColorModes(mDisplay, &modes);
1063 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001064 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001065 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1066 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001067 return true;
1068 }
1069 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1070 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001071 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1072 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001073 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001074 ALOGW("Attempt to set active color mode %s %d for virtual display",
1075 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001076 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001077 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1078 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001079 }
1080 return true;
1081 }
1082 };
1083 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1084 postMessageSync(msg);
1085 return NO_ERROR;
1086}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001087
Svetoslavd85084b2014-03-20 10:28:31 -07001088status_t SurfaceFlinger::clearAnimationFrameStats() {
1089 Mutex::Autolock _l(mStateLock);
1090 mAnimFrameTracker.clearStats();
1091 return NO_ERROR;
1092}
1093
1094status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1095 Mutex::Autolock _l(mStateLock);
1096 mAnimFrameTracker.getStats(outStats);
1097 return NO_ERROR;
1098}
1099
Dan Stozac4f471e2016-03-24 09:31:08 -07001100status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1101 HdrCapabilities* outCapabilities) const {
1102 Mutex::Autolock _l(mStateLock);
1103
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001104 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 if (displayDevice == nullptr) {
1106 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1107 return BAD_VALUE;
1108 }
1109
Peiyong Linfb069302018-04-25 14:34:31 -07001110 // At this point the DisplayDeivce should already be set up,
1111 // meaning the luminance information is already queried from
1112 // hardware composer and stored properly.
1113 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1114 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1115 capabilities.getDesiredMaxLuminance(),
1116 capabilities.getDesiredMaxAverageLuminance(),
1117 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001118
1119 return NO_ERROR;
1120}
1121
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1124 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 if (mInjectVSyncs == enable) {
1127 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129
1130 if (enable) {
1131 ALOGV("VSync Injections enabled");
1132 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001133 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001134 mInjectorEventThread =
1135 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1136 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001138 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001139 } else {
1140 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001141 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001142 }
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 });
1146 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147 return NO_ERROR;
1148}
1149
1150status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 Mutex::Autolock _l(mStateLock);
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 if (!mInjectVSyncs) {
1154 ALOGE("VSync Injections not enabled");
1155 return BAD_VALUE;
1156 }
1157 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1158 ALOGV("Injecting VSync inside SurfaceFlinger");
1159 mVSyncInjector->onInjectSyncEvent(when);
1160 }
1161 return NO_ERROR;
1162}
1163
Lloyd Pique755e3192018-01-31 16:46:15 -08001164status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1165 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001166 IPCThreadState* ipc = IPCThreadState::self();
1167 const int pid = ipc->getCallingPid();
1168 const int uid = ipc->getCallingUid();
1169 if ((uid != AID_SHELL) &&
1170 !PermissionCache::checkPermission(sDump, pid, uid)) {
1171 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1172 return PERMISSION_DENIED;
1173 }
1174
1175 // Try to acquire a lock for 1s, fail gracefully
1176 const status_t err = mStateLock.timedLock(s2ns(1));
1177 const bool locked = (err == NO_ERROR);
1178 if (!locked) {
1179 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1180 return TIMED_OUT;
1181 }
1182
1183 outLayers->clear();
1184 mCurrentState.traverseInZOrder([&](Layer* layer) {
1185 outLayers->push_back(layer->getLayerDebugInfo());
1186 });
1187
1188 mStateLock.unlock();
1189 return NO_ERROR;
1190}
1191
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001192// ----------------------------------------------------------------------------
1193
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001194sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1195 ISurfaceComposer::VsyncSource vsyncSource) {
1196 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1197 return mSFEventThread->createEventConnection();
1198 } else {
1199 return mEventThread->createEventConnection();
1200 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001201}
1202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001203// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001204
1205void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001206 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001210 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001214 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001215}
1216
1217void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001218 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001219 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001220}
1221
1222status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001223 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001224 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001228 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001229 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230 if (res == NO_ERROR) {
1231 msg->wait();
1232 }
1233 return res;
1234}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001235
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001236void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001237 do {
1238 waitForEvent();
1239 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001240}
1241
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242void SurfaceFlinger::enableHardwareVsync() {
1243 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001244 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1247 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001249 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250}
1251
Jesse Hall948fe0c2013-10-14 12:56:09 -07001252void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 Mutex::Autolock _l(mHWVsyncLock);
1254
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255 if (makeAvailable) {
1256 mHWVsyncAvailable = true;
1257 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001258 // Hardware vsync is not currently available, so abort the resync
1259 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001260 return;
1261 }
1262
David Sodman105b7dc2017-11-04 20:28:14 -07001263 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001264 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265
1266 mPrimaryDispSync.reset();
1267 mPrimaryDispSync.setPeriod(period);
1268
1269 if (!mPrimaryHWVsyncEnabled) {
1270 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001271 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1272 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273 mPrimaryHWVsyncEnabled = true;
1274 }
1275}
1276
Jesse Hall948fe0c2013-10-14 12:56:09 -07001277void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278 Mutex::Autolock _l(mHWVsyncLock);
1279 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001280 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1281 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 mPrimaryDispSync.endResync();
1283 mPrimaryHWVsyncEnabled = false;
1284 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001285 if (makeUnavailable) {
1286 mHWVsyncAvailable = false;
1287 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288}
1289
Tim Murray4a4e4a22016-04-19 16:29:23 +00001290void SurfaceFlinger::resyncWithRateLimit() {
1291 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001292
1293 // No explicit locking is needed here since EventThread holds a lock while calling this method
1294 static nsecs_t sLastResyncAttempted = 0;
1295 const nsecs_t now = systemTime();
1296 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001297 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001298 }
Dan Stoza57164302017-05-08 14:03:54 -07001299 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300}
1301
Steven Thomasb02664d2017-07-26 18:48:28 -07001302void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1303 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001304 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001305 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001306 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 return;
1308 }
1309
1310 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001311 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 return;
1313 }
1314
Jamie Gennisd1700752013-10-14 12:22:52 -07001315 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316
Jamie Gennisd1700752013-10-14 12:22:52 -07001317 { // Scope for the lock
1318 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001320 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001322 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001323
1324 if (needsHwVsync) {
1325 enableHardwareVsync();
1326 } else {
1327 disableHardwareVsync(false);
1328 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001329}
1330
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001331void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001332 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1333 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001334}
1335
Lloyd Pique715a2c12017-12-14 17:18:08 -08001336void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1337 HWC2::Connection connection) {
1338 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1339 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340
Lloyd Piqueba04e622017-12-14 17:11:26 -08001341 // Ignore events that do not have the right sequenceId.
1342 if (sequenceId != getBE().mComposerSequenceId) {
1343 return;
1344 }
1345
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 // Only lock if we're not on the main thread. This function is normally
1347 // called on a hwbinder thread, but for the primary display it's called on
1348 // the main thread with the state lock already held, so don't attempt to
1349 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001350 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001351
Lloyd Pique715a2c12017-12-14 17:18:08 -08001352 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001353
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001354 if (std::this_thread::get_id() == mMainThreadId) {
1355 // Process all pending hot plug events immediately if we are on the main thread.
1356 processDisplayHotplugEventsLocked();
1357 }
1358
Lloyd Piqueba04e622017-12-14 17:11:26 -08001359 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001360}
1361
Steven Thomasb02664d2017-07-26 18:48:28 -07001362void SurfaceFlinger::onRefreshReceived(int sequenceId,
1363 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001365 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001367 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001368 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001369}
1370
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001372 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 getHwComposer().setVsyncEnabled(disp,
1375 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001376}
1377
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001379void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 // Clear the drawing state so that the logic inside of
1382 // handleTransactionLocked will fire. It will determine the delta between
1383 // mCurrentState and mDrawingState and re-apply all changes when we make the
1384 // transition.
1385 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001386 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 mDisplays.clear();
1388}
1389
Steven Thomas050b2c82017-03-06 11:45:16 -08001390void SurfaceFlinger::updateVrFlinger() {
1391 if (!mVrFlinger)
1392 return;
1393 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001395 return;
1396 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397
David Sodman105b7dc2017-11-04 20:28:14 -07001398 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 ALOGE("Vr flinger is only supported for remote hardware composer"
1400 " service connections. Ignoring request to transition to vr"
1401 " flinger.");
1402 mVrFlingerRequestsDisplay = false;
1403 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 int currentDisplayPowerMode = getDisplayDeviceLocked(
1409 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001414
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001416 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001417 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1418 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001419 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420
David Sodman105b7dc2017-11-04 20:28:14 -07001421 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1422 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001423
1424 if (vrFlingerRequestsDisplay) {
1425 mVrFlinger->GrantDisplayOwnership();
1426 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001427 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
1430 mVisibleRegionsDirty = true;
1431 invalidateHwcGeometry();
1432
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001433 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1435 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1436 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001439 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 const nsecs_t period = activeConfig->getVsyncPeriod();
1441 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 // Use phase of 0 since phase is not known.
1444 // Use latency of 0, which will snap to the ideal latency.
1445 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001446
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447 android_atomic_or(1, &mRepaintEverything);
1448 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001449}
1450
Mathias Agopian4fec8732012-06-29 14:12:52 -07001451void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001452 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001453 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001455 bool frameMissed = !mHadClientComposition &&
1456 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001457 (mPreviousPresentFence->getSignalTime() ==
1458 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001459 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001460 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001461 mTimeStats.incrementMissedFrames();
1462 if (mPropagateBackpressure) {
1463 signalLayerUpdate();
1464 break;
1465 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001466 }
Dan Stoza50182882016-07-08 12:02:20 -07001467
Steven Thomas050b2c82017-03-06 11:45:16 -08001468 // Now that we're going to make it to the handleMessageTransaction()
1469 // call below it's safe to call updateVrFlinger(), which will
1470 // potentially trigger a display handoff.
1471 updateVrFlinger();
1472
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 bool refreshNeeded = handleMessageTransaction();
1474 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001475 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001477 // Signal a refresh if a transaction modified the window state,
1478 // a new buffer was latched, or if HWC has requested a full
1479 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 signalRefresh();
1481 }
1482 break;
1483 }
1484 case MessageQueue::REFRESH: {
1485 handleMessageRefresh();
1486 break;
1487 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001488 }
1489}
1490
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001492 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001494 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498}
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503}
1504
1505void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001506 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001507
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001508 mRefreshPending = false;
1509
Pablo Ceballos40845df2016-01-25 17:41:15 -08001510 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001511
Brian Andersond6927fb2016-07-23 23:37:30 -07001512 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001513 rebuildLayerStacks();
1514 setUpHWComposer();
1515 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001516 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001517 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001518 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001519 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520
David Sodman105b7dc2017-11-04 20:28:14 -07001521 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001522
1523 mHadClientComposition = false;
1524 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1525 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1526 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001527 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001528 }
Dan Stoza2713c302018-03-28 17:07:36 -07001529 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001530
Dan Stoza9e56aa02015-11-02 13:00:03 -08001531 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001533
Mathias Agopiancd60f992012-08-16 16:28:27 -07001534void SurfaceFlinger::doDebugFlashRegions()
1535{
1536 // is debugging enabled
1537 if (CC_LIKELY(!mDebugRegion))
1538 return;
1539
1540 const bool repaintEverything = mRepaintEverything;
1541 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1542 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001543 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001544 // transform the dirty region into this screen's coordinate space
1545 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1546 if (!dirtyRegion.isEmpty()) {
1547 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001548 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549
1550 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001552 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001553 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1554
Mathias Agopianda27af92012-09-13 18:17:13 -07001555 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556 }
1557 }
1558 }
1559
1560 postFramebuffer();
1561
1562 if (mDebugRegion > 1) {
1563 usleep(mDebugRegion * 1000);
1564 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001565
Dan Stoza9e56aa02015-11-02 13:00:03 -08001566 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001567 auto& displayDevice = mDisplays[displayId];
1568 if (!displayDevice->isDisplayOn()) {
1569 continue;
1570 }
1571
David Sodman105b7dc2017-11-04 20:28:14 -07001572 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1573 ALOGE_IF(result != NO_ERROR,
1574 "prepareFrame for display %zd failed:"
1575 " %d (%s)",
1576 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001577 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578}
1579
Adrian Roos1e1a1282017-11-01 19:05:31 +01001580void SurfaceFlinger::doTracing(const char* where) {
1581 ATRACE_CALL();
1582 ATRACE_NAME(where);
1583 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001584 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001585 }
1586}
1587
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001588void SurfaceFlinger::logLayerStats() {
1589 ATRACE_CALL();
1590 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1591 int32_t hwcId = -1;
1592 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1593 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1594 if (displayDevice->isPrimary()) {
1595 hwcId = displayDevice->getHwcDisplayId();
1596 break;
1597 }
1598 }
1599 if (hwcId < 0) {
1600 ALOGE("LayerStats: Hmmm, no primary display?");
1601 return;
1602 }
1603 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1604 }
1605}
1606
Brian Andersond6927fb2016-07-23 23:37:30 -07001607void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001609 ATRACE_CALL();
1610 ALOGV("preComposition");
1611
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001613 mDrawingState.traverseInZOrder([&](Layer* layer) {
1614 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615 needExtraInvalidate = true;
1616 }
Robert Carr2047fae2016-11-28 14:09:09 -08001617 });
1618
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619 if (needExtraInvalidate) {
1620 signalLayerUpdate();
1621 }
1622}
1623
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624void SurfaceFlinger::updateCompositorTiming(
1625 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1626 std::shared_ptr<FenceTime>& presentFenceTime) {
1627 // Update queue of past composite+present times and determine the
1628 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001629 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001631 while (!getBE().mCompositePresentTimes.empty()) {
1632 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633 // Cached values should have been updated before calling this method,
1634 // which helps avoid duplicate syscalls.
1635 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1636 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1637 break;
1638 }
1639 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001640 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001641 }
1642
1643 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001644 while (getBE().mCompositePresentTimes.size() > 16) {
1645 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 }
1647
Brian Andersond0010582017-03-07 13:20:31 -08001648 setCompositorTimingSnapped(
1649 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1650}
1651
1652void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1653 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 // Integer division and modulo round toward 0 not -inf, so we need to
1655 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001656 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1658 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1659
Brian Andersond0010582017-03-07 13:20:31 -08001660 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1661 if (idealLatency <= 0) {
1662 idealLatency = vsyncInterval;
1663 }
1664
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665 // Snap the latency to a value that removes scheduling jitter from the
1666 // composition and present times, which often have >1ms of jitter.
1667 // Reducing jitter is important if an app attempts to extrapolate
1668 // something (such as user input) to an accurate diasplay time.
1669 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1670 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001671 nsecs_t bias = vsyncInterval / 2;
1672 int64_t extraVsyncs =
1673 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1674 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1675 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676
David Sodman99974d22017-11-28 12:04:33 -08001677 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1678 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1679 getBE().mCompositorTiming.interval = vsyncInterval;
1680 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681}
1682
1683void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001685 ATRACE_CALL();
1686 ALOGV("postComposition");
1687
Brian Anderson3546a3f2016-07-14 11:51:14 -07001688 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001689 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001690 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001691 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001692 }
1693
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001694 // |mStateLock| not needed as we are on the main thread
1695 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001696
David Sodman73beded2017-11-15 11:56:06 -08001697 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001698 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001699 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001700 glCompositionDoneFenceTime =
1701 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001702 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001703 } else {
1704 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1705 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001706
David Sodman73beded2017-11-15 11:56:06 -08001707 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001708 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001709 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001710 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1713 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1714
1715 // We use the refreshStartTime which might be sampled a little later than
1716 // when we started doing work for this frame, but that should be okay
1717 // since updateCompositorTiming has snapping logic.
1718 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001719 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001720 CompositorTiming compositorTiming;
1721 {
David Sodman99974d22017-11-28 12:04:33 -08001722 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1723 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001724 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725
Robert Carr2047fae2016-11-28 14:09:09 -08001726 mDrawingState.traverseInZOrder([&](Layer* layer) {
1727 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001728 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001729 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001730 recordBufferingStats(layer->getName().string(),
1731 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001732 }
Robert Carr2047fae2016-11-28 14:09:09 -08001733 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001734
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001735 if (presentFenceTime->isValid()) {
1736 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001737 enableHardwareVsync();
1738 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001739 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001740 }
1741 }
1742
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001743 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001744 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001745 enableHardwareVsync();
1746 }
1747 }
1748
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001749 if (mAnimCompositionPending) {
1750 mAnimCompositionPending = false;
1751
Brian Anderson4e606e32017-03-16 15:34:57 -07001752 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001753 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001754 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001755 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001756 // The HWC doesn't support present fences, so use the refresh
1757 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001758 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001759 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001760 mAnimFrameTracker.setActualPresentTime(presentTime);
1761 }
1762 mAnimFrameTracker.advanceFrame();
1763 }
Dan Stozab90cf072015-03-05 11:05:59 -08001764
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001765 mTimeStats.incrementTotalFrames();
1766 if (mHadClientComposition) {
1767 mTimeStats.incrementClientCompositionFrames();
1768 }
1769
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001770 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1771 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001772 return;
1773 }
1774
1775 nsecs_t currentTime = systemTime();
1776 if (mHasPoweredOff) {
1777 mHasPoweredOff = false;
1778 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001779 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001781 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1782 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001783 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001784 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001785 }
David Sodman4a36e932017-11-07 14:29:47 -08001786 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001787 }
David Sodman4a36e932017-11-07 14:29:47 -08001788 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001789}
1790
1791void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001792 ATRACE_CALL();
1793 ALOGV("rebuildLayerStacks");
1794
Mathias Agopiancd60f992012-08-16 16:28:27 -07001795 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001796 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001797 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001798 mVisibleRegionsDirty = false;
1799 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001800
Jeff Sharkey76488112017-02-27 14:15:18 -07001801 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1802 Region opaqueRegion;
1803 Region dirtyRegion;
1804 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001805 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001806 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1807 const Transform& tr(displayDevice->getTransform());
1808 const Rect bounds(displayDevice->getBounds());
1809 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001810 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001811
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001813 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001814 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1815 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 Region drawRegion(tr.transform(
1817 layer->visibleNonTransparentRegion));
1818 drawRegion.andSelf(bounds);
1819 if (!drawRegion.isEmpty()) {
1820 layersSortedByZ.add(layer);
1821 } else {
1822 // Clear out the HWC layer if this layer was
1823 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001824 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001825 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001827 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001828 // WM changes displayDevice->layerStack upon sleep/awake.
1829 // Here we make sure we delete the HWC layers even if
1830 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001831 hwcLayerDestroyed = layer->destroyHwcLayer(
1832 displayDevice->getHwcDisplayId());
1833 }
1834
1835 // If a layer is not going to get a release fence because
1836 // it is invisible, but it is also going to release its
1837 // old buffer, add it to the list of layers needing
1838 // fences.
1839 if (hwcLayerDestroyed) {
1840 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1841 mLayersWithQueuedFrames.cend(), layer);
1842 if (found != mLayersWithQueuedFrames.cend()) {
1843 layersNeedingFences.add(layer);
1844 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001845 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001846 });
1847 }
1848 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001849 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 displayDevice->undefinedRegion.set(bounds);
1851 displayDevice->undefinedRegion.subtractSelf(
1852 tr.transform(opaqueRegion));
1853 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001854 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001857
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001858// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001859// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001860// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001861// - Dataspace::DISPLAY_P3
1862// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001863// The returned HDR data space is one of
1864// - Dataspace::UNKNOWN
1865// - Dataspace::BT2020_HLG
1866// - Dataspace::BT2020_PQ
1867Dataspace SurfaceFlinger::getBestDataspace(
1868 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1869 Dataspace bestDataSpace = Dataspace::SRGB;
1870 *outHdrDataSpace = Dataspace::UNKNOWN;
1871
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001872 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1873 switch (layer->getDataSpace()) {
1874 case Dataspace::V0_SCRGB:
1875 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001876 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001877 break;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001878 case Dataspace::DISPLAY_P3:
1879 if (bestDataSpace == Dataspace::SRGB) {
1880 bestDataSpace = Dataspace::DISPLAY_P3;
1881 }
1882 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001883 case Dataspace::BT2020_PQ:
1884 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001885 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001887 case Dataspace::BT2020_HLG:
1888 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001889 // When there's mixed PQ content and HLG content, we set the HDR
1890 // data space to be BT2020_PQ and convert HLG to PQ.
1891 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1892 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001893 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 break;
1895 default:
1896 break;
1897 }
Romain Guy54f154a2017-10-24 21:40:32 +01001898 }
1899
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001900 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001901}
1902
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001905 ColorMode* outMode, Dataspace* outDataSpace,
1906 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001907 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1908 *outMode = ColorMode::NATIVE;
1909 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001910 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001912 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001913
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001914 Dataspace hdrDataSpace;
1915 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1916
1917 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1918 // Hardware composer can handle BT2100 ColorMode only when
1919 // - colorimetrical tone mapping is supported, or
1920 // - Auto mode is turned on and enhanced tone mapping is supported.
1921 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1922 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1923 displayDevice->hasBT2100PQEnhanceSupport())) {
1924 *outMode = ColorMode::BT2100_PQ;
1925 *outDataSpace = Dataspace::BT2020_PQ;
1926 } else if (displayDevice->hasHDR10Support()) {
1927 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1928 hdrDataSpace = Dataspace::UNKNOWN;
1929 } else {
1930 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931 *outMode = ColorMode::DISPLAY_P3;
1932 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001933 }
1934 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1935 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1936 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1937 displayDevice->hasBT2100HLGEnhanceSupport())) {
1938 *outMode = ColorMode::BT2100_HLG;
1939 *outDataSpace = Dataspace::BT2020_HLG;
1940 } else if (displayDevice->hasHLGSupport()) {
1941 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1942 hdrDataSpace = Dataspace::UNKNOWN;
1943 } else {
1944 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1945 *outMode = ColorMode::DISPLAY_P3;
1946 *outDataSpace = Dataspace::DISPLAY_P3;
1947 }
1948 }
1949
1950 // At this point, there's no HDR layer.
1951 if (hdrDataSpace == Dataspace::UNKNOWN) {
1952 switch (bestDataSpace) {
1953 case Dataspace::DISPLAY_P3:
1954 case Dataspace::V0_SCRGB_LINEAR:
1955 *outMode = ColorMode::DISPLAY_P3;
1956 *outDataSpace = Dataspace::DISPLAY_P3;
1957 break;
1958 default:
1959 *outMode = ColorMode::SRGB;
1960 *outDataSpace = Dataspace::SRGB;
1961 break;
1962 }
1963 }
1964 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1965}
1966
1967RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1968 ColorMode colorMode) const {
1969 // Native Mode means the display is not color managed, and whichever
1970 // render intent is picked doesn't matter, thus return
1971 // RenderIntent::COLORIMETRIC as default here.
1972 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1973 return RenderIntent::COLORIMETRIC;
1974 }
1975
1976 // In Auto Color Mode, we want to strech to panel color space, right now
1977 // only the built-in display supports it.
1978 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1979 mBuiltinDisplaySupportsEnhance &&
1980 displayDevice->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1981 switch (colorMode) {
1982 case ColorMode::DISPLAY_P3:
1983 case ColorMode::SRGB:
1984 return RenderIntent::ENHANCE;
1985 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1986 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1987 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1988 case ColorMode::BT2100_PQ:
1989 return displayDevice->hasBT2100PQEnhanceSupport() ?
1990 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1991 case ColorMode::BT2100_HLG:
1992 return displayDevice->hasBT2100HLGEnhanceSupport() ?
1993 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1994 // This statement shouldn't be reached, switch cases will always
1995 // cover all possible ColorMode returned by pickColorMode.
1996 default:
1997 return RenderIntent::COLORIMETRIC;
1998 }
1999 }
2000
2001 // Either enhance is not supported or we are in natural mode.
2002
2003 // Natural Mode means it's color managed and the color must be right,
2004 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2005 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2006 switch (colorMode) {
2007 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2008 // when TONE_MAP_COLORIMETRIC is supported.
2009 case ColorMode::BT2100_PQ:
2010 case ColorMode::BT2100_HLG:
2011 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002012 default:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002013 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002014 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002015}
2016
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ATRACE_CALL();
2019 ALOGV("setUpHWComposer");
2020
Jesse Hall028dc8f2013-08-20 16:35:32 -07002021 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002022 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002023 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2024 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2025
2026 // If nothing has changed (!dirty), don't recompose.
2027 // If something changed, but we don't currently have any visible layers,
2028 // and didn't when we last did a composition, then skip it this time.
2029 // The second rule does two things:
2030 // - When all layers are removed from a display, we'll emit one black
2031 // frame, then nothing more until we get new layers.
2032 // - When a display is created with a private layer stack, we won't
2033 // emit any black frames until a layer is added to the layer stack.
2034 bool mustRecompose = dirty && !(empty && wasEmpty);
2035
2036 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2037 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2038 mustRecompose ? "doing" : "skipping",
2039 dirty ? "+" : "-",
2040 empty ? "+" : "-",
2041 wasEmpty ? "+" : "-");
2042
Dan Stoza71433162014-02-04 16:22:36 -08002043 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002044
2045 if (mustRecompose) {
2046 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2047 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002048 }
2049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 // build the h/w work list
2051 if (CC_UNLIKELY(mGeometryInvalid)) {
2052 mGeometryInvalid = false;
2053 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2054 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2055 const auto hwcId = displayDevice->getHwcDisplayId();
2056 if (hwcId >= 0) {
2057 const Vector<sp<Layer>>& currentLayers(
2058 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002059 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002060 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002062 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002065 }
2066 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002067
Robert Carrae060832016-11-28 10:51:00 -08002068 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002069 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002071 }
2072 }
2073 }
2074 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 }
Riley Andrews03414a12014-07-01 14:22:59 -07002076
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 // Set the per-frame data
2078 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2079 auto& displayDevice = mDisplays[displayId];
2080 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002081
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 if (hwcId < 0) {
2083 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002084 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002085 if (mDrawingState.colorMatrixChanged) {
2086 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2087 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002088 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2089 "display %zd: %d", displayId, result);
2090 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002092 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2093 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002094 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002095 layer->forceClientComposition(hwcId);
2096 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002097 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2098 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2099 !displayDevice->hasHLGSupport()) {
2100 layer->forceClientComposition(hwcId);
2101 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002102
chaviwc9232ed2017-11-14 15:31:15 -08002103 if (layer->getForceClientComposition(hwcId)) {
2104 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2105 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2106 continue;
2107 }
2108
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 layer->setPerFrameData(displayDevice);
2110 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002111
2112 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002113 ColorMode colorMode;
2114 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002115 RenderIntent renderIntent;
2116 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2117 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002118 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 }
2120
Chia-I Wu28f320b2018-05-03 11:02:56 -07002121 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002122
Dan Stoza9e56aa02015-11-02 13:00:03 -08002123 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002124 auto& displayDevice = mDisplays[displayId];
2125 if (!displayDevice->isDisplayOn()) {
2126 continue;
2127 }
2128
David Sodman105b7dc2017-11-04 20:28:14 -07002129 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2131 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002132 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002133}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002134
Mathias Agopiancd60f992012-08-16 16:28:27 -07002135void SurfaceFlinger::doComposition() {
2136 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 ALOGV("doComposition");
2138
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002139 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002140 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002141 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002142 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002143 // transform the dirty region into this screen's coordinate space
2144 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002145
2146 // repaint the framebuffer (if needed)
2147 doDisplayComposition(hw, dirtyRegion);
2148
Mathias Agopiancd60f992012-08-16 16:28:27 -07002149 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002150 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002151 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002152 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002153 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002154}
2155
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156void SurfaceFlinger::postFramebuffer()
2157{
Mathias Agopian841cde52012-03-01 15:44:37 -08002158 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002160
Mathias Agopiana44b0412011-10-16 18:46:35 -07002161 const nsecs_t now = systemTime();
2162 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002163
Dan Stoza9e56aa02015-11-02 13:00:03 -08002164 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2165 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002166 if (!displayDevice->isDisplayOn()) {
2167 continue;
2168 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 const auto hwcId = displayDevice->getHwcDisplayId();
2170 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002171 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002172 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002173 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002174 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002176 // The layer buffer from the previous frame (if any) is released
2177 // by HWC only when the release fence from this frame (if any) is
2178 // signaled. Always get the release fence from HWC first.
2179 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002180 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002181
2182 // If the layer was client composited in the previous frame, we
2183 // need to merge with the previous client target acquire fence.
2184 // Since we do not track that, always merge with the current
2185 // client target acquire fence when it is available, even though
2186 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002188 releaseFence = Fence::merge("LayerRelease", releaseFence,
2189 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002190 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002191
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192 layer->onLayerDisplayed(releaseFence);
2193 }
Chia-I Wu83806892017-11-16 10:50:20 -08002194
2195 // We've got a list of layers needing fences, that are disjoint with
2196 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2197 // supply them with the present fence.
2198 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002199 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002200 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2201 layer->onLayerDisplayed(presentFence);
2202 }
2203 }
2204
Dan Stoza9e56aa02015-11-02 13:00:03 -08002205 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002206 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002207 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002208 }
2209
Mathias Agopiana44b0412011-10-16 18:46:35 -07002210 mLastSwapBufferTime = systemTime() - now;
2211 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002212
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002213 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002214 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2215 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2216 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2217 logFrameStats();
2218 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220}
2221
Mathias Agopian87baae12012-07-31 12:38:26 -07002222void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223{
Mathias Agopian841cde52012-03-01 15:44:37 -08002224 ATRACE_CALL();
2225
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002226 // here we keep a copy of the drawing state (that is the state that's
2227 // going to be overwritten by handleTransactionLocked()) outside of
2228 // mStateLock so that the side-effects of the State assignment
2229 // don't happen with mStateLock held (which can cause deadlocks).
2230 State drawingState(mDrawingState);
2231
Mathias Agopianca4d3602011-05-19 15:38:14 -07002232 Mutex::Autolock _l(mStateLock);
2233 const nsecs_t now = systemTime();
2234 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235
Mathias Agopianca4d3602011-05-19 15:38:14 -07002236 // Here we're guaranteed that some transaction flags are set
2237 // so we can call handleTransactionLocked() unconditionally.
2238 // We call getTransactionFlags(), which will also clear the flags,
2239 // with mStateLock held to guarantee that mCurrentState won't change
2240 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002241
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002242 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002243 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002244 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002245
Mathias Agopianca4d3602011-05-19 15:38:14 -07002246 mLastTransactionTime = systemTime() - now;
2247 mDebugInTransaction = 0;
2248 invalidateHwcGeometry();
2249 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002250}
2251
Lloyd Pique715a2c12017-12-14 17:18:08 -08002252DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002253 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002254 // Figure out whether the event is for the primary display or an
2255 // external display by matching the Hwc display id against one for a
2256 // connected display. If we did not find a match, we then check what
2257 // displays are not already connected to determine the type. If we don't
2258 // have a connected primary display, we assume the new display is meant to
2259 // be the primary display, and then if we don't have an external display,
2260 // we assume it is that.
2261 const auto primaryDisplayId =
2262 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2263 const auto externalDisplayId =
2264 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2265 if (primaryDisplayId && primaryDisplayId == display) {
2266 return DisplayDevice::DISPLAY_PRIMARY;
2267 } else if (externalDisplayId && externalDisplayId == display) {
2268 return DisplayDevice::DISPLAY_EXTERNAL;
2269 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2270 return DisplayDevice::DISPLAY_PRIMARY;
2271 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2272 return DisplayDevice::DISPLAY_EXTERNAL;
2273 }
2274
2275 return DisplayDevice::DISPLAY_ID_INVALID;
2276}
2277
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2279 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002280 auto displayType = determineDisplayType(event.display, event.connection);
2281 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2282 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2283 continue;
2284 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002285
2286 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2287 ALOGE("External displays are not supported by the vr hardware composer.");
2288 continue;
2289 }
2290
Lloyd Pique715a2c12017-12-14 17:18:08 -08002291 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002292
2293 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002294 if (!mBuiltinDisplays[displayType].get()) {
2295 ALOGV("Creating built in display %d", displayType);
2296 mBuiltinDisplays[displayType] = new BBinder();
2297 // All non-virtual displays are currently considered secure.
2298 DisplayDeviceState info(displayType, true);
2299 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2300 "Built-in Screen" : "External Screen";
2301 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002302 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002303 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002305 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002306
Lloyd Piquefcd86612017-12-14 17:15:36 -08002307 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2308 if (idx >= 0) {
2309 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002310 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002311 mCurrentState.displays.removeItemsAt(idx);
2312 }
2313 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002314 }
2315
2316 processDisplayChangesLocked();
2317 }
2318
2319 mPendingHotplugEvents.clear();
2320}
2321
Lloyd Pique09594832018-01-22 17:48:03 -08002322sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2323 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2324 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325 bool hasWideColorGamut = false;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002326 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2327
Lloyd Pique09594832018-01-22 17:48:03 -08002328 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002330 for (ColorMode colorMode : modes) {
2331 switch (colorMode) {
2332 case ColorMode::DISPLAY_P3:
2333 case ColorMode::ADOBE_RGB:
2334 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002336 break;
2337 default:
2338 break;
2339 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340
2341 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2342 colorMode);
2343 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2344 for (auto intent : renderIntents) {
2345 if (intent == RenderIntent::ENHANCE) {
2346 mBuiltinDisplaySupportsEnhance = true;
2347 break;
2348 }
2349 }
2350 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002351
2352 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2353 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2354 }
Lloyd Pique09594832018-01-22 17:48:03 -08002355 }
2356 }
2357
Peiyong Lin62665892018-04-16 11:07:44 -07002358 HdrCapabilities hdrCapabilities;
2359 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002360
2361 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2362 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2363
2364 /*
2365 * Create our display's surface
2366 */
2367 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2368 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2369 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2370 renderSurface->setNativeWindow(nativeWindow.get());
2371 const int displayWidth = renderSurface->queryWidth();
2372 const int displayHeight = renderSurface->queryHeight();
2373
2374 // Make sure that composition can never be stalled by a virtual display
2375 // consumer that isn't processing buffers fast enough. We have to do this
2376 // in two places:
2377 // * Here, in case the display is composed entirely by HWC.
2378 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2379 // window's swap interval in eglMakeCurrent, so they'll override the
2380 // interval we set here.
2381 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2382 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2383 }
2384
2385 // virtual displays are always considered enabled
2386 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2387 : HWC_POWER_MODE_OFF;
2388
2389 sp<DisplayDevice> hw =
2390 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2391 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002392 hasWideColorGamut, hdrCapabilities,
2393 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002394 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002395
2396 if (maxFrameBufferAcquiredBuffers >= 3) {
2397 nativeWindowSurface->preallocateBuffers();
2398 }
2399
2400 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002401 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2402 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002403 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002404 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002405 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002406 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2407 RenderIntent::COLORIMETRIC);
Lloyd Pique09594832018-01-22 17:48:03 -08002408 hw->setLayerStack(state.layerStack);
2409 hw->setProjection(state.orientation, state.viewport, state.frame);
2410 hw->setDisplayName(state.displayName);
2411
2412 return hw;
2413}
2414
Lloyd Pique347200f2017-12-14 17:00:15 -08002415void SurfaceFlinger::processDisplayChangesLocked() {
2416 // here we take advantage of Vector's copy-on-write semantics to
2417 // improve performance by skipping the transaction entirely when
2418 // know that the lists are identical
2419 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2420 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2421 if (!curr.isIdenticalTo(draw)) {
2422 mVisibleRegionsDirty = true;
2423 const size_t cc = curr.size();
2424 size_t dc = draw.size();
2425
2426 // find the displays that were removed
2427 // (ie: in drawing state but not in current state)
2428 // also handle displays that changed
2429 // (ie: displays that are in both lists)
2430 for (size_t i = 0; i < dc;) {
2431 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2432 if (j < 0) {
2433 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002434 // Call makeCurrent() on the primary display so we can
2435 // be sure that nothing associated with this display
2436 // is current.
2437 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2438 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2439 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2440 if (hw != nullptr) hw->disconnect(getHwComposer());
2441 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2442 mEventThread->onHotplugReceived(draw[i].type, false);
2443 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 } else {
2445 // this display is in both lists. see if something changed.
2446 const DisplayDeviceState& state(curr[j]);
2447 const wp<IBinder>& display(curr.keyAt(j));
2448 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2449 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2450 if (state_binder != draw_binder) {
2451 // changing the surface is like destroying and
2452 // recreating the DisplayDevice, so we just remove it
2453 // from the drawing state, so that it get re-added
2454 // below.
2455 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2456 if (hw != nullptr) hw->disconnect(getHwComposer());
2457 mDisplays.removeItem(display);
2458 mDrawingState.displays.removeItemsAt(i);
2459 dc--;
2460 // at this point we must loop to the next item
2461 continue;
2462 }
2463
2464 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2465 if (disp != nullptr) {
2466 if (state.layerStack != draw[i].layerStack) {
2467 disp->setLayerStack(state.layerStack);
2468 }
2469 if ((state.orientation != draw[i].orientation) ||
2470 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2471 disp->setProjection(state.orientation, state.viewport, state.frame);
2472 }
2473 if (state.width != draw[i].width || state.height != draw[i].height) {
2474 disp->setDisplaySize(state.width, state.height);
2475 }
2476 }
2477 }
2478 ++i;
2479 }
2480
2481 // find displays that were added
2482 // (ie: in current state but not in drawing state)
2483 for (size_t i = 0; i < cc; i++) {
2484 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2485 const DisplayDeviceState& state(curr[i]);
2486
2487 sp<DisplaySurface> dispSurface;
2488 sp<IGraphicBufferProducer> producer;
2489 sp<IGraphicBufferProducer> bqProducer;
2490 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002491 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492
2493 int32_t hwcId = -1;
2494 if (state.isVirtualDisplay()) {
2495 // Virtual displays without a surface are dormant:
2496 // they have external state (layer stack, projection,
2497 // etc.) but no internal state (i.e. a DisplayDevice).
2498 if (state.surface != nullptr) {
2499 // Allow VR composer to use virtual displays.
2500 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2501 int width = 0;
2502 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2503 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2504 int height = 0;
2505 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2506 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2507 int intFormat = 0;
2508 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2509 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002510 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511
2512 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2513 }
2514
2515 // TODO: Plumb requested format back up to consumer
2516
2517 sp<VirtualDisplaySurface> vds =
2518 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2519 bqProducer, bqConsumer,
2520 state.displayName);
2521
2522 dispSurface = vds;
2523 producer = vds;
2524 }
2525 } else {
2526 ALOGE_IF(state.surface != nullptr,
2527 "adding a supported display, but rendering "
2528 "surface is provided (%p), ignoring it",
2529 state.surface.get());
2530
2531 hwcId = state.type;
2532 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2533 producer = bqProducer;
2534 }
2535
2536 const wp<IBinder>& display(curr.keyAt(i));
2537 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002538 mDisplays.add(display,
2539 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2540 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002541 if (!state.isVirtualDisplay()) {
2542 mEventThread->onHotplugReceived(state.type, true);
2543 }
2544 }
2545 }
2546 }
2547 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548
2549 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002550}
2551
Mathias Agopian87baae12012-07-31 12:38:26 -07002552void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002553{
Dan Stoza7dde5992015-05-22 09:51:44 -07002554 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002555 mCurrentState.traverseInZOrder([](Layer* layer) {
2556 layer->notifyAvailableFrames();
2557 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002558
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 /*
2560 * Traversal of the children
2561 * (perform the transaction for each of them if needed)
2562 */
2563
Mathias Agopian3559b072012-08-15 13:46:03 -07002564 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002565 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002567 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568
2569 const uint32_t flags = layer->doTransaction(0);
2570 if (flags & Layer::eVisibleRegion)
2571 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002572 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 }
2574
2575 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 */
2578
Mathias Agopiane57f2922012-08-09 16:29:12 -07002579 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002581 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002584 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002585 // The transform hint might have changed for some layers
2586 // (either because a display has changed, or because a layer
2587 // as changed).
2588 //
2589 // Walk through all the layers in currentLayers,
2590 // and update their transform hint.
2591 //
2592 // If a layer is visible only on a single display, then that
2593 // display is used to calculate the hint, otherwise we use the
2594 // default display.
2595 //
2596 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2597 // the hint is set before we acquire a buffer from the surface texture.
2598 //
2599 // NOTE: layer transactions have taken place already, so we use their
2600 // drawing state. However, SurfaceFlinger's own transaction has not
2601 // happened yet, so we must use the current state layer list
2602 // (soon to become the drawing state list).
2603 //
2604 sp<const DisplayDevice> disp;
2605 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002606 bool first = true;
2607 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002608 // NOTE: we rely on the fact that layers are sorted by
2609 // layerStack first (so we don't have to traverse the list
2610 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002611 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002612 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002613 currentlayerStack = layerStack;
2614 // figure out if this layerstack is mirrored
2615 // (more than one display) if so, pick the default display,
2616 // if not, pick the only display it's on.
2617 disp.clear();
2618 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2619 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002620 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002621 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002622 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002623 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002624 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002625 break;
2626 }
2627 }
2628 }
2629 }
Chet Haase91d25932013-04-11 15:24:55 -07002630
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002631 if (disp == nullptr) {
2632 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2633 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002634
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002635 // could be null when this layer is using a layerStack
2636 // that is not visible on any display. Also can occur at
2637 // screen off/on times.
2638 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002639 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002640
2641 // disp can be null if there is no display available at all to get
2642 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002643 if (disp != nullptr) {
2644 layer->updateTransformHint(disp);
2645 }
Robert Carr2047fae2016-11-28 14:09:09 -08002646
2647 first = false;
2648 });
Mathias Agopian84300952012-11-21 16:02:13 -08002649 }
2650
2651
Mathias Agopian3559b072012-08-15 13:46:03 -07002652 /*
2653 * Perform our own transaction if needed
2654 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655
2656 if (mLayersAdded) {
2657 mLayersAdded = false;
2658 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002659 mVisibleRegionsDirty = true;
2660 }
2661
2662 // some layers might have been removed, so
2663 // we need to update the regions they're exposing.
2664 if (mLayersRemoved) {
2665 mLayersRemoved = false;
2666 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002667 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002669 // this layer is not visible anymore
2670 // TODO: we could traverse the tree from front to back and
2671 // compute the actual visible region
2672 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002673 Region visibleReg;
2674 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002675 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002676 }
Robert Carr2047fae2016-11-28 14:09:09 -08002677 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 }
2679
2680 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002681
2682 updateCursorAsync();
2683}
2684
2685void SurfaceFlinger::updateCursorAsync()
2686{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2688 auto& displayDevice = mDisplays[displayId];
2689 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002690 continue;
2691 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692
2693 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2694 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002695 }
2696 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002697}
2698
2699void SurfaceFlinger::commitTransaction()
2700{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002701 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 for (const auto& l : mLayersPendingRemoval) {
2704 recordBufferingStats(l->getName().string(),
2705 l->getOccupancyHistory(true));
2706 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707 }
2708 mLayersPendingRemoval.clear();
2709 }
2710
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002711 // If this transaction is part of a window animation then the next frame
2712 // we composite should be considered an animation as well.
2713 mAnimCompositionPending = mAnimTransactionPending;
2714
Mathias Agopian4fec8732012-06-29 14:12:52 -07002715 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002716 // clear the "changed" flags in current state
2717 mCurrentState.colorMatrixChanged = false;
2718
Robert Carr1f0a16a2016-10-24 16:27:39 -07002719 mDrawingState.traverseInZOrder([](Layer* layer) {
2720 layer->commitChildList();
2721 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002722 mTransactionPending = false;
2723 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
Chia-I Wuab0c3192017-08-01 11:29:00 -07002727void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002728 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729{
Mathias Agopian841cde52012-03-01 15:44:37 -08002730 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 Region aboveOpaqueLayers;
2734 Region aboveCoveredLayers;
2735 Region dirty;
2736
Mathias Agopian87baae12012-07-31 12:38:26 -07002737 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738
Robert Carr2047fae2016-11-28 14:09:09 -08002739 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002741 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
Jesse Hall01e29052013-02-19 16:13:35 -08002743 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002744 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002745 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002746
Mathias Agopianab028732010-03-16 16:41:46 -07002747 /*
2748 * opaqueRegion: area of a surface that is fully opaque.
2749 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002751
2752 /*
2753 * visibleRegion: area of a surface that is visible on screen
2754 * and not fully transparent. This is essentially the layer's
2755 * footprint minus the opaque regions above it.
2756 * Areas covered by a translucent surface are considered visible.
2757 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002759
2760 /*
2761 * coveredRegion: area of a surface that is covered by all
2762 * visible regions above it (which includes the translucent areas).
2763 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002765
Jesse Halla8026d22012-09-25 13:25:04 -07002766 /*
2767 * transparentRegion: area of a surface that is hinted to be completely
2768 * transparent. This is only used to tell when the layer has no visible
2769 * non-transparent regions and can be removed from the layer list. It
2770 * does not affect the visibleRegion of this layer or any layers
2771 * beneath it. The hint may not be correct if apps don't respect the
2772 * SurfaceView restrictions (which, sadly, some don't).
2773 */
2774 Region transparentRegion;
2775
Mathias Agopianab028732010-03-16 16:41:46 -07002776
2777 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002778 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002779 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002780 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002782 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002783 if (!visibleRegion.isEmpty()) {
2784 // Remove the transparent area from the visible region
2785 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002786 if (tr.preserveRects()) {
2787 // transform the transparent region
2788 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002789 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002790 // transformation too complex, can't do the
2791 // transparent region optimization.
2792 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002793 }
Mathias Agopianab028732010-03-16 16:41:46 -07002794 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795
Mathias Agopianab028732010-03-16 16:41:46 -07002796 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002797 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002798 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002799 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2800 // the opaque region is the layer's footprint
2801 opaqueRegion = visibleRegion;
2802 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 }
2804 }
2805
Robert Carre5f4f692018-01-12 13:12:28 -08002806 if (visibleRegion.isEmpty()) {
2807 layer->clearVisibilityRegions();
2808 return;
2809 }
2810
Mathias Agopianab028732010-03-16 16:41:46 -07002811 // Clip the covered region to the visible region
2812 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2813
2814 // Update aboveCoveredLayers for next (lower) layer
2815 aboveCoveredLayers.orSelf(visibleRegion);
2816
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 // subtract the opaque region covered by the layers above us
2818 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819
2820 // compute this layer's dirty region
2821 if (layer->contentDirty) {
2822 // we need to invalidate the whole region
2823 dirty = visibleRegion;
2824 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 layer->contentDirty = false;
2827 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002828 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002829 * the exposed region consists of two components:
2830 * 1) what's VISIBLE now and was COVERED before
2831 * 2) what's EXPOSED now less what was EXPOSED before
2832 *
2833 * note that (1) is conservative, we start with the whole
2834 * visible region but only keep what used to be covered by
2835 * something -- which mean it may have been exposed.
2836 *
2837 * (2) handles areas that were not covered by anything but got
2838 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002839 */
Mathias Agopianab028732010-03-16 16:41:46 -07002840 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002841 const Region oldVisibleRegion = layer->visibleRegion;
2842 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002843 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2844 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 }
2846 dirty.subtractSelf(aboveOpaqueLayers);
2847
2848 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002849 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850
Mathias Agopianab028732010-03-16 16:41:46 -07002851 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002853
Jesse Halla8026d22012-09-25 13:25:04 -07002854 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 layer->setVisibleRegion(visibleRegion);
2856 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002857 layer->setVisibleNonTransparentRegion(
2858 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002859 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860
Mathias Agopian87baae12012-07-31 12:38:26 -07002861 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862}
2863
Chia-I Wuab0c3192017-08-01 11:29:00 -07002864void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002865 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002866 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002867 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002868 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002869 }
2870 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002871}
2872
Dan Stoza6b9454d2014-11-07 16:00:59 -08002873bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 ALOGV("handlePageFlip");
2876
Brian Andersond6927fb2016-07-23 23:37:30 -07002877 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878
Mathias Agopian4fec8732012-06-29 14:12:52 -07002879 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002880 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002881 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002882
2883 // Store the set of layers that need updates. This set must not change as
2884 // buffers are being latched, as this could result in a deadlock.
2885 // Example: Two producers share the same command stream and:
2886 // 1.) Layer 0 is latched
2887 // 2.) Layer 0 gets a new frame
2888 // 2.) Layer 1 gets a new frame
2889 // 3.) Layer 1 is latched.
2890 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2891 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002892 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002893 if (layer->hasQueuedFrame()) {
2894 frameQueued = true;
2895 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002896 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002897 } else {
2898 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002899 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002900 } else {
2901 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002902 }
Robert Carr2047fae2016-11-28 14:09:09 -08002903 });
2904
Dan Stoza9e56aa02015-11-02 13:00:03 -08002905 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002906 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002907 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002908 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002909 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002910 newDataLatched = true;
2911 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002912 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002913
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002914 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002915
2916 // If we will need to wake up at some time in the future to deal with a
2917 // queued frame that shouldn't be displayed during this vsync period, wake
2918 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002919 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002920 signalLayerUpdate();
2921 }
2922
2923 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002924 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925}
2926
Mathias Agopianad456f92011-01-13 17:53:01 -08002927void SurfaceFlinger::invalidateHwcGeometry()
2928{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002930}
2931
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002932
Fabien Sanglard830b8472016-11-30 16:35:58 -08002933void SurfaceFlinger::doDisplayComposition(
2934 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002935 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002936{
Dan Stoza71433162014-02-04 16:22:36 -08002937 // We only need to actually compose the display if:
2938 // 1) It is being handled by hardware composer, which may need this to
2939 // keep its virtual display state machine in sync, or
2940 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002941 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002942 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002944 return;
2945 }
2946
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002948 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002949
2950 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002951 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952}
2953
Chia-I Wub02087d2017-11-09 10:19:54 -08002954bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002955{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002957
Chia-I Wub02087d2017-11-09 10:19:54 -08002958 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002959 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002961 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002962 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002963
Chia-I Wu8e50e692018-05-04 10:12:37 -07002964 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002965 bool needsLegacyColorMatrix = false;
2966 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002967
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 if (hasClientComposition) {
2969 ALOGV("hasClientComposition");
2970
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002971 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002972 if (displayDevice->hasWideColorGamut()) {
2973 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002974 }
2975 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002976 getBE().mRenderEngine->setDisplayMaxLuminance(
2977 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002978
Chia-I Wu8e50e692018-05-04 10:12:37 -07002979 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2980 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2981 HWC2::Capability::SkipClientColorTransform);
2982
2983 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2984 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002985 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002986 }
2987
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002988 needsLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002989 outputDataspace != Dataspace::UNKNOWN &&
2990 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991
Chia-I Wu7f402902017-11-09 12:51:10 -08002992 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002993 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002995 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002996
2997 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002998 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002999 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3000 }
3001 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003002 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003003
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003004 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003005 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003006 // when using overlays, we assume a fully transparent framebuffer
3007 // NOTE: we could reduce how much we need to clear, for instance
3008 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003009 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003010 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003011 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003012 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003013 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003014 // we're left with the letterbox region
3015 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003017
3018 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003020
Mathias Agopianb9494d52012-04-18 02:28:45 -07003021 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003022 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003023 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003025 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003026 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003027
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003029 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003030 // scissor on the main display. It should never be needed
3031 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 const Rect& bounds(displayDevice->getBounds());
3033 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003034 if (scissor != bounds) {
3035 // scissor doesn't match the screen's dimensions, so we
3036 // need to clear everything outside of it and enable
3037 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003038
Mathias Agopianf45c5102012-10-24 16:29:17 -07003039 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003041 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003042 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003043 }
3044 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003045 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003046
Mathias Agopian85d751c2012-08-29 16:59:24 -07003047 /*
3048 * and then, render the layers targeted at the framebuffer
3049 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003050
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 ALOGV("Rendering client layers");
3052 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003053 bool firstLayer = true;
3054 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3055 const Region clip(bounds.intersect(
3056 displayTransform.transform(layer->visibleRegion)));
3057 ALOGV("Layer: %s", layer->getName().string());
3058 ALOGV(" Composition type: %s",
3059 to_string(layer->getCompositionType(hwcId)).c_str());
3060 if (!clip.isEmpty()) {
3061 switch (layer->getCompositionType(hwcId)) {
3062 case HWC2::Composition::Cursor:
3063 case HWC2::Composition::Device:
3064 case HWC2::Composition::Sideband:
3065 case HWC2::Composition::SolidColor: {
3066 const Layer::State& state(layer->getDrawingState());
3067 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3068 layer->isOpaque(state) && (state.color.a == 1.0f)
3069 && hasClientComposition) {
3070 // never clear the very first layer since we're
3071 // guaranteed the FB is already cleared
3072 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003073 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003074 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003075 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003076 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003077 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003078 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3079 if (!legacyColorMatrixApplied) {
3080 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3081 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003082 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003083 } else if (legacyColorMatrixApplied) {
3084 getRenderEngine().setSaturationMatrix(mat4());
3085 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003086 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003087
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003088 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003089 break;
3090 }
3091 default:
3092 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003093 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003094 } else {
3095 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003096 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003098 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003099
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003100 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003101 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003102 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003103 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3104 getRenderEngine().setSaturationMatrix(mat4());
3105 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003106
Mathias Agopianf45c5102012-10-24 16:29:17 -07003107 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003108 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003109 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110}
3111
Fabien Sanglard830b8472016-11-30 16:35:58 -08003112void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3113 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003114 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003115 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116}
3117
Dan Stoza7d89d062015-04-30 13:29:25 -07003118status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003119 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003120 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 const sp<Layer>& lbc,
3122 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003123{
Dan Stoza7d89d062015-04-30 13:29:25 -07003124 // add this layer to the current state list
3125 {
3126 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003128 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3129 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003130 return NO_MEMORY;
3131 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003132 if (parent == nullptr) {
3133 mCurrentState.layersSortedByZ.add(lbc);
3134 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003135 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003136 ALOGE("addClientLayer called with a removed parent");
3137 return NAME_NOT_FOUND;
3138 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003139 parent->addChild(lbc);
3140 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003141
Yiwei Zhang243b3782018-05-15 17:40:04 -07003142 if (gbc != nullptr) {
3143 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3144 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3145 mMaxGraphicBufferProducerListSize,
3146 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3147 mGraphicBufferProducerList.size(),
3148 mMaxGraphicBufferProducerListSize, mNumLayers);
3149 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 mLayersAdded = true;
3151 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003152 }
3153
Mathias Agopian96f08192010-06-02 23:28:45 -07003154 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003155 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003156
Dan Stoza7d89d062015-04-30 13:29:25 -07003157 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003158}
3159
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003160status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003161 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003162 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3163}
Robert Carr7f9b8992017-03-10 11:08:39 -08003164
chaviwca27f252018-02-06 16:46:39 -08003165status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3166 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003167 if (layer->isPendingRemoval()) {
3168 return NO_ERROR;
3169 }
3170
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003172 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003173 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003174 if (topLevelOnly) {
3175 return NO_ERROR;
3176 }
3177
Chia-I Wu98f1c102017-05-30 14:54:08 -07003178 sp<Layer> ancestor = p;
3179 while (ancestor->getParent() != nullptr) {
3180 ancestor = ancestor->getParent();
3181 }
3182 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3183 ALOGE("removeLayer called with a layer whose parent has been removed");
3184 return NAME_NOT_FOUND;
3185 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003186
3187 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003188 } else {
3189 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003190 }
3191
Robert Carr136e2f62017-02-08 17:54:29 -08003192 // As a matter of normal operation, the LayerCleaner will produce a second
3193 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3194 // so we will succeed in promoting it, but it's already been removed
3195 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3196 // otherwise something has gone wrong and we are leaking the layer.
3197 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003198 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3199 layer->getName().string(),
3200 (p != nullptr) ? p->getName().string() : "no-parent");
3201 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003202 } else if (index < 0) {
3203 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003204 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003205
Chia-I Wuc6657022017-08-15 11:18:17 -07003206 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 mLayersPendingRemoval.add(layer);
3208 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003209 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003210 setTransactionFlags(eTransactionNeeded);
3211 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212}
3213
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003214uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003215 return android_atomic_release_load(&mTransactionFlags);
3216}
3217
Mathias Agopian3f844832013-08-07 21:24:32 -07003218uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3220}
3221
Mathias Agopian3f844832013-08-07 21:24:32 -07003222uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003223 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3224}
3225
3226uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3227 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003229 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003231 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 }
3233 return old;
3234}
3235
chaviwca27f252018-02-06 16:46:39 -08003236bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3237 for (const ComposerState& state : states) {
3238 // Here we need to check that the interface we're given is indeed
3239 // one of our own. A malicious client could give us a nullptr
3240 // IInterface, or one of its own or even one of our own but a
3241 // different type. All these situations would cause us to crash.
3242 if (state.client == nullptr) {
3243 return true;
3244 }
3245
3246 sp<IBinder> binder = IInterface::asBinder(state.client);
3247 if (binder == nullptr) {
3248 return true;
3249 }
3250
3251 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3252 return true;
3253 }
3254 }
3255 return false;
3256}
3257
Mathias Agopian8b33f032012-07-24 20:43:54 -07003258void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003259 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003260 const Vector<DisplayState>& displays,
3261 uint32_t flags)
3262{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003263 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003264 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003265 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266
chaviwca27f252018-02-06 16:46:39 -08003267 if (containsAnyInvalidClientState(states)) {
3268 return;
3269 }
3270
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003271 if (flags & eAnimation) {
3272 // For window updates that are part of an animation we must wait for
3273 // previous animation "frames" to be handled.
3274 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003275 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003276 if (CC_UNLIKELY(err != NO_ERROR)) {
3277 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003278 // caller after a few seconds.
3279 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3280 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003281 mAnimTransactionPending = false;
3282 break;
3283 }
3284 }
3285 }
3286
chaviwca27f252018-02-06 16:46:39 -08003287 for (const DisplayState& display : displays) {
3288 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003289 }
3290
chaviwca27f252018-02-06 16:46:39 -08003291 for (const ComposerState& state : states) {
3292 transactionFlags |= setClientStateLocked(state);
3293 }
3294
3295 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3296 // as destroyed should only occur after setting all other states. This is to allow for a
3297 // child re-parent to happen before marking its original parent as destroyed (which would
3298 // then mark the child as destroyed).
3299 for (const ComposerState& state : states) {
3300 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003301 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003302
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003303 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3304 // anyway. This can be used as a flush mechanism for previous async transactions.
3305 // Empty animation transaction can be used to simulate back-pressure, so also force a
3306 // transaction for empty animation transactions.
3307 if (transactionFlags == 0 &&
3308 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003309 transactionFlags = eTransactionNeeded;
3310 }
3311
Mathias Agopian386aa982011-11-07 21:58:03 -08003312 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003313 if (mInterceptor->isEnabled()) {
3314 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003315 }
Irvel468051e2016-06-13 16:44:44 -07003316
Mathias Agopian386aa982011-11-07 21:58:03 -08003317 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003318 const auto start = (flags & eEarlyWakeup)
3319 ? VSyncModulator::TransactionStart::EARLY
3320 : VSyncModulator::TransactionStart::NORMAL;
3321 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003322
3323 // if this is a synchronous transaction, wait for it to take effect
3324 // before returning.
3325 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003326 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003328 if (flags & eAnimation) {
3329 mAnimTransactionPending = true;
3330 }
3331 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003332 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3333 if (CC_UNLIKELY(err != NO_ERROR)) {
3334 // just in case something goes wrong in SF, return to the
3335 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003336 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3337 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003338 break;
3339 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003340 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003341 }
3342}
3343
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3345{
Jesse Hall9a143922012-10-04 16:29:19 -07003346 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3347 if (dpyIdx < 0)
3348 return 0;
3349
Mathias Agopiane57f2922012-08-09 16:29:12 -07003350 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003351 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003352 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003353 const uint32_t what = s.what;
3354 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003355 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356 disp.surface = s.surface;
3357 flags |= eDisplayTransactionNeeded;
3358 }
3359 }
3360 if (what & DisplayState::eLayerStackChanged) {
3361 if (disp.layerStack != s.layerStack) {
3362 disp.layerStack = s.layerStack;
3363 flags |= eDisplayTransactionNeeded;
3364 }
3365 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003366 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003367 if (disp.orientation != s.orientation) {
3368 disp.orientation = s.orientation;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 if (disp.frame != s.frame) {
3372 disp.frame = s.frame;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 if (disp.viewport != s.viewport) {
3376 disp.viewport = s.viewport;
3377 flags |= eDisplayTransactionNeeded;
3378 }
3379 }
Michael Lentine47e45402014-07-18 15:34:25 -07003380 if (what & DisplayState::eDisplaySizeChanged) {
3381 if (disp.width != s.width) {
3382 disp.width = s.width;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 if (disp.height != s.height) {
3386 disp.height = s.height;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003390 }
3391 return flags;
3392}
3393
chaviwca27f252018-02-06 16:46:39 -08003394uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3395 const layer_state_t& s = composerState.state;
3396 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3397
Mathias Agopian13127d82013-03-05 17:47:11 -08003398 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003399 if (layer == nullptr) {
3400 return 0;
3401 }
3402
3403 if (layer->isPendingRemoval()) {
3404 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3405 return 0;
3406 }
3407
3408 uint32_t flags = 0;
3409
3410 const uint32_t what = s.what;
3411 bool geometryAppliesWithResize =
3412 what & layer_state_t::eGeometryAppliesWithResize;
3413 if (what & layer_state_t::ePositionChanged) {
3414 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3415 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 }
3418 if (what & layer_state_t::eLayerChanged) {
3419 // NOTE: index needs to be calculated before we update the state
3420 const auto& p = layer->getParent();
3421 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003422 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003423 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424 mCurrentState.layersSortedByZ.removeAt(idx);
3425 mCurrentState.layersSortedByZ.add(layer);
3426 // we need traversal (state changed)
3427 // AND transaction (list changed)
3428 flags |= eTransactionNeeded|eTraversalNeeded;
3429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 } else {
3431 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003432 flags |= eTransactionNeeded|eTraversalNeeded;
3433 }
3434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 }
3436 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003437 // NOTE: index needs to be calculated before we update the state
3438 const auto& p = layer->getParent();
3439 if (p == nullptr) {
3440 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3441 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3442 mCurrentState.layersSortedByZ.removeAt(idx);
3443 mCurrentState.layersSortedByZ.add(layer);
3444 // we need traversal (state changed)
3445 // AND transaction (list changed)
3446 flags |= eTransactionNeeded|eTraversalNeeded;
3447 }
3448 } else {
3449 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3450 flags |= eTransactionNeeded|eTraversalNeeded;
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 }
3453 }
3454 if (what & layer_state_t::eSizeChanged) {
3455 if (layer->setSize(s.w, s.h)) {
3456 flags |= eTraversalNeeded;
3457 }
3458 }
3459 if (what & layer_state_t::eAlphaChanged) {
3460 if (layer->setAlpha(s.alpha))
3461 flags |= eTraversalNeeded;
3462 }
3463 if (what & layer_state_t::eColorChanged) {
3464 if (layer->setColor(s.color))
3465 flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eMatrixChanged) {
3468 if (layer->setMatrix(s.matrix))
3469 flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eTransparentRegionChanged) {
3472 if (layer->setTransparentRegionHint(s.transparentRegion))
3473 flags |= eTraversalNeeded;
3474 }
3475 if (what & layer_state_t::eFlagsChanged) {
3476 if (layer->setFlags(s.flags, s.mask))
3477 flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eCropChanged) {
3480 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3481 flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eFinalCropChanged) {
3484 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3485 flags |= eTraversalNeeded;
3486 }
3487 if (what & layer_state_t::eLayerStackChanged) {
3488 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3489 // We only allow setting layer stacks for top level layers,
3490 // everything else inherits layer stack from its parent.
3491 if (layer->hasParent()) {
3492 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3493 layer->getName().string());
3494 } else if (idx < 0) {
3495 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3496 "that also does not appear in the top level layer list. Something"
3497 " has gone wrong.", layer->getName().string());
3498 } else if (layer->setLayerStack(s.layerStack)) {
3499 mCurrentState.layersSortedByZ.removeAt(idx);
3500 mCurrentState.layersSortedByZ.add(layer);
3501 // we need traversal (state changed)
3502 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003503 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003504 }
3505 }
3506 if (what & layer_state_t::eDeferTransaction) {
3507 if (s.barrierHandle != nullptr) {
3508 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3509 } else if (s.barrierGbp != nullptr) {
3510 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3511 if (authenticateSurfaceTextureLocked(gbp)) {
3512 const auto& otherLayer =
3513 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3514 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3515 } else {
3516 ALOGE("Attempt to defer transaction to to an"
3517 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003518 }
3519 }
chaviw8b3871a2017-11-01 17:41:01 -07003520 // We don't trigger a traversal here because if no other state is
3521 // changed, we don't want this to cause any more work
3522 }
3523 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003524 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003525 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003526 if (!hadParent) {
3527 mCurrentState.layersSortedByZ.remove(layer);
3528 }
chaviw8b3871a2017-11-01 17:41:01 -07003529 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003530 }
chaviw8b3871a2017-11-01 17:41:01 -07003531 }
3532 if (what & layer_state_t::eReparentChildren) {
3533 if (layer->reparentChildren(s.reparentHandle)) {
3534 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003535 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 if (what & layer_state_t::eDetachChildren) {
3538 layer->detachChildren();
3539 }
3540 if (what & layer_state_t::eOverrideScalingModeChanged) {
3541 layer->setOverrideScalingMode(s.overrideScalingMode);
3542 // We don't trigger a traversal here because if no other state is
3543 // changed, we don't want this to cause any more work
3544 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003545 return flags;
3546}
3547
chaviwca27f252018-02-06 16:46:39 -08003548void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3549 const layer_state_t& state = composerState.state;
3550 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3551
3552 sp<Layer> layer(client->getLayerUser(state.surface));
3553 if (layer == nullptr) {
3554 return;
3555 }
3556
3557 if (layer->isPendingRemoval()) {
3558 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3559 return;
3560 }
3561
3562 if (state.what & layer_state_t::eDestroySurface) {
3563 removeLayerLocked(mStateLock, layer);
3564 }
3565}
3566
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003567status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003568 const String8& name,
3569 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003570 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003571 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003572 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003574 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003575 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003576 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003577 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003578 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003579
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003580 status_t result = NO_ERROR;
3581
3582 sp<Layer> layer;
3583
Cody Northropbc755282017-03-31 12:00:08 -06003584 String8 uniqueName = getUniqueLayerName(name);
3585
Mathias Agopian3165cc22012-08-08 19:42:09 -07003586 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3587 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003588 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003589 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 break;
chaviw13fdc492017-06-27 12:40:18 -07003593 case ISurfaceComposerClient::eFXSurfaceColor:
3594 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003595 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003596 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597 break;
3598 default:
3599 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 break;
3601 }
3602
Dan Stoza7d89d062015-04-30 13:29:25 -07003603 if (result != NO_ERROR) {
3604 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003605 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003606
Chia-I Wuab0c3192017-08-01 11:29:00 -07003607 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3608 // TODO b/64227542
3609 if (windowType == 441731) {
3610 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3611 layer->setPrimaryDisplayOnly();
3612 }
3613
Albert Chaulk479c60c2017-01-27 14:21:34 -05003614 layer->setInfo(windowType, ownerUid);
3615
Robert Carr1f0a16a2016-10-24 16:27:39 -07003616 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003617 if (result != NO_ERROR) {
3618 return result;
3619 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003620 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003621
3622 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003623 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003624}
3625
Cody Northropbc755282017-03-31 12:00:08 -06003626String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3627{
3628 bool matchFound = true;
3629 uint32_t dupeCounter = 0;
3630
3631 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3632 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3633
3634 // Loop over layers until we're sure there is no matching name
3635 while (matchFound) {
3636 matchFound = false;
3637 mDrawingState.traverseInZOrder([&](Layer* layer) {
3638 if (layer->getName() == uniqueName) {
3639 matchFound = true;
3640 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3641 }
3642 });
3643 }
3644
3645 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3646
3647 return uniqueName;
3648}
3649
David Sodman0c69cad2017-08-21 12:12:51 -07003650status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003651 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3652 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653{
3654 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003655 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656 case PIXEL_FORMAT_TRANSPARENT:
3657 case PIXEL_FORMAT_TRANSLUCENT:
3658 format = PIXEL_FORMAT_RGBA_8888;
3659 break;
3660 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003661 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662 break;
3663 }
3664
David Sodman0c69cad2017-08-21 12:12:51 -07003665 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3666 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003667 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003668 *handle = layer->getHandle();
3669 *gbp = layer->getProducer();
3670 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672
David Sodman0c69cad2017-08-21 12:12:51 -07003673 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003674 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675}
3676
chaviw13fdc492017-06-27 12:40:18 -07003677status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003678 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003679 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680{
chaviw13fdc492017-06-27 12:40:18 -07003681 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003682 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003683 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003684}
3685
Mathias Agopianac9fa422013-02-11 16:40:36 -08003686status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003687{
Robert Carr9524cb32017-02-13 11:32:32 -08003688 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003689 status_t err = NO_ERROR;
3690 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003691 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003692 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003693 err = removeLayer(l);
3694 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3695 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003696 }
3697 return err;
3698}
3699
Mathias Agopian13127d82013-03-05 17:47:11 -08003700status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003701{
Mathias Agopian67106042013-03-14 19:18:13 -07003702 // called by ~LayerCleaner() when all references to the IBinder (handle)
3703 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003704 sp<Layer> l = layer.promote();
3705 if (l == nullptr) {
3706 // The layer has already been removed, carry on
3707 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003708 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003709 // If we have a parent, then we can continue to live as long as it does.
3710 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711}
3712
Mathias Agopianb60314a2012-04-10 22:09:54 -07003713// ---------------------------------------------------------------------------
3714
Andy McFadden13a082e2012-08-24 10:16:42 -07003715void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003716 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003717 Vector<ComposerState> state;
3718 Vector<DisplayState> displays;
3719 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003720 d.what = DisplayState::eDisplayProjectionChanged |
3721 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003722 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003723 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003724 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003725 d.frame.makeInvalid();
3726 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003727 d.width = 0;
3728 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003729 displays.add(d);
3730 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003731 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3732 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003733
David Sodman105b7dc2017-11-04 20:28:14 -07003734 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003735 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003736 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003737
Brian Andersond0010582017-03-07 13:20:31 -08003738 // Use phase of 0 since phase is not known.
3739 // Use latency of 0, which will snap to the ideal latency.
3740 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003741}
3742
3743void SurfaceFlinger::initializeDisplays() {
3744 class MessageScreenInitialized : public MessageBase {
3745 SurfaceFlinger* flinger;
3746 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003747 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003748 virtual bool handler() {
3749 flinger->onInitializeDisplays();
3750 return true;
3751 }
3752 };
3753 sp<MessageBase> msg = new MessageScreenInitialized(this);
3754 postMessageAsync(msg); // we may be called from main thread, use async message
3755}
3756
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003757void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003758 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3760 this);
3761 int32_t type = hw->getDisplayType();
3762 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003763
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003765 return;
3766 }
3767
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003768 hw->setPowerMode(mode);
3769 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3770 ALOGW("Trying to set power mode for virtual display");
3771 return;
3772 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003773
Lloyd Pique4d234852018-01-22 17:21:36 -08003774 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003775 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003776 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3777 if (idx < 0) {
3778 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3779 return;
3780 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003781 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003782 }
3783
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003785 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003786 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003787 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3788 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003789 // FIXME: eventthread only knows about the main display right now
3790 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003791 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003792 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003795 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003796 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003797
3798 struct sched_param param = {0};
3799 param.sched_priority = 1;
3800 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3801 ALOGW("Couldn't set SCHED_FIFO on display on");
3802 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003804 // Turn off the display
3805 struct sched_param param = {0};
3806 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3807 ALOGW("Couldn't set SCHED_OTHER on display off");
3808 }
3809
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003810 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3811 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003812 disableHardwareVsync(true); // also cancels any in-progress resync
3813
Mathias Agopiancde87a32012-09-13 14:09:01 -07003814 // FIXME: eventthread only knows about the main display right now
3815 mEventThread->onScreenReleased();
3816 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003817
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003818 getHwComposer().setPowerMode(type, mode);
3819 mVisibleRegionsDirty = true;
3820 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003821 } else if (mode == HWC_POWER_MODE_DOZE ||
3822 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003823 // Update display while dozing
3824 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003825 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3826 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003827 // FIXME: eventthread only knows about the main display right now
3828 mEventThread->onScreenAcquired();
3829 resyncToHardwareVsync(true);
3830 }
3831 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3832 // Leave display going to doze
3833 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3834 disableHardwareVsync(true); // also cancels any in-progress resync
3835 // FIXME: eventthread only knows about the main display right now
3836 mEventThread->onScreenReleased();
3837 }
3838 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003839 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003840 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003841 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003842 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003843 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003844}
3845
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3847 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003848 SurfaceFlinger& mFlinger;
3849 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003850 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003851 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003852 MessageSetPowerMode(SurfaceFlinger& flinger,
3853 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3854 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003855 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003856 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003857 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003858 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003859 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003860 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003861 ALOGW("Attempt to set power mode = %d for virtual display",
3862 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003863 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003864 mFlinger.setPowerModeInternal(
3865 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003866 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003867 return true;
3868 }
3869 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003870 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003871 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003872}
3873
3874// ---------------------------------------------------------------------------
3875
Lloyd Pique755e3192018-01-31 16:46:15 -08003876status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3877 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003879
Mathias Agopianbd115332013-04-18 16:41:04 -07003880 IPCThreadState* ipc = IPCThreadState::self();
3881 const int pid = ipc->getCallingPid();
3882 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003883
Mathias Agopianbd115332013-04-18 16:41:04 -07003884 if ((uid != AID_SHELL) &&
3885 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003886 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003887 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003889 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003890 // (this would indicate SF is stuck, but we want to be able to
3891 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003892 status_t err = mStateLock.timedLock(s2ns(1));
3893 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003894 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003895 result.appendFormat(
3896 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3897 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003898 }
3899
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003900 bool dumpAll = true;
3901 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003902 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003903
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003904 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003905 if ((index < numArgs) &&
3906 (args[index] == String16("--list"))) {
3907 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003908 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003909 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003910 }
3911
3912 if ((index < numArgs) &&
3913 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003914 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003915 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003916 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003917 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003918
3919 if ((index < numArgs) &&
3920 (args[index] == String16("--latency-clear"))) {
3921 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003922 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003923 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003924 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003925
3926 if ((index < numArgs) &&
3927 (args[index] == String16("--dispsync"))) {
3928 index++;
3929 mPrimaryDispSync.dump(result);
3930 dumpAll = false;
3931 }
Dan Stozab90cf072015-03-05 11:05:59 -08003932
3933 if ((index < numArgs) &&
3934 (args[index] == String16("--static-screen"))) {
3935 index++;
3936 dumpStaticScreenStats(result);
3937 dumpAll = false;
3938 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003939
3940 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003941 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003942 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003943 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003944 dumpAll = false;
3945 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003946
3947 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3948 index++;
3949 dumpWideColorInfo(result);
3950 dumpAll = false;
3951 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003952
3953 if ((index < numArgs) &&
3954 (args[index] == String16("--enable-layer-stats"))) {
3955 index++;
3956 mLayerStats.enable();
3957 dumpAll = false;
3958 }
3959
3960 if ((index < numArgs) &&
3961 (args[index] == String16("--disable-layer-stats"))) {
3962 index++;
3963 mLayerStats.disable();
3964 dumpAll = false;
3965 }
3966
3967 if ((index < numArgs) &&
3968 (args[index] == String16("--clear-layer-stats"))) {
3969 index++;
3970 mLayerStats.clear();
3971 dumpAll = false;
3972 }
3973
3974 if ((index < numArgs) &&
3975 (args[index] == String16("--dump-layer-stats"))) {
3976 index++;
3977 mLayerStats.dump(result);
3978 dumpAll = false;
3979 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003980
3981 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3982 index++;
3983 mTimeStats.parseArgs(asProto, args, index, result);
3984 dumpAll = false;
3985 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003987
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003988 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003989 if (asProto) {
3990 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3991 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3992 } else {
3993 dumpAllLocked(args, index, result);
3994 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003995 }
3996
Mathias Agopian9795c422009-08-26 16:36:26 -07003997 if (locked) {
3998 mStateLock.unlock();
3999 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 }
4001 write(fd, result.string(), result.size());
4002 return NO_ERROR;
4003}
4004
Dan Stozac7014012014-02-14 15:03:43 -08004005void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4006 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007{
Robert Carr2047fae2016-11-28 14:09:09 -08004008 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004009 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004010 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011}
4012
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004013void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004014 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004015{
4016 String8 name;
4017 if (index < args.size()) {
4018 name = String8(args[index]);
4019 index++;
4020 }
4021
David Sodman105b7dc2017-11-04 20:28:14 -07004022 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004023 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004024 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004025
4026 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004027 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004028 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004029 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004030 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004031 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004032 }
Robert Carr2047fae2016-11-28 14:09:09 -08004033 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004034 }
4035}
4036
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004037void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004038 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004039{
4040 String8 name;
4041 if (index < args.size()) {
4042 name = String8(args[index]);
4043 index++;
4044 }
4045
Robert Carr2047fae2016-11-28 14:09:09 -08004046 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004047 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004048 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049 }
Robert Carr2047fae2016-11-28 14:09:09 -08004050 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004051
Svetoslavd85084b2014-03-20 10:28:31 -07004052 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004053}
4054
Jamie Gennis6547ff42013-07-16 20:12:42 -07004055// This should only be called from the main thread. Otherwise it would need
4056// the lock and should use mCurrentState rather than mDrawingState.
4057void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004058 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004059 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004060 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004061
4062 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4063}
4064
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004065void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004066{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004067 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004068
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004069 if (isLayerTripleBufferingDisabled())
4070 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004071
4072 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004073 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004074 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004075 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004076 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4077 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004078 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004079}
4080
Dan Stozab90cf072015-03-05 11:05:59 -08004081void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4082{
4083 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004084 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4085 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004086 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004087 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004088 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4089 b + 1, bucketTimeSec, percent);
4090 }
David Sodman4a36e932017-11-07 14:29:47 -08004091 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004092 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004093 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004094 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004095 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004096}
4097
Dan Stozae77c7662016-05-13 11:37:28 -07004098void SurfaceFlinger::recordBufferingStats(const char* layerName,
4099 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004100 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4101 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004102 for (const auto& segment : history) {
4103 if (!segment.usedThirdBuffer) {
4104 stats.twoBufferTime += segment.totalTime;
4105 }
4106 if (segment.occupancyAverage < 1.0f) {
4107 stats.doubleBufferedTime += segment.totalTime;
4108 } else if (segment.occupancyAverage < 2.0f) {
4109 stats.tripleBufferedTime += segment.totalTime;
4110 }
4111 ++stats.numSegments;
4112 stats.totalTime += segment.totalTime;
4113 }
4114}
4115
Brian Andersond6927fb2016-07-23 23:37:30 -07004116void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4117 result.appendFormat("Layer frame timestamps:\n");
4118
4119 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4120 const size_t count = currentLayers.size();
4121 for (size_t i=0 ; i<count ; i++) {
4122 currentLayers[i]->dumpFrameEvents(result);
4123 }
4124}
4125
Dan Stozae77c7662016-05-13 11:37:28 -07004126void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4127 result.append("Buffering stats:\n");
4128 result.append(" [Layer name] <Active time> <Two buffer> "
4129 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004130 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004131 typedef std::tuple<std::string, float, float, float> BufferTuple;
4132 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004133 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004134 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004135 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004136 if (stats.numSegments == 0) {
4137 continue;
4138 }
4139 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4140 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4141 stats.totalTime;
4142 float doubleBufferRatio = static_cast<float>(
4143 stats.doubleBufferedTime) / stats.totalTime;
4144 float tripleBufferRatio = static_cast<float>(
4145 stats.tripleBufferedTime) / stats.totalTime;
4146 sorted.insert({activeTime, {name, twoBufferRatio,
4147 doubleBufferRatio, tripleBufferRatio}});
4148 }
4149 for (const auto& sortedPair : sorted) {
4150 float activeTime = sortedPair.first;
4151 const BufferTuple& values = sortedPair.second;
4152 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4153 std::get<0>(values).c_str(), activeTime,
4154 std::get<1>(values), std::get<2>(values),
4155 std::get<3>(values));
4156 }
4157 result.append("\n");
4158}
4159
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004160void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4161 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004162 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004163
4164 // TODO: print out if wide-color mode is active or not
4165
4166 for (size_t d = 0; d < mDisplays.size(); d++) {
4167 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4168 int32_t hwcId = displayDevice->getHwcDisplayId();
4169 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4170 continue;
4171 }
4172
4173 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004174 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175 for (auto&& mode : modes) {
4176 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4177 }
4178
Peiyong Lina52f0292018-03-14 17:26:31 -07004179 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004180 result.appendFormat(" Current color mode: %s (%d)\n",
4181 decodeColorMode(currentMode).c_str(), currentMode);
4182 }
4183 result.append("\n");
4184}
4185
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004186LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004187 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004188 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4189 const State& state = useDrawing ? mDrawingState : mCurrentState;
4190 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004191 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004192 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004193 });
4194
4195 return layersProto;
4196}
4197
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004198LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4199 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004200 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004201
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004202 SizeProto* resolution = layersProto.mutable_resolution();
4203 resolution->set_w(displayDevice->getWidth());
4204 resolution->set_h(displayDevice->getHeight());
4205
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004206 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4207 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4208 layersProto.set_global_transform(
4209 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4210
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004211 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004212 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004213 LayerProto* layerProto = layersProto.add_layers();
4214 layer->writeToProto(layerProto, hwcId);
4215 }
4216 });
4217
4218 return layersProto;
4219}
4220
Mathias Agopian74d211a2013-04-22 16:55:35 +02004221void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4222 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004223{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004224 bool colorize = false;
4225 if (index < args.size()
4226 && (args[index] == String16("--color"))) {
4227 colorize = true;
4228 index++;
4229 }
4230
4231 Colorizer colorizer(colorize);
4232
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233 // figure out if we're stuck somewhere
4234 const nsecs_t now = systemTime();
4235 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4236 const nsecs_t inTransaction(mDebugInTransaction);
4237 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4238 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4239
4240 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004241 * Dump library configuration.
4242 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004243
4244 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004245 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004246 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004247 appendSfConfigString(result);
4248 appendUiConfigString(result);
4249 appendGuiConfigString(result);
4250 result.append("\n");
4251
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004252 result.append("\nWide-Color information:\n");
4253 dumpWideColorInfo(result);
4254
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004255 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004256 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004258 result.append(SyncFeatures::getInstance().toString());
4259 result.append("\n");
4260
David Sodman105b7dc2017-11-04 20:28:14 -07004261 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004262
Andy McFadden41d67d72014-04-25 16:58:34 -07004263 colorizer.bold(result);
4264 result.append("DispSync configuration: ");
4265 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004266 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4267 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4268 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004269 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004270 result.append("\n");
4271
Dan Stozab90cf072015-03-05 11:05:59 -08004272 // Dump static screen stats
4273 result.append("\n");
4274 dumpStaticScreenStats(result);
4275 result.append("\n");
4276
Dan Stozae77c7662016-05-13 11:37:28 -07004277 dumpBufferingStats(result);
4278
Andy McFadden4803b742012-09-24 19:07:20 -07004279 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280 * Dump the visible layer list
4281 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004282 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004283 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004284 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4285 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004286 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004287
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004288 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004289 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004290 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004291 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292
4293 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004294 * Dump Display state
4295 */
4296
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004298 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004300 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4301 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004302 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004303 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004304 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004305
4306 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307 * Dump SurfaceFlinger global state
4308 */
4309
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004310 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004311 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004312 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
Mathias Agopian888c8222012-08-04 21:10:38 -07004314 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004315 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004316
David Sodmanbc815282017-11-05 18:57:52 -08004317 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004319 if (hw) {
4320 hw->undefinedRegion.dump(result, "undefinedRegion");
4321 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4322 hw->getOrientation(), hw->isDisplayOn());
4323 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004324 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004325 " last eglSwapBuffers() time: %f us\n"
4326 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004327 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 " refresh-rate : %f fps\n"
4329 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004330 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004331 " gpu_to_cpu_unsupported : %d\n"
4332 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 mLastSwapBufferTime/1000.0,
4334 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004335 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004336 1e9 / activeConfig->getVsyncPeriod(),
4337 activeConfig->getDpiX(),
4338 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004339 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340
Mathias Agopian74d211a2013-04-22 16:55:35 +02004341 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343
Mathias Agopian74d211a2013-04-22 16:55:35 +02004344 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346
4347 /*
4348 * VSYNC state
4349 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004351 result.append("\n");
4352
4353 /*
4354 * HWC layer minidump
4355 */
4356 for (size_t d = 0; d < mDisplays.size(); d++) {
4357 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4358 int32_t hwcId = displayDevice->getHwcDisplayId();
4359 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4360 continue;
4361 }
4362
4363 result.appendFormat("Display %d HWC layers:\n", hwcId);
4364 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004365 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004366 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004367 });
Dan Stozae22aec72016-08-01 13:20:59 -07004368 result.append("\n");
4369 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004370
4371 /*
4372 * Dump HWComposer state
4373 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004374 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004375 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004376 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004377 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004378 result.appendFormat(" h/w composer %s\n",
4379 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004380 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381
4382 /*
4383 * Dump gralloc state
4384 */
4385 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4386 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004387
4388 /*
4389 * Dump VrFlinger state if in use.
4390 */
4391 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4392 result.append("VrFlinger state:\n");
4393 result.append(mVrFlinger->Dump().c_str());
4394 result.append("\n");
4395 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396}
4397
Mathias Agopian13127d82013-03-05 17:47:11 -08004398const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004399SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004400 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004401 wp<IBinder> dpy;
4402 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4403 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4404 dpy = mDisplays.keyAt(i);
4405 break;
4406 }
4407 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004408 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004409 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4410 // Just use the primary display so we have something to return
4411 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4412 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004413 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004414}
4415
Keun young Park63f165f2012-08-31 10:53:36 -07004416bool SurfaceFlinger::startDdmConnection()
4417{
4418 void* libddmconnection_dso =
4419 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4420 if (!libddmconnection_dso) {
4421 return false;
4422 }
4423 void (*DdmConnection_start)(const char* name);
4424 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004425 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004426 if (!DdmConnection_start) {
4427 dlclose(libddmconnection_dso);
4428 return false;
4429 }
4430 (*DdmConnection_start)(getServiceName());
4431 return true;
4432}
4433
Chia-I Wu28f320b2018-05-03 11:02:56 -07004434void SurfaceFlinger::updateColorMatrixLocked() {
4435 mat4 colorMatrix;
4436 if (mGlobalSaturationFactor != 1.0f) {
4437 // Rec.709 luma coefficients
4438 float3 luminance{0.213f, 0.715f, 0.072f};
4439 luminance *= 1.0f - mGlobalSaturationFactor;
4440 mat4 saturationMatrix = mat4(
4441 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4442 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4443 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4444 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4445 );
4446 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4447 } else {
4448 colorMatrix = mClientColorMatrix * mDaltonizer();
4449 }
4450
4451 if (mCurrentState.colorMatrix != colorMatrix) {
4452 mCurrentState.colorMatrix = colorMatrix;
4453 mCurrentState.colorMatrixChanged = true;
4454 setTransactionFlags(eTransactionNeeded);
4455 }
4456}
4457
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004458status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 switch (code) {
4460 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004461 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004462 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004463 case CLEAR_ANIMATION_FRAME_STATS:
4464 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004465 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004466 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004467 case ENABLE_VSYNC_INJECTIONS:
4468 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004469 {
4470 // codes that require permission check
4471 IPCThreadState* ipc = IPCThreadState::self();
4472 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004473 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004474 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004475 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004476 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004477 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004479 break;
4480 }
Robert Carr1db73f62016-12-21 12:58:51 -08004481 /*
4482 * Calling setTransactionState is safe, because you need to have been
4483 * granted a reference to Client* and Handle* to do anything with it.
4484 *
4485 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4486 */
4487 case SET_TRANSACTION_STATE:
4488 case CREATE_SCOPED_CONNECTION:
4489 {
4490 return OK;
4491 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004492 case CAPTURE_SCREEN:
4493 {
4494 // codes that require permission check
4495 IPCThreadState* ipc = IPCThreadState::self();
4496 const int pid = ipc->getCallingPid();
4497 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004498 if ((uid != AID_GRAPHICS) &&
4499 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004500 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004501 return PERMISSION_DENIED;
4502 }
4503 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004504 }
chaviwa76b2712017-09-20 12:02:26 -07004505 case CAPTURE_LAYERS: {
4506 IPCThreadState* ipc = IPCThreadState::self();
4507 const int pid = ipc->getCallingPid();
4508 const int uid = ipc->getCallingUid();
4509 if ((uid != AID_GRAPHICS) &&
4510 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4511 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4512 return PERMISSION_DENIED;
4513 }
4514 break;
4515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004517 return OK;
4518}
4519
4520status_t SurfaceFlinger::onTransact(
4521 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4522{
4523 status_t credentialCheck = CheckTransactCodeCredentials(code);
4524 if (credentialCheck != OK) {
4525 return credentialCheck;
4526 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4529 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004530 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004531 IPCThreadState* ipc = IPCThreadState::self();
4532 const int uid = ipc->getCallingUid();
4533 if (CC_UNLIKELY(uid != AID_SYSTEM
4534 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004535 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004536 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004537 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 return PERMISSION_DENIED;
4539 }
4540 int n;
4541 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004542 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004543 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 return NO_ERROR;
4545 case 1002: // SHOW_UPDATES
4546 n = data.readInt32();
4547 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004548 invalidateHwcGeometry();
4549 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004552 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004553 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004554 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004555 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004556 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004557 setTransactionFlags(
4558 eTransactionNeeded|
4559 eDisplayTransactionNeeded|
4560 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004561 return NO_ERROR;
4562 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004563 case 1006:{ // send empty update
4564 signalRefresh();
4565 return NO_ERROR;
4566 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004567 case 1008: // toggle use of hw composer
4568 n = data.readInt32();
4569 mDebugDisableHWC = n ? 1 : 0;
4570 invalidateHwcGeometry();
4571 repaintEverything();
4572 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004573 case 1009: // toggle use of transform hint
4574 n = data.readInt32();
4575 mDebugDisableTransformHint = n ? 1 : 0;
4576 invalidateHwcGeometry();
4577 repaintEverything();
4578 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004580 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004581 reply->writeInt32(0);
4582 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004583 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004584 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585 return NO_ERROR;
4586 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004587 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004588 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004589 return NO_ERROR;
4590 }
4591 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004592 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004593 // daltonize
4594 n = data.readInt32();
4595 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004596 case 1:
4597 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4598 break;
4599 case 2:
4600 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4601 break;
4602 case 3:
4603 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4604 break;
4605 default:
4606 mDaltonizer.setType(ColorBlindnessType::None);
4607 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004608 }
4609 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004610 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004611 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004612 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004613 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004614
4615 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004616 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004617 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004618 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004619 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004620 // apply a color matrix
4621 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004622 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004623 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004624 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004625 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004626 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004627 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004628 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004629 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004630 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004631 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004632
4633 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4634 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004635 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004636 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4637 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4638 }
4639
Chia-I Wu28f320b2018-05-03 11:02:56 -07004640 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 return NO_ERROR;
4642 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004643 // This is an experimental interface
4644 // Needs to be shifted to proper binder interface when we productize
4645 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004646 n = data.readInt32();
4647 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004648 return NO_ERROR;
4649 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004650 case 1017: {
4651 n = data.readInt32();
4652 mForceFullDamage = static_cast<bool>(n);
4653 return NO_ERROR;
4654 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004655 case 1018: { // Modify Choreographer's phase offset
4656 n = data.readInt32();
4657 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4658 return NO_ERROR;
4659 }
4660 case 1019: { // Modify SurfaceFlinger's phase offset
4661 n = data.readInt32();
4662 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4663 return NO_ERROR;
4664 }
Irvel468051e2016-06-13 16:44:44 -07004665 case 1020: { // Layer updates interceptor
4666 n = data.readInt32();
4667 if (n) {
4668 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004669 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004670 }
4671 else{
4672 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004673 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004674 }
4675 return NO_ERROR;
4676 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004677 case 1021: { // Disable HWC virtual displays
4678 n = data.readInt32();
4679 mUseHwcVirtualDisplays = !n;
4680 return NO_ERROR;
4681 }
Romain Guy0147a172017-06-01 13:53:56 -07004682 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004683 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004684 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004685
Chia-I Wu28f320b2018-05-03 11:02:56 -07004686 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004687 return NO_ERROR;
4688 }
Romain Guy54f154a2017-10-24 21:40:32 +01004689 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004690 int32_t value = data.readInt32();
4691 if (value > 2) {
4692 return BAD_VALUE;
4693 }
4694 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4695 return BAD_VALUE;
4696 }
Romain Guy54f154a2017-10-24 21:40:32 +01004697
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004698 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004699 invalidateHwcGeometry();
4700 repaintEverything();
4701 return NO_ERROR;
4702 }
4703 case 1024: { // Is wide color gamut rendering/color management supported?
4704 reply->writeBool(hasWideColorDisplay);
4705 return NO_ERROR;
4706 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004707 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004708 n = data.readInt32();
4709 if (n) {
4710 ALOGV("LayerTracing enabled");
4711 mTracing.enable();
4712 doTracing("tracing.enable");
4713 reply->writeInt32(NO_ERROR);
4714 } else {
4715 ALOGV("LayerTracing disabled");
4716 status_t err = mTracing.disable();
4717 reply->writeInt32(err);
4718 }
4719 return NO_ERROR;
4720 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004721 case 1026: { // Get layer tracing status
4722 reply->writeBool(mTracing.isEnabled());
4723 return NO_ERROR;
4724 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004725 // Is a DisplayColorSetting supported?
4726 case 1027: {
4727 int32_t value = data.readInt32();
4728 switch (value) {
4729 case 0:
4730 reply->writeBool(hasWideColorDisplay);
4731 return NO_ERROR;
4732 case 1:
4733 reply->writeBool(true);
4734 return NO_ERROR;
4735 case 2:
4736 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4737 return NO_ERROR;
4738 default:
4739 return BAD_VALUE;
4740 }
4741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 }
4743 }
4744 return err;
4745}
4746
Steven Thomas6d8110b2017-08-31 18:24:21 -07004747void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004748 android_atomic_or(1, &mRepaintEverything);
4749 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004750}
4751
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004752// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4753class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004754public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004755 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4756 ~WindowDisconnector() {
4757 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004758 }
4759
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004760private:
4761 ANativeWindow* mWindow;
4762 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004763};
4764
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004765status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4766 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4767 int32_t minLayerZ, int32_t maxLayerZ,
4768 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004769 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004770 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004771
chaviwa76b2712017-09-20 12:02:26 -07004772 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4773
4774 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004775 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4776
chaviwa76b2712017-09-20 12:02:26 -07004777 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4778
4779 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4780 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004781 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004782}
4783
4784status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004785 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004786 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004787 ATRACE_CALL();
4788
4789 class LayerRenderArea : public RenderArea {
4790 public:
Robert Carr578038f2018-03-09 12:25:24 -08004791 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4792 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004793 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004794 mLayer(layer),
4795 mCrop(crop),
4796 mFlinger(flinger),
4797 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004798 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004799 Rect getBounds() const override {
4800 const Layer::State& layerState(mLayer->getDrawingState());
4801 return Rect(layerState.active.w, layerState.active.h);
4802 }
4803 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4804 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4805 bool isSecure() const override { return false; }
4806 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004807 Rect getSourceCrop() const override {
4808 if (mCrop.isEmpty()) {
4809 return getBounds();
4810 } else {
4811 return mCrop;
4812 }
4813 }
Robert Carr578038f2018-03-09 12:25:24 -08004814 class ReparentForDrawing {
4815 public:
4816 const sp<Layer>& oldParent;
4817 const sp<Layer>& newParent;
4818
4819 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4820 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004821 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004822 }
Robert Carr15eae092018-03-23 13:43:53 -07004823 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004824 };
4825
4826 void render(std::function<void()> drawLayers) override {
4827 if (!mChildrenOnly) {
4828 mTransform = mLayer->getTransform().inverse();
4829 drawLayers();
4830 } else {
4831 Rect bounds = getBounds();
4832 screenshotParentLayer =
4833 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4834 bounds.getWidth(), bounds.getHeight(), 0);
4835
4836 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4837 drawLayers();
4838 }
4839 }
chaviwa76b2712017-09-20 12:02:26 -07004840
chaviwa76b2712017-09-20 12:02:26 -07004841 private:
chaviw7206d492017-11-10 16:16:12 -08004842 const sp<Layer> mLayer;
4843 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004844
4845 // In the "childrenOnly" case we reparent the children to a screenshot
4846 // layer which has no properties set and which does not draw.
4847 sp<ContainerLayer> screenshotParentLayer;
4848 Transform mTransform;
4849
4850 SurfaceFlinger* mFlinger;
4851 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004852 };
4853
4854 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4855 auto parent = layerHandle->owner.promote();
4856
chaviw7206d492017-11-10 16:16:12 -08004857 if (parent == nullptr || parent->isPendingRemoval()) {
4858 ALOGE("captureLayers called with a removed parent");
4859 return NAME_NOT_FOUND;
4860 }
4861
Robert Carr578038f2018-03-09 12:25:24 -08004862 const int uid = IPCThreadState::self()->getCallingUid();
4863 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4864 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4865 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4866 return PERMISSION_DENIED;
4867 }
4868
chaviw7206d492017-11-10 16:16:12 -08004869 Rect crop(sourceCrop);
4870 if (sourceCrop.width() <= 0) {
4871 crop.left = 0;
4872 crop.right = parent->getCurrentState().active.w;
4873 }
4874
4875 if (sourceCrop.height() <= 0) {
4876 crop.top = 0;
4877 crop.bottom = parent->getCurrentState().active.h;
4878 }
4879
4880 int32_t reqWidth = crop.width() * frameScale;
4881 int32_t reqHeight = crop.height() * frameScale;
4882
Robert Carr578038f2018-03-09 12:25:24 -08004883 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004884
Robert Carr578038f2018-03-09 12:25:24 -08004885 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004886 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4887 if (!layer->isVisible()) {
4888 return;
Robert Carr578038f2018-03-09 12:25:24 -08004889 } else if (childrenOnly && layer == parent.get()) {
4890 return;
chaviwa76b2712017-09-20 12:02:26 -07004891 }
4892 visitor(layer);
4893 });
4894 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004895 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004896}
4897
4898status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4899 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004900 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004901 bool useIdentityTransform) {
4902 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004903
chaviwa76b2712017-09-20 12:02:26 -07004904 renderArea.updateDimensions();
4905
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004906 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4907 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4908 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4909 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004910
4911 // This mutex protects syncFd and captureResult for communication of the return values from the
4912 // main thread back to this Binder thread
4913 std::mutex captureMutex;
4914 std::condition_variable captureCondition;
4915 std::unique_lock<std::mutex> captureLock(captureMutex);
4916 int syncFd = -1;
4917 std::optional<status_t> captureResult;
4918
Robert Carr03480e22018-01-04 16:02:06 -08004919 const int uid = IPCThreadState::self()->getCallingUid();
4920 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4921
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004922 sp<LambdaMessage> message = new LambdaMessage([&]() {
4923 // If there is a refresh pending, bug out early and tell the binder thread to try again
4924 // after the refresh.
4925 if (mRefreshPending) {
4926 ATRACE_NAME("Skipping screenshot for now");
4927 std::unique_lock<std::mutex> captureLock(captureMutex);
4928 captureResult = std::make_optional<status_t>(EAGAIN);
4929 captureCondition.notify_one();
4930 return;
4931 }
4932
4933 status_t result = NO_ERROR;
4934 int fd = -1;
4935 {
4936 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004937 renderArea.render([&]() {
4938 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4939 useIdentityTransform, forSystem, &fd);
4940 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004941 }
4942
4943 {
4944 std::unique_lock<std::mutex> captureLock(captureMutex);
4945 syncFd = fd;
4946 captureResult = std::make_optional<status_t>(result);
4947 captureCondition.notify_one();
4948 }
4949 });
4950
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004951 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004952 if (result == NO_ERROR) {
4953 captureCondition.wait(captureLock, [&]() { return captureResult; });
4954 while (*captureResult == EAGAIN) {
4955 captureResult.reset();
4956 result = postMessageAsync(message);
4957 if (result != NO_ERROR) {
4958 return result;
4959 }
4960 captureCondition.wait(captureLock, [&]() { return captureResult; });
4961 }
4962 result = *captureResult;
4963 }
4964
4965 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004966 sync_wait(syncFd, -1);
4967 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004968 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004969
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004970 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004971}
4972
chaviwa76b2712017-09-20 12:02:26 -07004973void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4974 TraverseLayersFunction traverseLayers, bool yswap,
4975 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004976 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004977
Lloyd Pique144e1162017-12-20 16:44:52 -08004978 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004979
4980 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004981 const auto raWidth = renderArea.getWidth();
4982 const auto raHeight = renderArea.getHeight();
4983
4984 const auto reqWidth = renderArea.getReqWidth();
4985 const auto reqHeight = renderArea.getReqHeight();
4986 Rect sourceCrop = renderArea.getSourceCrop();
4987
4988 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4989 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004990
Dan Stozac1879002014-05-22 15:59:05 -07004991 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004992 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004993 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004994 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004995 }
4996
4997 // ensure that sourceCrop is inside screen
4998 if (sourceCrop.left < 0) {
4999 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5000 }
chaviwa76b2712017-09-20 12:02:26 -07005001 if (sourceCrop.right > raWidth) {
5002 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005003 }
5004 if (sourceCrop.top < 0) {
5005 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5006 }
chaviwa76b2712017-09-20 12:02:26 -07005007 if (sourceCrop.bottom > raHeight) {
5008 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005009 }
5010
Chia-I Wu36574d92018-05-16 10:54:36 -07005011 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5012 engine.setOutputDataSpace(Dataspace::SRGB);
5013 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005014
Mathias Agopian180f10d2013-04-10 22:55:41 -07005015 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005016 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005017
5018 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005019 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5020 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005021 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005022
chaviw50da5042018-04-09 13:49:37 -07005023 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005024 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005025 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005026
chaviwa76b2712017-09-20 12:02:26 -07005027 traverseLayers([&](Layer* layer) {
5028 if (filtering) layer->setFiltering(true);
5029 layer->draw(renderArea, useIdentityTransform);
5030 if (filtering) layer->setFiltering(false);
5031 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005032}
5033
chaviwa76b2712017-09-20 12:02:26 -07005034status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5035 TraverseLayersFunction traverseLayers,
5036 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005037 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005038 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005039 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005040 ATRACE_CALL();
5041
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005042 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005043
5044 traverseLayers([&](Layer* layer) {
5045 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5046 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005047
Robert Carr03480e22018-01-04 16:02:06 -08005048 // We allow the system server to take screenshots of secure layers for
5049 // use in situations like the Screen-rotation animation and place
5050 // the impetus on WindowManager to not persist them.
5051 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005052 ALOGW("FB is protected: PERMISSION_DENIED");
5053 return PERMISSION_DENIED;
5054 }
5055
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005056 // this binds the given EGLImage as a framebuffer for the
5057 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005058 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005059 if (bufferBond.getStatus() != NO_ERROR) {
5060 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005061 return INVALID_OPERATION;
5062 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005063
Dan Stozaabcda352017-06-01 14:37:39 -07005064 // this will in fact render into our dequeued buffer
5065 // via an FBO, which means we didn't have to create
5066 // an EGLSurface and therefore we're not
5067 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005068 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005069
Dan Stozaabcda352017-06-01 14:37:39 -07005070 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005071 getRenderEngine().finish();
5072 *outSyncFd = -1;
5073
chaviwa76b2712017-09-20 12:02:26 -07005074 const auto reqWidth = renderArea.getReqWidth();
5075 const auto reqHeight = renderArea.getReqHeight();
5076
Dan Stozaabcda352017-06-01 14:37:39 -07005077 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5078 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005079 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005080 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005081 } else {
5082 base::unique_fd syncFd = getRenderEngine().flush();
5083 if (syncFd < 0) {
5084 getRenderEngine().finish();
5085 }
5086 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005087 }
5088
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005089 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005090}
5091
Mathias Agopiand5556842013-09-19 17:08:37 -07005092void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005093 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005094 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005095 for (size_t y = 0; y < h; y++) {
5096 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5097 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005098 if (p[x] != 0xFF000000) return;
5099 }
5100 }
chaviwa76b2712017-09-20 12:02:26 -07005101 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005102
Robert Carr2047fae2016-11-28 14:09:09 -08005103 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005104 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005105 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005106 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5107 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5108 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5109 static_cast<float>(state.color.a));
5110 i++;
5111 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005112 }
5113}
5114
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005115// ---------------------------------------------------------------------------
5116
Dan Stoza412903f2017-04-27 13:42:17 -07005117void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5118 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005119}
5120
Dan Stoza412903f2017-04-27 13:42:17 -07005121void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5122 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005123}
5124
chaviwa76b2712017-09-20 12:02:26 -07005125void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5126 int32_t maxLayerZ,
5127 const LayerVector::Visitor& visitor) {
5128 // We loop through the first level of layers without traversing,
5129 // as we need to interpret min/max layer Z in the top level Z space.
5130 for (const auto& layer : mDrawingState.layersSortedByZ) {
5131 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5132 continue;
5133 }
5134 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005135 // relative layers are traversed in Layer::traverseInZOrder
5136 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005137 continue;
5138 }
5139 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005140 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5141 return;
5142 }
chaviwa76b2712017-09-20 12:02:26 -07005143 if (!layer->isVisible()) {
5144 return;
5145 }
5146 visitor(layer);
5147 });
5148 }
5149}
5150
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005151}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005152
5153
5154#if defined(__gl_h_)
5155#error "don't include gl/gl.h in this file"
5156#endif
5157
5158#if defined(__gl2_h_)
5159#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005160#endif