blob: 588d24c45fd941930bcd1de4954b5ef157788891 [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
Dan Stoza0a0158c2018-03-16 13:38:54 -0700319 // TODO (b/74616334): Reduce the default value once we isolate the leak
320 const size_t defaultListSize = 4 * MAX_LAYERS;
321 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
322 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
323
Dan Stoza2713c302018-03-28 17:07:36 -0700324 property_get("debug.sf.early_phase_offset_ns", value, "0");
325 const int earlyWakeupOffsetOffsetNs = atoi(value);
326 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
327 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
328 sfVsyncPhaseOffsetNs);
329
Romain Guy11d63f42017-07-20 12:47:14 -0700330 // We should be reading 'persist.sys.sf.color_saturation' here
331 // but since /data may be encrypted, we need to wait until after vold
332 // comes online to attempt to read the property. The property is
333 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800334
335 if (useTrebleTestingOverride()) {
336 // Without the override SurfaceFlinger cannot connect to HIDL
337 // services that are not listed in the manifests. Considered
338 // deriving the setting from the set service name, but it
339 // would be brittle if the name that's not 'default' is used
340 // for production purposes later on.
341 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800345void SurfaceFlinger::onFirstRef()
346{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800347 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800348}
349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350SurfaceFlinger::~SurfaceFlinger()
351{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352}
353
Dan Stozac7014012014-02-14 15:03:43 -0800354void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355{
356 // the window manager died on us. prepare its eulogy.
357
Andy McFadden13a082e2012-08-24 10:16:42 -0700358 // restore initial conditions (default device unblank, etc)
359 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800360
361 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363}
364
Robert Carr1db73f62016-12-21 12:58:51 -0800365static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700366 status_t err = client->initCheck();
367 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800368 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369 }
Robert Carr1db73f62016-12-21 12:58:51 -0800370 return nullptr;
371}
372
373sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
374 return initClient(new Client(this));
375}
376
377sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
378 const sp<IGraphicBufferProducer>& gbp) {
379 if (authenticateSurfaceTexture(gbp) == false) {
380 return nullptr;
381 }
382 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
383 if (layer == nullptr) {
384 return nullptr;
385 }
386
387 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388}
389
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700390sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
391 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700392{
393 class DisplayToken : public BBinder {
394 sp<SurfaceFlinger> flinger;
395 virtual ~DisplayToken() {
396 // no more references, this display must be terminated
397 Mutex::Autolock _l(flinger->mStateLock);
398 flinger->mCurrentState.displays.removeItem(this);
399 flinger->setTransactionFlags(eDisplayTransactionNeeded);
400 }
401 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700402 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403 : flinger(flinger) {
404 }
405 };
406
407 sp<BBinder> token = new DisplayToken(this);
408
409 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700410 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700411 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700412 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800413 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 return token;
415}
416
Jesse Hall6c913be2013-08-08 12:15:49 -0700417void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
418 Mutex::Autolock _l(mStateLock);
419
420 ssize_t idx = mCurrentState.displays.indexOfKey(display);
421 if (idx < 0) {
422 ALOGW("destroyDisplay: invalid display token");
423 return;
424 }
425
426 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
427 if (!info.isVirtualDisplay()) {
428 ALOGE("destroyDisplay called for non-virtual display");
429 return;
430 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800431 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700432 mCurrentState.displays.removeItemsAt(idx);
433 setTransactionFlags(eDisplayTransactionNeeded);
434}
435
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700437 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800439 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 }
Jesse Hall692c7232012-11-08 15:41:56 -0800441 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442}
443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444void SurfaceFlinger::bootFinished()
445{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700446 if (mStartPropertySetThread->join() != NO_ERROR) {
447 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 const nsecs_t now = systemTime();
450 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000451 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700452
453 // wait patiently for the window manager death
454 const String16 name("window");
455 sp<IBinder> window(defaultServiceManager()->getService(name));
456 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700457 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700458 }
459
Steven Thomas050b2c82017-03-06 11:45:16 -0800460 if (mVrFlinger) {
461 mVrFlinger->OnBootFinished();
462 }
463
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700464 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700465 // formerly we would just kill the process, but we now ask it to exit so it
466 // can choose where to stop the animation.
467 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700468
469 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
470 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
471 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700472
Thierry Strudel2924d012017-08-14 15:19:37 -0700473 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700474 readPersistentProperties();
475 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477}
478
Mathias Agopian3f844832013-08-07 21:24:32 -0700479void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700480 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800481 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700482 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
485 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700487 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700488 return true;
489 }
490 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700491 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700492}
493
Lloyd Piquee83f9312018-02-01 12:53:17 -0800494class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700496 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000497 const char* name) :
498 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000501 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
502 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503 mDispSync(dispSync),
504 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 mVsyncMutex(),
506 mPhaseOffset(phaseOffset),
507 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700508
Lloyd Piquee83f9312018-02-01 12:53:17 -0800509 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510
Lloyd Piquee83f9312018-02-01 12:53:17 -0800511 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700512 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700520 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 } else {
522 status_t err = mDispSync->removeEventListener(
523 static_cast<DispSync::Callback*>(this));
524 if (err != NO_ERROR) {
525 ALOGE("error unregistering vsync callback: %s (%d)",
526 strerror(-err), err);
527 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700528 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700530 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 }
532
Lloyd Piquee83f9312018-02-01 12:53:17 -0800533 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 mCallback = callback;
536 }
537
Lloyd Piquee83f9312018-02-01 12:53:17 -0800538 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700539 Mutex::Autolock lock(mVsyncMutex);
540
541 // Normalize phaseOffset to [0, period)
542 auto period = mDispSync->getPeriod();
543 phaseOffset %= period;
544 if (phaseOffset < 0) {
545 // If we're here, then phaseOffset is in (-period, 0). After this
546 // operation, it will be in (0, period)
547 phaseOffset += period;
548 }
549 mPhaseOffset = phaseOffset;
550
551 // If we're not enabled, we don't need to mess with the listeners
552 if (!mEnabled) {
553 return;
554 }
555
Dan Stoza2713c302018-03-28 17:07:36 -0700556 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
557 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700558 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700559 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 strerror(-err), err);
561 }
562 }
563
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564private:
565 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800566 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 callback = mCallback;
570
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700571 if (mTraceVsync) {
572 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700573 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575 }
576
Peiyong Lin566a3b42018-01-09 18:22:43 -0800577 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 callback->onVSyncEvent(when);
579 }
580 }
581
Tim Murray4a4e4a22016-04-19 16:29:23 +0000582 const char* const mName;
583
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584 int mValue;
585
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700586 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 const String8 mVsyncOnLabel;
588 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700591
592 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mVsyncMutex; // Protects the following
596 nsecs_t mPhaseOffset;
597 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598};
599
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700601public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800602 InjectVSyncSource() = default;
603 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700606 std::lock_guard<std::mutex> lock(mCallbackMutex);
607 mCallback = callback;
608 }
609
Lloyd Piquee83f9312018-02-01 12:53:17 -0800610 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700611 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700612 if (mCallback) {
613 mCallback->onVSyncEvent(when);
614 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700615 }
616
Lloyd Piquee83f9312018-02-01 12:53:17 -0800617 void setVSyncEnabled(bool) override {}
618 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700619
620private:
621 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800622 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700623};
624
Wei Wangf9b05ee2017-07-19 20:59:39 -0700625// Do not call property_set on main thread which will be blocked by init
626// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700627void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700628 ALOGI( "SurfaceFlinger's main thread ready to run. "
629 "Initializing graphics H/W...");
630
Thierry Strudel2924d012017-08-14 15:19:37 -0700631 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800636 mEventThreadSource =
637 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
638 true, "app");
639 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
640 "appEventThread");
641 mSfEventThreadSource =
642 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
643 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800644
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800645 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
646 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800647 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700648 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649
Steven Thomasb02664d2017-07-26 18:48:28 -0700650 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800651 getBE().mRenderEngine =
652 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
653 hasWideColorDisplay
654 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
655 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800656 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700657
658 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
659 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800660 getBE().mHwc.reset(
661 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700662 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800663 // Process any initial hotplug and resulting display changes.
664 processDisplayHotplugEventsLocked();
665 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
666 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668 // make the default display GLContext current so that we can create textures
669 // when creating Layers (which may happens before we render something)
670 getDefaultDisplayDeviceLocked()->makeCurrent();
671
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 if (useVrFlinger) {
673 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700674 // This callback is called from the vr flinger dispatch thread. We
675 // need to call signalTransaction(), which requires holding
676 // mStateLock when we're not on the main thread. Acquiring
677 // mStateLock from the vr flinger dispatch thread might trigger a
678 // deadlock in surface flinger (see b/66916578), so post a message
679 // to be handled on the main thread instead.
680 sp<LambdaMessage> message = new LambdaMessage([=]() {
681 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
682 mVrFlingerRequestsDisplay = requestDisplay;
683 signalTransaction();
684 });
685 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800686 };
David Sodman105b7dc2017-11-04 20:28:14 -0700687 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
688 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800689 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (!mVrFlinger) {
691 ALOGE("Failed to start vrflinger");
692 }
693 }
694
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800695 mEventControlThread = std::make_unique<impl::EventControlThread>(
696 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700697
Mathias Agopian92a979a2012-08-02 18:32:23 -0700698 // initialize our drawing state
699 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700700
Andy McFadden13a082e2012-08-24 10:16:42 -0700701 // set initial conditions (e.g. unblank default device)
702 initializeDisplays();
703
David Sodmanbc815282017-11-05 18:57:52 -0800704 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700705
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 // Inform native graphics APIs whether the present timestamp is supported:
707 if (getHwComposer().hasCapability(
708 HWC2::Capability::PresentFenceIsNotReliable)) {
709 mStartPropertySetThread = new StartPropertySetThread(false);
710 } else {
711 mStartPropertySetThread = new StartPropertySetThread(true);
712 }
713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
719 Dataspace::SRGB_LINEAR);
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
736 ALOGV("Display Color Setting is set to %s.",
737 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800751 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800755 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Dan Stoza7f7da322014-05-02 15:26:25 -0700793status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
794 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800795 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500799 if (!display.get())
800 return NAME_NOT_FOUND;
801
Jesse Hall692c7232012-11-08 15:41:56 -0800802 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700803 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800804 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700805 type = i;
806 break;
807 }
808 }
809
810 if (type < 0) {
811 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700812 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 // TODO: Not sure if display density should handled by SF any longer
815 class Density {
816 static int getDensityFromProperty(char const* propName) {
817 char property[PROPERTY_VALUE_MAX];
818 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800819 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 density = atoi(property);
821 }
822 return density;
823 }
824 public:
825 static int getEmuDensity() {
826 return getDensityFromProperty("qemu.sf.lcd_density"); }
827 static int getBuildDensity() {
828 return getDensityFromProperty("ro.sf.lcd_density"); }
829 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Steven Thomas6d8110b2017-08-31 18:24:21 -0700833 ConditionalLock _l(mStateLock,
834 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 DisplayInfo info = DisplayInfo();
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 float xdpi = hwConfig->getDpiX();
839 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 if (type == DisplayDevice::DISPLAY_PRIMARY) {
842 // The density of the device is provided by a build property
843 float density = Density::getBuildDensity() / 160.0f;
844 if (density == 0) {
845 // the build doesn't provide a density -- this is wrong!
846 // use xdpi instead
847 ALOGE("ro.sf.lcd_density must be defined as a build property");
848 density = xdpi / 160.0f;
849 }
850 if (Density::getEmuDensity()) {
851 // if "qemu.sf.lcd_density" is specified, it overrides everything
852 xdpi = ydpi = density = Density::getEmuDensity();
853 density /= 160.0f;
854 }
855 info.density = density;
856
857 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700858 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800859 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 } else {
861 // TODO: where should this value come from?
862 static const int TV_DENSITY = 213;
863 info.density = TV_DENSITY / 160.0f;
864 info.orientation = 0;
865 }
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.w = hwConfig->getWidth();
868 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900872 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800887 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Michael Wright28f24d02016-07-12 13:30:53 -0700892 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700893 }
894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 return NO_ERROR;
896}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700897
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800898status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800900 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return BAD_VALUE;
902 }
903
904 // FIXME for now we always return stats for the primary display
905 memset(stats, 0, sizeof(*stats));
906 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
907 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
908 return NO_ERROR;
909}
910
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (display == nullptr) {
913 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800914 return BAD_VALUE;
915 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700916
917 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800918 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700919 return device->getActiveConfig();
920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700921
Dan Stoza24a42e92015-03-09 10:04:11 -0700922 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
926 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
927 this);
928 int32_t type = hw->getDisplayType();
929 int currentMode = hw->getActiveConfig();
930
931 if (mode == currentMode) {
932 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
933 return;
934 }
935
936 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
937 ALOGW("Trying to set config for virtual display");
938 return;
939 }
940
941 hw->setActiveConfig(mode);
942 getHwComposer().setActiveConfig(type, mode);
943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
946 class MessageSetActiveConfig: public MessageBase {
947 SurfaceFlinger& mFlinger;
948 sp<IBinder> mDisplay;
949 int mMode;
950 public:
951 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
952 int mode) :
953 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
954 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700955 Vector<DisplayInfo> configs;
956 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700957 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700958 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700959 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700960 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700961 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800963 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
967 ALOGW("Attempt to set active config = %d for virtual display",
968 mMode);
969 } else {
970 mFlinger.setActiveConfigInternal(hw, mMode);
971 }
972 return true;
973 }
974 };
975 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
976 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700977 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978}
Michael Wright28f24d02016-07-12 13:30:53 -0700979status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
982 return BAD_VALUE;
983 }
984
985 if (!display.get()) {
986 return NAME_NOT_FOUND;
987 }
988
989 int32_t type = NAME_NOT_FOUND;
990 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
991 if (display == mBuiltinDisplays[i]) {
992 type = i;
993 break;
994 }
995 }
996
997 if (type < 0) {
998 return type;
999 }
1000
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 {
1003 ConditionalLock _l(mStateLock,
1004 std::this_thread::get_id() != mMainThreadId);
1005 modes = getHwComposer().getColorModes(type);
1006 }
Michael Wright28f24d02016-07-12 13:30:53 -07001007 outColorModes->clear();
1008 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1009
1010 return NO_ERROR;
1011}
1012
Peiyong Lina52f0292018-03-14 17:26:31 -07001013ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001015 if (device != nullptr) {
1016 return device->getActiveColorMode();
1017 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
1021void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001022 ColorMode mode, Dataspace dataSpace,
1023 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001024 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001027 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001028
Peiyong Lin38e9a562018-04-10 16:24:20 -07001029 if (mode == currentMode && dataSpace == currentDataSpace &&
1030 renderIntent == currentRenderIntent) {
1031 return;
1032 }
1033
1034 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1035 ALOGW("Trying to set config for virtual display");
1036 return;
1037 }
1038
1039 hw->setActiveColorMode(mode);
1040 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001041 hw->setActiveRenderIntent(renderIntent);
1042 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1043
1044 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1045 decodeColorMode(mode).c_str(), mode,
1046 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1047 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001048}
1049
1050
1051status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001052 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001053 class MessageSetActiveColorMode: public MessageBase {
1054 SurfaceFlinger& mFlinger;
1055 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001056 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 public:
1058 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001059 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001060 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1061 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001062 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 mFlinger.getDisplayColorModes(mDisplay, &modes);
1064 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001066 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1067 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001068 return true;
1069 }
1070 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1071 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001072 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1073 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001074 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001075 ALOGW("Attempt to set active color mode %s %d for virtual display",
1076 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001077 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001078 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1079 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001080 }
1081 return true;
1082 }
1083 };
1084 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1085 postMessageSync(msg);
1086 return NO_ERROR;
1087}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001088
Svetoslavd85084b2014-03-20 10:28:31 -07001089status_t SurfaceFlinger::clearAnimationFrameStats() {
1090 Mutex::Autolock _l(mStateLock);
1091 mAnimFrameTracker.clearStats();
1092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1096 Mutex::Autolock _l(mStateLock);
1097 mAnimFrameTracker.getStats(outStats);
1098 return NO_ERROR;
1099}
1100
Dan Stozac4f471e2016-03-24 09:31:08 -07001101status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1102 HdrCapabilities* outCapabilities) const {
1103 Mutex::Autolock _l(mStateLock);
1104
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001105 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001106 if (displayDevice == nullptr) {
1107 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1108 return BAD_VALUE;
1109 }
1110
Peiyong Linfb069302018-04-25 14:34:31 -07001111 // At this point the DisplayDeivce should already be set up,
1112 // meaning the luminance information is already queried from
1113 // hardware composer and stored properly.
1114 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1115 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1116 capabilities.getDesiredMaxLuminance(),
1117 capabilities.getDesiredMaxAverageLuminance(),
1118 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001119
1120 return NO_ERROR;
1121}
1122
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001123status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1125 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 if (mInjectVSyncs == enable) {
1128 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001130
1131 if (enable) {
1132 ALOGV("VSync Injections enabled");
1133 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001134 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001135 mInjectorEventThread =
1136 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1137 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001139 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 } else {
1141 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001142 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 }
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 });
1147 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001148 return NO_ERROR;
1149}
1150
1151status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 Mutex::Autolock _l(mStateLock);
1153
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154 if (!mInjectVSyncs) {
1155 ALOGE("VSync Injections not enabled");
1156 return BAD_VALUE;
1157 }
1158 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1159 ALOGV("Injecting VSync inside SurfaceFlinger");
1160 mVSyncInjector->onInjectSyncEvent(when);
1161 }
1162 return NO_ERROR;
1163}
1164
Lloyd Pique755e3192018-01-31 16:46:15 -08001165status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1166 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001167 IPCThreadState* ipc = IPCThreadState::self();
1168 const int pid = ipc->getCallingPid();
1169 const int uid = ipc->getCallingUid();
1170 if ((uid != AID_SHELL) &&
1171 !PermissionCache::checkPermission(sDump, pid, uid)) {
1172 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1173 return PERMISSION_DENIED;
1174 }
1175
1176 // Try to acquire a lock for 1s, fail gracefully
1177 const status_t err = mStateLock.timedLock(s2ns(1));
1178 const bool locked = (err == NO_ERROR);
1179 if (!locked) {
1180 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1181 return TIMED_OUT;
1182 }
1183
1184 outLayers->clear();
1185 mCurrentState.traverseInZOrder([&](Layer* layer) {
1186 outLayers->push_back(layer->getLayerDebugInfo());
1187 });
1188
1189 mStateLock.unlock();
1190 return NO_ERROR;
1191}
1192
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001193// ----------------------------------------------------------------------------
1194
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001195sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1196 ISurfaceComposer::VsyncSource vsyncSource) {
1197 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1198 return mSFEventThread->createEventConnection();
1199 } else {
1200 return mEventThread->createEventConnection();
1201 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001202}
1203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001205
1206void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001207 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208}
1209
1210void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001211 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001212}
1213
1214void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001215 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001219 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001220 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001225 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226}
1227
1228status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001229 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001230 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001231 if (res == NO_ERROR) {
1232 msg->wait();
1233 }
1234 return res;
1235}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001237void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001238 do {
1239 waitForEvent();
1240 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001241}
1242
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243void SurfaceFlinger::enableHardwareVsync() {
1244 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001245 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001247 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1248 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001250 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251}
1252
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 Mutex::Autolock _l(mHWVsyncLock);
1255
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (makeAvailable) {
1257 mHWVsyncAvailable = true;
1258 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001259 // Hardware vsync is not currently available, so abort the resync
1260 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261 return;
1262 }
1263
David Sodman105b7dc2017-11-04 20:28:14 -07001264 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001265 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266
1267 mPrimaryDispSync.reset();
1268 mPrimaryDispSync.setPeriod(period);
1269
1270 if (!mPrimaryHWVsyncEnabled) {
1271 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001272 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1273 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 mPrimaryHWVsyncEnabled = true;
1275 }
1276}
1277
Jesse Hall948fe0c2013-10-14 12:56:09 -07001278void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279 Mutex::Autolock _l(mHWVsyncLock);
1280 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1282 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 mPrimaryDispSync.endResync();
1284 mPrimaryHWVsyncEnabled = false;
1285 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286 if (makeUnavailable) {
1287 mHWVsyncAvailable = false;
1288 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289}
1290
Tim Murray4a4e4a22016-04-19 16:29:23 +00001291void SurfaceFlinger::resyncWithRateLimit() {
1292 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001293
1294 // No explicit locking is needed here since EventThread holds a lock while calling this method
1295 static nsecs_t sLastResyncAttempted = 0;
1296 const nsecs_t now = systemTime();
1297 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001298 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001299 }
Dan Stoza57164302017-05-08 14:03:54 -07001300 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001301}
1302
Steven Thomasb02664d2017-07-26 18:48:28 -07001303void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1304 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001305 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001306 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001307 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001308 return;
1309 }
1310
1311 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001312 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001313 return;
1314 }
1315
Jamie Gennisd1700752013-10-14 12:22:52 -07001316 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317
Jamie Gennisd1700752013-10-14 12:22:52 -07001318 { // Scope for the lock
1319 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001320 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001321 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001323 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001324
1325 if (needsHwVsync) {
1326 enableHardwareVsync();
1327 } else {
1328 disableHardwareVsync(false);
1329 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001330}
1331
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001332void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001333 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1334 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001335}
1336
Lloyd Pique715a2c12017-12-14 17:18:08 -08001337void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1338 HWC2::Connection connection) {
1339 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1340 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
Lloyd Piqueba04e622017-12-14 17:11:26 -08001342 // Ignore events that do not have the right sequenceId.
1343 if (sequenceId != getBE().mComposerSequenceId) {
1344 return;
1345 }
1346
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 // Only lock if we're not on the main thread. This function is normally
1348 // called on a hwbinder thread, but for the primary display it's called on
1349 // the main thread with the state lock already held, so don't attempt to
1350 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001351 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001352
Lloyd Pique715a2c12017-12-14 17:18:08 -08001353 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001354
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001355 if (std::this_thread::get_id() == mMainThreadId) {
1356 // Process all pending hot plug events immediately if we are on the main thread.
1357 processDisplayHotplugEventsLocked();
1358 }
1359
Lloyd Piqueba04e622017-12-14 17:11:26 -08001360 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001361}
1362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363void SurfaceFlinger::onRefreshReceived(int sequenceId,
1364 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001366 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001368 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001369 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001370}
1371
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001375 getHwComposer().setVsyncEnabled(disp,
1376 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001377}
1378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001380void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 // Clear the drawing state so that the logic inside of
1383 // handleTransactionLocked will fire. It will determine the delta between
1384 // mCurrentState and mDrawingState and re-apply all changes when we make the
1385 // transition.
1386 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001387 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388 mDisplays.clear();
1389}
1390
Steven Thomas050b2c82017-03-06 11:45:16 -08001391void SurfaceFlinger::updateVrFlinger() {
1392 if (!mVrFlinger)
1393 return;
1394 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001396 return;
1397 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 ALOGE("Vr flinger is only supported for remote hardware composer"
1401 " service connections. Ignoring request to transition to vr"
1402 " flinger.");
1403 mVrFlingerRequestsDisplay = false;
1404 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 int currentDisplayPowerMode = getDisplayDeviceLocked(
1410 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001417 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001418 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1419 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001420 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
David Sodman105b7dc2017-11-04 20:28:14 -07001422 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1423 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001424
1425 if (vrFlingerRequestsDisplay) {
1426 mVrFlinger->GrantDisplayOwnership();
1427 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
1431 mVisibleRegionsDirty = true;
1432 invalidateHwcGeometry();
1433
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001434 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1436 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1437 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001440 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 const nsecs_t period = activeConfig->getVsyncPeriod();
1442 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 // Use phase of 0 since phase is not known.
1445 // Use latency of 0, which will snap to the ideal latency.
1446 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001447
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 android_atomic_or(1, &mRepaintEverything);
1449 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450}
1451
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001453 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001456 bool frameMissed = !mHadClientComposition &&
1457 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458 (mPreviousPresentFence->getSignalTime() ==
1459 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001460 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001461 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001462 mTimeStats.incrementMissedFrames();
1463 if (mPropagateBackpressure) {
1464 signalLayerUpdate();
1465 break;
1466 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001467 }
Dan Stoza50182882016-07-08 12:02:20 -07001468
Steven Thomas050b2c82017-03-06 11:45:16 -08001469 // Now that we're going to make it to the handleMessageTransaction()
1470 // call below it's safe to call updateVrFlinger(), which will
1471 // potentially trigger a display handoff.
1472 updateVrFlinger();
1473
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 bool refreshNeeded = handleMessageTransaction();
1475 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001476 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001477 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001478 // Signal a refresh if a transaction modified the window state,
1479 // a new buffer was latched, or if HWC has requested a full
1480 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 signalRefresh();
1482 }
1483 break;
1484 }
1485 case MessageQueue::REFRESH: {
1486 handleMessageRefresh();
1487 break;
1488 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001489 }
1490}
1491
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001493 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001495 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001497 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001499}
1500
Dan Stoza6b9454d2014-11-07 16:00:59 -08001501bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504}
1505
1506void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001507 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001508
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001509 mRefreshPending = false;
1510
Pablo Ceballos40845df2016-01-25 17:41:15 -08001511 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001512
Brian Andersond6927fb2016-07-23 23:37:30 -07001513 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001514 rebuildLayerStacks();
1515 setUpHWComposer();
1516 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001517 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001518 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001519 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001520 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001521
David Sodman105b7dc2017-11-04 20:28:14 -07001522 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001523
1524 mHadClientComposition = false;
1525 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1526 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1527 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001528 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529 }
Dan Stoza2713c302018-03-28 17:07:36 -07001530 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001531
Dan Stoza9e56aa02015-11-02 13:00:03 -08001532 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535void SurfaceFlinger::doDebugFlashRegions()
1536{
1537 // is debugging enabled
1538 if (CC_LIKELY(!mDebugRegion))
1539 return;
1540
1541 const bool repaintEverything = mRepaintEverything;
1542 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1543 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001544 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 // transform the dirty region into this screen's coordinate space
1546 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1547 if (!dirtyRegion.isEmpty()) {
1548 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001549 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550
1551 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001553 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001554 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1555
Mathias Agopianda27af92012-09-13 18:17:13 -07001556 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 }
1558 }
1559 }
1560
1561 postFramebuffer();
1562
1563 if (mDebugRegion > 1) {
1564 usleep(mDebugRegion * 1000);
1565 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001566
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001568 auto& displayDevice = mDisplays[displayId];
1569 if (!displayDevice->isDisplayOn()) {
1570 continue;
1571 }
1572
David Sodman105b7dc2017-11-04 20:28:14 -07001573 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1574 ALOGE_IF(result != NO_ERROR,
1575 "prepareFrame for display %zd failed:"
1576 " %d (%s)",
1577 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001578 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579}
1580
Adrian Roos1e1a1282017-11-01 19:05:31 +01001581void SurfaceFlinger::doTracing(const char* where) {
1582 ATRACE_CALL();
1583 ATRACE_NAME(where);
1584 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001585 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001586 }
1587}
1588
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001589void SurfaceFlinger::logLayerStats() {
1590 ATRACE_CALL();
1591 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1592 int32_t hwcId = -1;
1593 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1594 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1595 if (displayDevice->isPrimary()) {
1596 hwcId = displayDevice->getHwcDisplayId();
1597 break;
1598 }
1599 }
1600 if (hwcId < 0) {
1601 ALOGE("LayerStats: Hmmm, no primary display?");
1602 return;
1603 }
1604 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1605 }
1606}
1607
Brian Andersond6927fb2016-07-23 23:37:30 -07001608void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001609{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001610 ATRACE_CALL();
1611 ALOGV("preComposition");
1612
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001614 mDrawingState.traverseInZOrder([&](Layer* layer) {
1615 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616 needExtraInvalidate = true;
1617 }
Robert Carr2047fae2016-11-28 14:09:09 -08001618 });
1619
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620 if (needExtraInvalidate) {
1621 signalLayerUpdate();
1622 }
1623}
1624
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625void SurfaceFlinger::updateCompositorTiming(
1626 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1627 std::shared_ptr<FenceTime>& presentFenceTime) {
1628 // Update queue of past composite+present times and determine the
1629 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001630 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001631 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001632 while (!getBE().mCompositePresentTimes.empty()) {
1633 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Cached values should have been updated before calling this method,
1635 // which helps avoid duplicate syscalls.
1636 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1637 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1638 break;
1639 }
1640 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001641 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 }
1643
1644 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001645 while (getBE().mCompositePresentTimes.size() > 16) {
1646 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 }
1648
Brian Andersond0010582017-03-07 13:20:31 -08001649 setCompositorTimingSnapped(
1650 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1651}
1652
1653void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1654 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 // Integer division and modulo round toward 0 not -inf, so we need to
1656 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001657 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1659 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1660
Brian Andersond0010582017-03-07 13:20:31 -08001661 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1662 if (idealLatency <= 0) {
1663 idealLatency = vsyncInterval;
1664 }
1665
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 // Snap the latency to a value that removes scheduling jitter from the
1667 // composition and present times, which often have >1ms of jitter.
1668 // Reducing jitter is important if an app attempts to extrapolate
1669 // something (such as user input) to an accurate diasplay time.
1670 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1671 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001672 nsecs_t bias = vsyncInterval / 2;
1673 int64_t extraVsyncs =
1674 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1675 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1676 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677
David Sodman99974d22017-11-28 12:04:33 -08001678 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1679 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1680 getBE().mCompositorTiming.interval = vsyncInterval;
1681 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682}
1683
1684void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001686 ATRACE_CALL();
1687 ALOGV("postComposition");
1688
Brian Anderson3546a3f2016-07-14 11:51:14 -07001689 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001690 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001691 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001692 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001693 }
1694
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001695 // |mStateLock| not needed as we are on the main thread
1696 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001697
David Sodman73beded2017-11-15 11:56:06 -08001698 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001700 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001701 glCompositionDoneFenceTime =
1702 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001703 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001704 } else {
1705 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1706 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707
David Sodman73beded2017-11-15 11:56:06 -08001708 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001709 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001710 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001711 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1714 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1715
1716 // We use the refreshStartTime which might be sampled a little later than
1717 // when we started doing work for this frame, but that should be okay
1718 // since updateCompositorTiming has snapping logic.
1719 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001720 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001721 CompositorTiming compositorTiming;
1722 {
David Sodman99974d22017-11-28 12:04:33 -08001723 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1724 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001725 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726
Robert Carr2047fae2016-11-28 14:09:09 -08001727 mDrawingState.traverseInZOrder([&](Layer* layer) {
1728 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001730 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001731 recordBufferingStats(layer->getName().string(),
1732 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001733 }
Robert Carr2047fae2016-11-28 14:09:09 -08001734 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001736 if (presentFenceTime->isValid()) {
1737 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001738 enableHardwareVsync();
1739 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001740 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001741 }
1742 }
1743
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001744 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001745 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001746 enableHardwareVsync();
1747 }
1748 }
1749
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001750 if (mAnimCompositionPending) {
1751 mAnimCompositionPending = false;
1752
Brian Anderson4e606e32017-03-16 15:34:57 -07001753 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001755 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001756 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001757 // The HWC doesn't support present fences, so use the refresh
1758 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001760 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001761 mAnimFrameTracker.setActualPresentTime(presentTime);
1762 }
1763 mAnimFrameTracker.advanceFrame();
1764 }
Dan Stozab90cf072015-03-05 11:05:59 -08001765
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001766 mTimeStats.incrementTotalFrames();
1767 if (mHadClientComposition) {
1768 mTimeStats.incrementClientCompositionFrames();
1769 }
1770
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001771 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1772 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001773 return;
1774 }
1775
1776 nsecs_t currentTime = systemTime();
1777 if (mHasPoweredOff) {
1778 mHasPoweredOff = false;
1779 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001780 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001782 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1783 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001784 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001785 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001786 }
David Sodman4a36e932017-11-07 14:29:47 -08001787 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001788 }
David Sodman4a36e932017-11-07 14:29:47 -08001789 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001790}
1791
1792void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001793 ATRACE_CALL();
1794 ALOGV("rebuildLayerStacks");
1795
Mathias Agopiancd60f992012-08-16 16:28:27 -07001796 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001797 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001798 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001799 mVisibleRegionsDirty = false;
1800 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001801
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1803 Region opaqueRegion;
1804 Region dirtyRegion;
1805 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001806 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1808 const Transform& tr(displayDevice->getTransform());
1809 const Rect bounds(displayDevice->getBounds());
1810 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001811 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001812
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001814 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001815 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1816 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 Region drawRegion(tr.transform(
1818 layer->visibleNonTransparentRegion));
1819 drawRegion.andSelf(bounds);
1820 if (!drawRegion.isEmpty()) {
1821 layersSortedByZ.add(layer);
1822 } else {
1823 // Clear out the HWC layer if this layer was
1824 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001825 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001826 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001828 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001829 // WM changes displayDevice->layerStack upon sleep/awake.
1830 // Here we make sure we delete the HWC layers even if
1831 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001832 hwcLayerDestroyed = layer->destroyHwcLayer(
1833 displayDevice->getHwcDisplayId());
1834 }
1835
1836 // If a layer is not going to get a release fence because
1837 // it is invisible, but it is also going to release its
1838 // old buffer, add it to the list of layers needing
1839 // fences.
1840 if (hwcLayerDestroyed) {
1841 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1842 mLayersWithQueuedFrames.cend(), layer);
1843 if (found != mLayersWithQueuedFrames.cend()) {
1844 layersNeedingFences.add(layer);
1845 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001846 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 });
1848 }
1849 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001850 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001851 displayDevice->undefinedRegion.set(bounds);
1852 displayDevice->undefinedRegion.subtractSelf(
1853 tr.transform(opaqueRegion));
1854 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001856 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001858
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001859// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001860// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001861// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001862// - Dataspace::DISPLAY_P3
1863// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001864// The returned HDR data space is one of
1865// - Dataspace::UNKNOWN
1866// - Dataspace::BT2020_HLG
1867// - Dataspace::BT2020_PQ
1868Dataspace SurfaceFlinger::getBestDataspace(
1869 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1870 Dataspace bestDataSpace = Dataspace::SRGB;
1871 *outHdrDataSpace = Dataspace::UNKNOWN;
1872
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1874 switch (layer->getDataSpace()) {
1875 case Dataspace::V0_SCRGB:
1876 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001877 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001878 break;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001879 case Dataspace::DISPLAY_P3:
1880 if (bestDataSpace == Dataspace::SRGB) {
1881 bestDataSpace = Dataspace::DISPLAY_P3;
1882 }
1883 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884 case Dataspace::BT2020_PQ:
1885 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001886 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001887 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001888 case Dataspace::BT2020_HLG:
1889 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001890 // When there's mixed PQ content and HLG content, we set the HDR
1891 // data space to be BT2020_PQ and convert HLG to PQ.
1892 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1893 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001894 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895 break;
1896 default:
1897 break;
1898 }
Romain Guy54f154a2017-10-24 21:40:32 +01001899 }
1900
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001901 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001902}
1903
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001906 ColorMode* outMode, Dataspace* outDataSpace,
1907 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1909 *outMode = ColorMode::NATIVE;
1910 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001911 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001913 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001914
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001915 Dataspace hdrDataSpace;
1916 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1917
1918 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1919 // Hardware composer can handle BT2100 ColorMode only when
1920 // - colorimetrical tone mapping is supported, or
1921 // - Auto mode is turned on and enhanced tone mapping is supported.
1922 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1923 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1924 displayDevice->hasBT2100PQEnhanceSupport())) {
1925 *outMode = ColorMode::BT2100_PQ;
1926 *outDataSpace = Dataspace::BT2020_PQ;
1927 } else if (displayDevice->hasHDR10Support()) {
1928 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1929 hdrDataSpace = Dataspace::UNKNOWN;
1930 } else {
1931 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001932 *outMode = ColorMode::DISPLAY_P3;
1933 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001934 }
1935 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1936 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1937 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1938 displayDevice->hasBT2100HLGEnhanceSupport())) {
1939 *outMode = ColorMode::BT2100_HLG;
1940 *outDataSpace = Dataspace::BT2020_HLG;
1941 } else if (displayDevice->hasHLGSupport()) {
1942 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1943 hdrDataSpace = Dataspace::UNKNOWN;
1944 } else {
1945 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1946 *outMode = ColorMode::DISPLAY_P3;
1947 *outDataSpace = Dataspace::DISPLAY_P3;
1948 }
1949 }
1950
1951 // At this point, there's no HDR layer.
1952 if (hdrDataSpace == Dataspace::UNKNOWN) {
1953 switch (bestDataSpace) {
1954 case Dataspace::DISPLAY_P3:
1955 case Dataspace::V0_SCRGB_LINEAR:
1956 *outMode = ColorMode::DISPLAY_P3;
1957 *outDataSpace = Dataspace::DISPLAY_P3;
1958 break;
1959 default:
1960 *outMode = ColorMode::SRGB;
1961 *outDataSpace = Dataspace::SRGB;
1962 break;
1963 }
1964 }
1965 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1966}
1967
1968RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1969 ColorMode colorMode) const {
1970 // Native Mode means the display is not color managed, and whichever
1971 // render intent is picked doesn't matter, thus return
1972 // RenderIntent::COLORIMETRIC as default here.
1973 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1974 return RenderIntent::COLORIMETRIC;
1975 }
1976
1977 // In Auto Color Mode, we want to strech to panel color space, right now
1978 // only the built-in display supports it.
1979 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1980 mBuiltinDisplaySupportsEnhance &&
1981 displayDevice->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1982 switch (colorMode) {
1983 case ColorMode::DISPLAY_P3:
1984 case ColorMode::SRGB:
1985 return RenderIntent::ENHANCE;
1986 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1987 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1988 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1989 case ColorMode::BT2100_PQ:
1990 return displayDevice->hasBT2100PQEnhanceSupport() ?
1991 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1992 case ColorMode::BT2100_HLG:
1993 return displayDevice->hasBT2100HLGEnhanceSupport() ?
1994 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1995 // This statement shouldn't be reached, switch cases will always
1996 // cover all possible ColorMode returned by pickColorMode.
1997 default:
1998 return RenderIntent::COLORIMETRIC;
1999 }
2000 }
2001
2002 // Either enhance is not supported or we are in natural mode.
2003
2004 // Natural Mode means it's color managed and the color must be right,
2005 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2006 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2007 switch (colorMode) {
2008 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2009 // when TONE_MAP_COLORIMETRIC is supported.
2010 case ColorMode::BT2100_PQ:
2011 case ColorMode::BT2100_HLG:
2012 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002013 default:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002014 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002015 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002016}
2017
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 ATRACE_CALL();
2020 ALOGV("setUpHWComposer");
2021
Jesse Hall028dc8f2013-08-20 16:35:32 -07002022 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002023 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002024 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2025 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2026
2027 // If nothing has changed (!dirty), don't recompose.
2028 // If something changed, but we don't currently have any visible layers,
2029 // and didn't when we last did a composition, then skip it this time.
2030 // The second rule does two things:
2031 // - When all layers are removed from a display, we'll emit one black
2032 // frame, then nothing more until we get new layers.
2033 // - When a display is created with a private layer stack, we won't
2034 // emit any black frames until a layer is added to the layer stack.
2035 bool mustRecompose = dirty && !(empty && wasEmpty);
2036
2037 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2038 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2039 mustRecompose ? "doing" : "skipping",
2040 dirty ? "+" : "-",
2041 empty ? "+" : "-",
2042 wasEmpty ? "+" : "-");
2043
Dan Stoza71433162014-02-04 16:22:36 -08002044 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002045
2046 if (mustRecompose) {
2047 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2048 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002049 }
2050
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 // build the h/w work list
2052 if (CC_UNLIKELY(mGeometryInvalid)) {
2053 mGeometryInvalid = false;
2054 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2055 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2056 const auto hwcId = displayDevice->getHwcDisplayId();
2057 if (hwcId >= 0) {
2058 const Vector<sp<Layer>>& currentLayers(
2059 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002060 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002061 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002063 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002066 }
2067 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002068
Robert Carrae060832016-11-28 10:51:00 -08002069 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002070 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002072 }
2073 }
2074 }
2075 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 }
Riley Andrews03414a12014-07-01 14:22:59 -07002077
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 // Set the per-frame data
2079 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2080 auto& displayDevice = mDisplays[displayId];
2081 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002082
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 if (hwcId < 0) {
2084 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002085 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002086 if (mDrawingState.colorMatrixChanged) {
2087 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2088 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002089 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2090 "display %zd: %d", displayId, result);
2091 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002093 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2094 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002095 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002096 layer->forceClientComposition(hwcId);
2097 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002098 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2099 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2100 !displayDevice->hasHLGSupport()) {
2101 layer->forceClientComposition(hwcId);
2102 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002103
chaviwc9232ed2017-11-14 15:31:15 -08002104 if (layer->getForceClientComposition(hwcId)) {
2105 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2106 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2107 continue;
2108 }
2109
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 layer->setPerFrameData(displayDevice);
2111 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002112
2113 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002114 ColorMode colorMode;
2115 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002116 RenderIntent renderIntent;
2117 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2118 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002119 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 }
2121
Chia-I Wu28f320b2018-05-03 11:02:56 -07002122 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002123
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002125 auto& displayDevice = mDisplays[displayId];
2126 if (!displayDevice->isDisplayOn()) {
2127 continue;
2128 }
2129
David Sodman105b7dc2017-11-04 20:28:14 -07002130 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2132 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002133 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002134}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002135
Mathias Agopiancd60f992012-08-16 16:28:27 -07002136void SurfaceFlinger::doComposition() {
2137 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 ALOGV("doComposition");
2139
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002140 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002141 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002142 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002143 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002144 // transform the dirty region into this screen's coordinate space
2145 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002146
2147 // repaint the framebuffer (if needed)
2148 doDisplayComposition(hw, dirtyRegion);
2149
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002151 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002152 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002153 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002154 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002155}
2156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157void SurfaceFlinger::postFramebuffer()
2158{
Mathias Agopian841cde52012-03-01 15:44:37 -08002159 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002160 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002161
Mathias Agopiana44b0412011-10-16 18:46:35 -07002162 const nsecs_t now = systemTime();
2163 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002164
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2166 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002167 if (!displayDevice->isDisplayOn()) {
2168 continue;
2169 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 const auto hwcId = displayDevice->getHwcDisplayId();
2171 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002172 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002173 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002174 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002175 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002177 // The layer buffer from the previous frame (if any) is released
2178 // by HWC only when the release fence from this frame (if any) is
2179 // signaled. Always get the release fence from HWC first.
2180 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002181 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002182
2183 // If the layer was client composited in the previous frame, we
2184 // need to merge with the previous client target acquire fence.
2185 // Since we do not track that, always merge with the current
2186 // client target acquire fence when it is available, even though
2187 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002188 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002189 releaseFence = Fence::merge("LayerRelease", releaseFence,
2190 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002191 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002192
Dan Stoza9e56aa02015-11-02 13:00:03 -08002193 layer->onLayerDisplayed(releaseFence);
2194 }
Chia-I Wu83806892017-11-16 10:50:20 -08002195
2196 // We've got a list of layers needing fences, that are disjoint with
2197 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2198 // supply them with the present fence.
2199 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002200 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002201 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2202 layer->onLayerDisplayed(presentFence);
2203 }
2204 }
2205
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002207 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002208 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002209 }
2210
Mathias Agopiana44b0412011-10-16 18:46:35 -07002211 mLastSwapBufferTime = systemTime() - now;
2212 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002213
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002214 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002215 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2216 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2217 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2218 logFrameStats();
2219 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002220 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221}
2222
Mathias Agopian87baae12012-07-31 12:38:26 -07002223void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224{
Mathias Agopian841cde52012-03-01 15:44:37 -08002225 ATRACE_CALL();
2226
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002227 // here we keep a copy of the drawing state (that is the state that's
2228 // going to be overwritten by handleTransactionLocked()) outside of
2229 // mStateLock so that the side-effects of the State assignment
2230 // don't happen with mStateLock held (which can cause deadlocks).
2231 State drawingState(mDrawingState);
2232
Mathias Agopianca4d3602011-05-19 15:38:14 -07002233 Mutex::Autolock _l(mStateLock);
2234 const nsecs_t now = systemTime();
2235 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236
Mathias Agopianca4d3602011-05-19 15:38:14 -07002237 // Here we're guaranteed that some transaction flags are set
2238 // so we can call handleTransactionLocked() unconditionally.
2239 // We call getTransactionFlags(), which will also clear the flags,
2240 // with mStateLock held to guarantee that mCurrentState won't change
2241 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002242
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002243 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002244 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002245 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002246
Mathias Agopianca4d3602011-05-19 15:38:14 -07002247 mLastTransactionTime = systemTime() - now;
2248 mDebugInTransaction = 0;
2249 invalidateHwcGeometry();
2250 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002251}
2252
Lloyd Pique715a2c12017-12-14 17:18:08 -08002253DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002254 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 // Figure out whether the event is for the primary display or an
2256 // external display by matching the Hwc display id against one for a
2257 // connected display. If we did not find a match, we then check what
2258 // displays are not already connected to determine the type. If we don't
2259 // have a connected primary display, we assume the new display is meant to
2260 // be the primary display, and then if we don't have an external display,
2261 // we assume it is that.
2262 const auto primaryDisplayId =
2263 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2264 const auto externalDisplayId =
2265 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2266 if (primaryDisplayId && primaryDisplayId == display) {
2267 return DisplayDevice::DISPLAY_PRIMARY;
2268 } else if (externalDisplayId && externalDisplayId == display) {
2269 return DisplayDevice::DISPLAY_EXTERNAL;
2270 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2271 return DisplayDevice::DISPLAY_PRIMARY;
2272 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2273 return DisplayDevice::DISPLAY_EXTERNAL;
2274 }
2275
2276 return DisplayDevice::DISPLAY_ID_INVALID;
2277}
2278
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2280 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002281 auto displayType = determineDisplayType(event.display, event.connection);
2282 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2283 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2284 continue;
2285 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002286
2287 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2288 ALOGE("External displays are not supported by the vr hardware composer.");
2289 continue;
2290 }
2291
Lloyd Pique715a2c12017-12-14 17:18:08 -08002292 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002293
2294 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002295 if (!mBuiltinDisplays[displayType].get()) {
2296 ALOGV("Creating built in display %d", displayType);
2297 mBuiltinDisplays[displayType] = new BBinder();
2298 // All non-virtual displays are currently considered secure.
2299 DisplayDeviceState info(displayType, true);
2300 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2301 "Built-in Screen" : "External Screen";
2302 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002303 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002304 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002307
Lloyd Piquefcd86612017-12-14 17:15:36 -08002308 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2309 if (idx >= 0) {
2310 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002311 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002312 mCurrentState.displays.removeItemsAt(idx);
2313 }
2314 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315 }
2316
2317 processDisplayChangesLocked();
2318 }
2319
2320 mPendingHotplugEvents.clear();
2321}
2322
Lloyd Pique09594832018-01-22 17:48:03 -08002323sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2324 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2325 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326 bool hasWideColorGamut = false;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002327 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2328
Lloyd Pique09594832018-01-22 17:48:03 -08002329 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002331 for (ColorMode colorMode : modes) {
2332 switch (colorMode) {
2333 case ColorMode::DISPLAY_P3:
2334 case ColorMode::ADOBE_RGB:
2335 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002336 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002337 break;
2338 default:
2339 break;
2340 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341
2342 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2343 colorMode);
2344 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2345 for (auto intent : renderIntents) {
2346 if (intent == RenderIntent::ENHANCE) {
2347 mBuiltinDisplaySupportsEnhance = true;
2348 break;
2349 }
2350 }
2351 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002352
2353 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2354 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2355 }
Lloyd Pique09594832018-01-22 17:48:03 -08002356 }
2357 }
2358
Peiyong Lin62665892018-04-16 11:07:44 -07002359 HdrCapabilities hdrCapabilities;
2360 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002361
2362 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2363 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2364
2365 /*
2366 * Create our display's surface
2367 */
2368 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2369 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2370 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2371 renderSurface->setNativeWindow(nativeWindow.get());
2372 const int displayWidth = renderSurface->queryWidth();
2373 const int displayHeight = renderSurface->queryHeight();
2374
2375 // Make sure that composition can never be stalled by a virtual display
2376 // consumer that isn't processing buffers fast enough. We have to do this
2377 // in two places:
2378 // * Here, in case the display is composed entirely by HWC.
2379 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2380 // window's swap interval in eglMakeCurrent, so they'll override the
2381 // interval we set here.
2382 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2383 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2384 }
2385
2386 // virtual displays are always considered enabled
2387 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2388 : HWC_POWER_MODE_OFF;
2389
2390 sp<DisplayDevice> hw =
2391 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2392 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002393 hasWideColorGamut, hdrCapabilities,
2394 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002395 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002396
2397 if (maxFrameBufferAcquiredBuffers >= 3) {
2398 nativeWindowSurface->preallocateBuffers();
2399 }
2400
2401 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002402 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2403 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002404 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002405 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002406 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002407 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2408 RenderIntent::COLORIMETRIC);
Lloyd Pique09594832018-01-22 17:48:03 -08002409 hw->setLayerStack(state.layerStack);
2410 hw->setProjection(state.orientation, state.viewport, state.frame);
2411 hw->setDisplayName(state.displayName);
2412
2413 return hw;
2414}
2415
Lloyd Pique347200f2017-12-14 17:00:15 -08002416void SurfaceFlinger::processDisplayChangesLocked() {
2417 // here we take advantage of Vector's copy-on-write semantics to
2418 // improve performance by skipping the transaction entirely when
2419 // know that the lists are identical
2420 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2421 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2422 if (!curr.isIdenticalTo(draw)) {
2423 mVisibleRegionsDirty = true;
2424 const size_t cc = curr.size();
2425 size_t dc = draw.size();
2426
2427 // find the displays that were removed
2428 // (ie: in drawing state but not in current state)
2429 // also handle displays that changed
2430 // (ie: displays that are in both lists)
2431 for (size_t i = 0; i < dc;) {
2432 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2433 if (j < 0) {
2434 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002435 // Call makeCurrent() on the primary display so we can
2436 // be sure that nothing associated with this display
2437 // is current.
2438 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2439 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2440 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2441 if (hw != nullptr) hw->disconnect(getHwComposer());
2442 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2443 mEventThread->onHotplugReceived(draw[i].type, false);
2444 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 } else {
2446 // this display is in both lists. see if something changed.
2447 const DisplayDeviceState& state(curr[j]);
2448 const wp<IBinder>& display(curr.keyAt(j));
2449 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2450 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2451 if (state_binder != draw_binder) {
2452 // changing the surface is like destroying and
2453 // recreating the DisplayDevice, so we just remove it
2454 // from the drawing state, so that it get re-added
2455 // below.
2456 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2457 if (hw != nullptr) hw->disconnect(getHwComposer());
2458 mDisplays.removeItem(display);
2459 mDrawingState.displays.removeItemsAt(i);
2460 dc--;
2461 // at this point we must loop to the next item
2462 continue;
2463 }
2464
2465 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2466 if (disp != nullptr) {
2467 if (state.layerStack != draw[i].layerStack) {
2468 disp->setLayerStack(state.layerStack);
2469 }
2470 if ((state.orientation != draw[i].orientation) ||
2471 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2472 disp->setProjection(state.orientation, state.viewport, state.frame);
2473 }
2474 if (state.width != draw[i].width || state.height != draw[i].height) {
2475 disp->setDisplaySize(state.width, state.height);
2476 }
2477 }
2478 }
2479 ++i;
2480 }
2481
2482 // find displays that were added
2483 // (ie: in current state but not in drawing state)
2484 for (size_t i = 0; i < cc; i++) {
2485 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2486 const DisplayDeviceState& state(curr[i]);
2487
2488 sp<DisplaySurface> dispSurface;
2489 sp<IGraphicBufferProducer> producer;
2490 sp<IGraphicBufferProducer> bqProducer;
2491 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002492 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493
2494 int32_t hwcId = -1;
2495 if (state.isVirtualDisplay()) {
2496 // Virtual displays without a surface are dormant:
2497 // they have external state (layer stack, projection,
2498 // etc.) but no internal state (i.e. a DisplayDevice).
2499 if (state.surface != nullptr) {
2500 // Allow VR composer to use virtual displays.
2501 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2502 int width = 0;
2503 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2504 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2505 int height = 0;
2506 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2507 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2508 int intFormat = 0;
2509 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2510 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002511 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002512
2513 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2514 }
2515
2516 // TODO: Plumb requested format back up to consumer
2517
2518 sp<VirtualDisplaySurface> vds =
2519 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2520 bqProducer, bqConsumer,
2521 state.displayName);
2522
2523 dispSurface = vds;
2524 producer = vds;
2525 }
2526 } else {
2527 ALOGE_IF(state.surface != nullptr,
2528 "adding a supported display, but rendering "
2529 "surface is provided (%p), ignoring it",
2530 state.surface.get());
2531
2532 hwcId = state.type;
2533 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2534 producer = bqProducer;
2535 }
2536
2537 const wp<IBinder>& display(curr.keyAt(i));
2538 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002539 mDisplays.add(display,
2540 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2541 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002542 if (!state.isVirtualDisplay()) {
2543 mEventThread->onHotplugReceived(state.type, true);
2544 }
2545 }
2546 }
2547 }
2548 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002549
2550 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002551}
2552
Mathias Agopian87baae12012-07-31 12:38:26 -07002553void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002554{
Dan Stoza7dde5992015-05-22 09:51:44 -07002555 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002556 mCurrentState.traverseInZOrder([](Layer* layer) {
2557 layer->notifyAvailableFrames();
2558 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 /*
2561 * Traversal of the children
2562 * (perform the transaction for each of them if needed)
2563 */
2564
Mathias Agopian3559b072012-08-15 13:46:03 -07002565 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002566 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002568 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569
2570 const uint32_t flags = layer->doTransaction(0);
2571 if (flags & Layer::eVisibleRegion)
2572 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002573 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574 }
2575
2576 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002577 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 */
2579
Mathias Agopiane57f2922012-08-09 16:29:12 -07002580 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002581 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002583 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002585 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002586 // The transform hint might have changed for some layers
2587 // (either because a display has changed, or because a layer
2588 // as changed).
2589 //
2590 // Walk through all the layers in currentLayers,
2591 // and update their transform hint.
2592 //
2593 // If a layer is visible only on a single display, then that
2594 // display is used to calculate the hint, otherwise we use the
2595 // default display.
2596 //
2597 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2598 // the hint is set before we acquire a buffer from the surface texture.
2599 //
2600 // NOTE: layer transactions have taken place already, so we use their
2601 // drawing state. However, SurfaceFlinger's own transaction has not
2602 // happened yet, so we must use the current state layer list
2603 // (soon to become the drawing state list).
2604 //
2605 sp<const DisplayDevice> disp;
2606 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002607 bool first = true;
2608 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002609 // NOTE: we rely on the fact that layers are sorted by
2610 // layerStack first (so we don't have to traverse the list
2611 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002612 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002613 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002614 currentlayerStack = layerStack;
2615 // figure out if this layerstack is mirrored
2616 // (more than one display) if so, pick the default display,
2617 // if not, pick the only display it's on.
2618 disp.clear();
2619 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2620 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002621 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002622 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002623 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002624 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002625 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002626 break;
2627 }
2628 }
2629 }
2630 }
Chet Haase91d25932013-04-11 15:24:55 -07002631
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002632 if (disp == nullptr) {
2633 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2634 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002635
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002636 // could be null when this layer is using a layerStack
2637 // that is not visible on any display. Also can occur at
2638 // screen off/on times.
2639 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002640 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002641
2642 // disp can be null if there is no display available at all to get
2643 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002644 if (disp != nullptr) {
2645 layer->updateTransformHint(disp);
2646 }
Robert Carr2047fae2016-11-28 14:09:09 -08002647
2648 first = false;
2649 });
Mathias Agopian84300952012-11-21 16:02:13 -08002650 }
2651
2652
Mathias Agopian3559b072012-08-15 13:46:03 -07002653 /*
2654 * Perform our own transaction if needed
2655 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002656
2657 if (mLayersAdded) {
2658 mLayersAdded = false;
2659 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002660 mVisibleRegionsDirty = true;
2661 }
2662
2663 // some layers might have been removed, so
2664 // we need to update the regions they're exposing.
2665 if (mLayersRemoved) {
2666 mLayersRemoved = false;
2667 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002668 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002670 // this layer is not visible anymore
2671 // TODO: we could traverse the tree from front to back and
2672 // compute the actual visible region
2673 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 Region visibleReg;
2675 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002676 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002677 }
Robert Carr2047fae2016-11-28 14:09:09 -08002678 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679 }
2680
2681 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002682
2683 updateCursorAsync();
2684}
2685
2686void SurfaceFlinger::updateCursorAsync()
2687{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002688 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2689 auto& displayDevice = mDisplays[displayId];
2690 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002691 continue;
2692 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693
2694 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2695 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002696 }
2697 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002698}
2699
2700void SurfaceFlinger::commitTransaction()
2701{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002702 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002703 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 for (const auto& l : mLayersPendingRemoval) {
2705 recordBufferingStats(l->getName().string(),
2706 l->getOccupancyHistory(true));
2707 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002708 }
2709 mLayersPendingRemoval.clear();
2710 }
2711
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002712 // If this transaction is part of a window animation then the next frame
2713 // we composite should be considered an animation as well.
2714 mAnimCompositionPending = mAnimTransactionPending;
2715
Mathias Agopian4fec8732012-06-29 14:12:52 -07002716 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002717 // clear the "changed" flags in current state
2718 mCurrentState.colorMatrixChanged = false;
2719
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 mDrawingState.traverseInZOrder([](Layer* layer) {
2721 layer->commitChildList();
2722 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002723 mTransactionPending = false;
2724 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726}
2727
Chia-I Wuab0c3192017-08-01 11:29:00 -07002728void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002729 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730{
Mathias Agopian841cde52012-03-01 15:44:37 -08002731 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 Region aboveOpaqueLayers;
2735 Region aboveCoveredLayers;
2736 Region dirty;
2737
Mathias Agopian87baae12012-07-31 12:38:26 -07002738 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739
Robert Carr2047fae2016-11-28 14:09:09 -08002740 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002742 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
Jesse Hall01e29052013-02-19 16:13:35 -08002744 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002745 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002746 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002747
Mathias Agopianab028732010-03-16 16:41:46 -07002748 /*
2749 * opaqueRegion: area of a surface that is fully opaque.
2750 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002752
2753 /*
2754 * visibleRegion: area of a surface that is visible on screen
2755 * and not fully transparent. This is essentially the layer's
2756 * footprint minus the opaque regions above it.
2757 * Areas covered by a translucent surface are considered visible.
2758 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002760
2761 /*
2762 * coveredRegion: area of a surface that is covered by all
2763 * visible regions above it (which includes the translucent areas).
2764 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002766
Jesse Halla8026d22012-09-25 13:25:04 -07002767 /*
2768 * transparentRegion: area of a surface that is hinted to be completely
2769 * transparent. This is only used to tell when the layer has no visible
2770 * non-transparent regions and can be removed from the layer list. It
2771 * does not affect the visibleRegion of this layer or any layers
2772 * beneath it. The hint may not be correct if apps don't respect the
2773 * SurfaceView restrictions (which, sadly, some don't).
2774 */
2775 Region transparentRegion;
2776
Mathias Agopianab028732010-03-16 16:41:46 -07002777
2778 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002779 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002780 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002784 if (!visibleRegion.isEmpty()) {
2785 // Remove the transparent area from the visible region
2786 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002787 if (tr.preserveRects()) {
2788 // transform the transparent region
2789 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002790 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002791 // transformation too complex, can't do the
2792 // transparent region optimization.
2793 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794 }
Mathias Agopianab028732010-03-16 16:41:46 -07002795 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Mathias Agopianab028732010-03-16 16:41:46 -07002797 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002799 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002800 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2801 // the opaque region is the layer's footprint
2802 opaqueRegion = visibleRegion;
2803 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 }
2805 }
2806
Robert Carre5f4f692018-01-12 13:12:28 -08002807 if (visibleRegion.isEmpty()) {
2808 layer->clearVisibilityRegions();
2809 return;
2810 }
2811
Mathias Agopianab028732010-03-16 16:41:46 -07002812 // Clip the covered region to the visible region
2813 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2814
2815 // Update aboveCoveredLayers for next (lower) layer
2816 aboveCoveredLayers.orSelf(visibleRegion);
2817
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 // subtract the opaque region covered by the layers above us
2819 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820
2821 // compute this layer's dirty region
2822 if (layer->contentDirty) {
2823 // we need to invalidate the whole region
2824 dirty = visibleRegion;
2825 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 layer->contentDirty = false;
2828 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002829 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002830 * the exposed region consists of two components:
2831 * 1) what's VISIBLE now and was COVERED before
2832 * 2) what's EXPOSED now less what was EXPOSED before
2833 *
2834 * note that (1) is conservative, we start with the whole
2835 * visible region but only keep what used to be covered by
2836 * something -- which mean it may have been exposed.
2837 *
2838 * (2) handles areas that were not covered by anything but got
2839 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002840 */
Mathias Agopianab028732010-03-16 16:41:46 -07002841 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002842 const Region oldVisibleRegion = layer->visibleRegion;
2843 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002844 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2845 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846 }
2847 dirty.subtractSelf(aboveOpaqueLayers);
2848
2849 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002850 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851
Mathias Agopianab028732010-03-16 16:41:46 -07002852 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002854
Jesse Halla8026d22012-09-25 13:25:04 -07002855 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 layer->setVisibleRegion(visibleRegion);
2857 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002858 layer->setVisibleNonTransparentRegion(
2859 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002860 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861
Mathias Agopian87baae12012-07-31 12:38:26 -07002862 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863}
2864
Chia-I Wuab0c3192017-08-01 11:29:00 -07002865void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002866 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002867 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002868 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002869 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002870 }
2871 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002872}
2873
Dan Stoza6b9454d2014-11-07 16:00:59 -08002874bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 ALOGV("handlePageFlip");
2877
Brian Andersond6927fb2016-07-23 23:37:30 -07002878 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879
Mathias Agopian4fec8732012-06-29 14:12:52 -07002880 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002881 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002882 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002883
2884 // Store the set of layers that need updates. This set must not change as
2885 // buffers are being latched, as this could result in a deadlock.
2886 // Example: Two producers share the same command stream and:
2887 // 1.) Layer 0 is latched
2888 // 2.) Layer 0 gets a new frame
2889 // 2.) Layer 1 gets a new frame
2890 // 3.) Layer 1 is latched.
2891 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2892 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002893 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002894 if (layer->hasQueuedFrame()) {
2895 frameQueued = true;
2896 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002897 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002898 } else {
2899 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002900 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002901 } else {
2902 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002903 }
Robert Carr2047fae2016-11-28 14:09:09 -08002904 });
2905
Dan Stoza9e56aa02015-11-02 13:00:03 -08002906 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002907 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002908 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002909 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002910 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002911 newDataLatched = true;
2912 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002913 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002914
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002915 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916
2917 // If we will need to wake up at some time in the future to deal with a
2918 // queued frame that shouldn't be displayed during this vsync period, wake
2919 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002920 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921 signalLayerUpdate();
2922 }
2923
2924 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002925 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926}
2927
Mathias Agopianad456f92011-01-13 17:53:01 -08002928void SurfaceFlinger::invalidateHwcGeometry()
2929{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002931}
2932
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002933
Fabien Sanglard830b8472016-11-30 16:35:58 -08002934void SurfaceFlinger::doDisplayComposition(
2935 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002936 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937{
Dan Stoza71433162014-02-04 16:22:36 -08002938 // We only need to actually compose the display if:
2939 // 1) It is being handled by hardware composer, which may need this to
2940 // keep its virtual display state machine in sync, or
2941 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002942 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002943 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002945 return;
2946 }
2947
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002949 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002950
2951 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002952 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953}
2954
Chia-I Wub02087d2017-11-09 10:19:54 -08002955bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002956{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002958
Chia-I Wub02087d2017-11-09 10:19:54 -08002959 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002960 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002962 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002963 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002964
Chia-I Wu8e50e692018-05-04 10:12:37 -07002965 bool applyColorMatrix = false;
2966 bool applyLegacyColorMatrix = false;
2967 mat4 colorMatrix;
2968 mat4 legacyColorMatrix;
2969 const mat4* currentColorMatrix = nullptr;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002970
Dan Stoza9e56aa02015-11-02 13:00:03 -08002971 if (hasClientComposition) {
2972 ALOGV("hasClientComposition");
2973
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002974 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002975 if (displayDevice->hasWideColorGamut()) {
2976 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002977 }
2978 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002979 getBE().mRenderEngine->setDisplayMaxLuminance(
2980 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002981
Chia-I Wu8e50e692018-05-04 10:12:37 -07002982 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2983 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2984 HWC2::Capability::SkipClientColorTransform);
2985
2986 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2987 if (applyColorMatrix) {
2988 colorMatrix = mDrawingState.colorMatrix;
2989 }
2990
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002991 applyLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2992 outputDataspace != Dataspace::UNKNOWN &&
2993 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002994 if (applyLegacyColorMatrix) {
2995 if (applyColorMatrix) {
2996 legacyColorMatrix = colorMatrix * mLegacySrgbSaturationMatrix;
2997 } else {
2998 legacyColorMatrix = mLegacySrgbSaturationMatrix;
2999 }
3000 }
3001
Chia-I Wu7f402902017-11-09 12:51:10 -08003002 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003003 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003004 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003005 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003006
3007 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003008 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003009 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3010 }
3011 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003012 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003013
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003014 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003016 // when using overlays, we assume a fully transparent framebuffer
3017 // NOTE: we could reduce how much we need to clear, for instance
3018 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003019 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003020 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003021 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003022 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003023 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003024 // we're left with the letterbox region
3025 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003026 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003027
3028 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003029 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003030
Mathias Agopianb9494d52012-04-18 02:28:45 -07003031 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003032 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003033 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003035 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003036 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003037
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003039 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003040 // scissor on the main display. It should never be needed
3041 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003042 const Rect& bounds(displayDevice->getBounds());
3043 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003044 if (scissor != bounds) {
3045 // scissor doesn't match the screen's dimensions, so we
3046 // need to clear everything outside of it and enable
3047 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003048
Mathias Agopianf45c5102012-10-24 16:29:17 -07003049 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003051 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003052 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003053 }
3054 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003055 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003056
Mathias Agopian85d751c2012-08-29 16:59:24 -07003057 /*
3058 * and then, render the layers targeted at the framebuffer
3059 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003060
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 ALOGV("Rendering client layers");
3062 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003063 bool firstLayer = true;
3064 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3065 const Region clip(bounds.intersect(
3066 displayTransform.transform(layer->visibleRegion)));
3067 ALOGV("Layer: %s", layer->getName().string());
3068 ALOGV(" Composition type: %s",
3069 to_string(layer->getCompositionType(hwcId)).c_str());
3070 if (!clip.isEmpty()) {
3071 switch (layer->getCompositionType(hwcId)) {
3072 case HWC2::Composition::Cursor:
3073 case HWC2::Composition::Device:
3074 case HWC2::Composition::Sideband:
3075 case HWC2::Composition::SolidColor: {
3076 const Layer::State& state(layer->getDrawingState());
3077 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3078 layer->isOpaque(state) && (state.color.a == 1.0f)
3079 && hasClientComposition) {
3080 // never clear the very first layer since we're
3081 // guaranteed the FB is already cleared
3082 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003083 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003084 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003085 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003086 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003087 // switch color matrices lazily
3088 if (layer->isLegacyDataSpace()) {
3089 if (applyLegacyColorMatrix && currentColorMatrix != &legacyColorMatrix) {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07003090 // TODO(b/78891890) Legacy sRGB saturation matrix should be set
3091 // separately.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003092 getRenderEngine().setupColorTransform(legacyColorMatrix);
3093 currentColorMatrix = &legacyColorMatrix;
3094 }
3095 } else {
3096 if (applyColorMatrix && currentColorMatrix != &colorMatrix) {
3097 getRenderEngine().setupColorTransform(colorMatrix);
3098 currentColorMatrix = &colorMatrix;
3099 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003101
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003102 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 break;
3104 }
3105 default:
3106 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003107 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003108 } else {
3109 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003110 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003111 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003112 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003113
Chia-I Wu8e50e692018-05-04 10:12:37 -07003114 if (applyColorMatrix || applyLegacyColorMatrix) {
3115 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003116 }
3117
Mathias Agopianf45c5102012-10-24 16:29:17 -07003118 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003119 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003120 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121}
3122
Fabien Sanglard830b8472016-11-30 16:35:58 -08003123void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3124 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003125 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003126 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127}
3128
Dan Stoza7d89d062015-04-30 13:29:25 -07003129status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003130 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003131 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003132 const sp<Layer>& lbc,
3133 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003134{
Dan Stoza7d89d062015-04-30 13:29:25 -07003135 // add this layer to the current state list
3136 {
3137 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003139 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3140 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003141 return NO_MEMORY;
3142 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 if (parent == nullptr) {
3144 mCurrentState.layersSortedByZ.add(lbc);
3145 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003146 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003147 ALOGE("addClientLayer called with a removed parent");
3148 return NAME_NOT_FOUND;
3149 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 parent->addChild(lbc);
3151 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003152
Dan Stoza101d8dc2018-02-27 15:42:25 -08003153 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003154 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3155 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3156 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3157 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3158 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 mLayersAdded = true;
3160 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003161 }
3162
Mathias Agopian96f08192010-06-02 23:28:45 -07003163 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003164 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003165
Dan Stoza7d89d062015-04-30 13:29:25 -07003166 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003167}
3168
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003169status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003170 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003171 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3172}
Robert Carr7f9b8992017-03-10 11:08:39 -08003173
chaviwca27f252018-02-06 16:46:39 -08003174status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3175 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003176 if (layer->isPendingRemoval()) {
3177 return NO_ERROR;
3178 }
3179
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003181 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003182 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003183 if (topLevelOnly) {
3184 return NO_ERROR;
3185 }
3186
Chia-I Wu98f1c102017-05-30 14:54:08 -07003187 sp<Layer> ancestor = p;
3188 while (ancestor->getParent() != nullptr) {
3189 ancestor = ancestor->getParent();
3190 }
3191 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3192 ALOGE("removeLayer called with a layer whose parent has been removed");
3193 return NAME_NOT_FOUND;
3194 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003195
3196 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003197 } else {
3198 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003199 }
3200
Robert Carr136e2f62017-02-08 17:54:29 -08003201 // As a matter of normal operation, the LayerCleaner will produce a second
3202 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3203 // so we will succeed in promoting it, but it's already been removed
3204 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3205 // otherwise something has gone wrong and we are leaking the layer.
3206 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3208 layer->getName().string(),
3209 (p != nullptr) ? p->getName().string() : "no-parent");
3210 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003211 } else if (index < 0) {
3212 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003213 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003214
Chia-I Wuc6657022017-08-15 11:18:17 -07003215 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003216 mLayersPendingRemoval.add(layer);
3217 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003218 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003219 setTransactionFlags(eTransactionNeeded);
3220 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221}
3222
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003223uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003224 return android_atomic_release_load(&mTransactionFlags);
3225}
3226
Mathias Agopian3f844832013-08-07 21:24:32 -07003227uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3229}
3230
Mathias Agopian3f844832013-08-07 21:24:32 -07003231uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003232 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3233}
3234
3235uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3236 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003238 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003240 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 }
3242 return old;
3243}
3244
chaviwca27f252018-02-06 16:46:39 -08003245bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3246 for (const ComposerState& state : states) {
3247 // Here we need to check that the interface we're given is indeed
3248 // one of our own. A malicious client could give us a nullptr
3249 // IInterface, or one of its own or even one of our own but a
3250 // different type. All these situations would cause us to crash.
3251 if (state.client == nullptr) {
3252 return true;
3253 }
3254
3255 sp<IBinder> binder = IInterface::asBinder(state.client);
3256 if (binder == nullptr) {
3257 return true;
3258 }
3259
3260 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3261 return true;
3262 }
3263 }
3264 return false;
3265}
3266
Mathias Agopian8b33f032012-07-24 20:43:54 -07003267void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003268 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003269 const Vector<DisplayState>& displays,
3270 uint32_t flags)
3271{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003272 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003273 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003274 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003275
chaviwca27f252018-02-06 16:46:39 -08003276 if (containsAnyInvalidClientState(states)) {
3277 return;
3278 }
3279
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003280 if (flags & eAnimation) {
3281 // For window updates that are part of an animation we must wait for
3282 // previous animation "frames" to be handled.
3283 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003284 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003285 if (CC_UNLIKELY(err != NO_ERROR)) {
3286 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003287 // caller after a few seconds.
3288 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3289 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003290 mAnimTransactionPending = false;
3291 break;
3292 }
3293 }
3294 }
3295
chaviwca27f252018-02-06 16:46:39 -08003296 for (const DisplayState& display : displays) {
3297 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003298 }
3299
chaviwca27f252018-02-06 16:46:39 -08003300 for (const ComposerState& state : states) {
3301 transactionFlags |= setClientStateLocked(state);
3302 }
3303
3304 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3305 // as destroyed should only occur after setting all other states. This is to allow for a
3306 // child re-parent to happen before marking its original parent as destroyed (which would
3307 // then mark the child as destroyed).
3308 for (const ComposerState& state : states) {
3309 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003310 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003311
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003312 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3313 // anyway. This can be used as a flush mechanism for previous async transactions.
3314 // Empty animation transaction can be used to simulate back-pressure, so also force a
3315 // transaction for empty animation transactions.
3316 if (transactionFlags == 0 &&
3317 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003318 transactionFlags = eTransactionNeeded;
3319 }
3320
Mathias Agopian386aa982011-11-07 21:58:03 -08003321 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003322 if (mInterceptor->isEnabled()) {
3323 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003324 }
Irvel468051e2016-06-13 16:44:44 -07003325
Mathias Agopian386aa982011-11-07 21:58:03 -08003326 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003327 const auto start = (flags & eEarlyWakeup)
3328 ? VSyncModulator::TransactionStart::EARLY
3329 : VSyncModulator::TransactionStart::NORMAL;
3330 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003331
3332 // if this is a synchronous transaction, wait for it to take effect
3333 // before returning.
3334 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003335 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003336 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003337 if (flags & eAnimation) {
3338 mAnimTransactionPending = true;
3339 }
3340 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003341 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3342 if (CC_UNLIKELY(err != NO_ERROR)) {
3343 // just in case something goes wrong in SF, return to the
3344 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003345 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3346 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003347 break;
3348 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350 }
3351}
3352
Mathias Agopiane57f2922012-08-09 16:29:12 -07003353uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3354{
Jesse Hall9a143922012-10-04 16:29:19 -07003355 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3356 if (dpyIdx < 0)
3357 return 0;
3358
Mathias Agopiane57f2922012-08-09 16:29:12 -07003359 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003360 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003361 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 const uint32_t what = s.what;
3363 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003364 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365 disp.surface = s.surface;
3366 flags |= eDisplayTransactionNeeded;
3367 }
3368 }
3369 if (what & DisplayState::eLayerStackChanged) {
3370 if (disp.layerStack != s.layerStack) {
3371 disp.layerStack = s.layerStack;
3372 flags |= eDisplayTransactionNeeded;
3373 }
3374 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003375 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003376 if (disp.orientation != s.orientation) {
3377 disp.orientation = s.orientation;
3378 flags |= eDisplayTransactionNeeded;
3379 }
3380 if (disp.frame != s.frame) {
3381 disp.frame = s.frame;
3382 flags |= eDisplayTransactionNeeded;
3383 }
3384 if (disp.viewport != s.viewport) {
3385 disp.viewport = s.viewport;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 }
Michael Lentine47e45402014-07-18 15:34:25 -07003389 if (what & DisplayState::eDisplaySizeChanged) {
3390 if (disp.width != s.width) {
3391 disp.width = s.width;
3392 flags |= eDisplayTransactionNeeded;
3393 }
3394 if (disp.height != s.height) {
3395 disp.height = s.height;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003399 }
3400 return flags;
3401}
3402
chaviwca27f252018-02-06 16:46:39 -08003403uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3404 const layer_state_t& s = composerState.state;
3405 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3406
Mathias Agopian13127d82013-03-05 17:47:11 -08003407 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003408 if (layer == nullptr) {
3409 return 0;
3410 }
3411
3412 if (layer->isPendingRemoval()) {
3413 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3414 return 0;
3415 }
3416
3417 uint32_t flags = 0;
3418
3419 const uint32_t what = s.what;
3420 bool geometryAppliesWithResize =
3421 what & layer_state_t::eGeometryAppliesWithResize;
3422 if (what & layer_state_t::ePositionChanged) {
3423 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3424 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003425 }
chaviw8b3871a2017-11-01 17:41:01 -07003426 }
3427 if (what & layer_state_t::eLayerChanged) {
3428 // NOTE: index needs to be calculated before we update the state
3429 const auto& p = layer->getParent();
3430 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003431 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003432 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003433 mCurrentState.layersSortedByZ.removeAt(idx);
3434 mCurrentState.layersSortedByZ.add(layer);
3435 // we need traversal (state changed)
3436 // AND transaction (list changed)
3437 flags |= eTransactionNeeded|eTraversalNeeded;
3438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 } else {
3440 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003441 flags |= eTransactionNeeded|eTraversalNeeded;
3442 }
3443 }
chaviw8b3871a2017-11-01 17:41:01 -07003444 }
3445 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003446 // NOTE: index needs to be calculated before we update the state
3447 const auto& p = layer->getParent();
3448 if (p == nullptr) {
3449 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3450 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3451 mCurrentState.layersSortedByZ.removeAt(idx);
3452 mCurrentState.layersSortedByZ.add(layer);
3453 // we need traversal (state changed)
3454 // AND transaction (list changed)
3455 flags |= eTransactionNeeded|eTraversalNeeded;
3456 }
3457 } else {
3458 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3459 flags |= eTransactionNeeded|eTraversalNeeded;
3460 }
chaviw8b3871a2017-11-01 17:41:01 -07003461 }
3462 }
3463 if (what & layer_state_t::eSizeChanged) {
3464 if (layer->setSize(s.w, s.h)) {
3465 flags |= eTraversalNeeded;
3466 }
3467 }
3468 if (what & layer_state_t::eAlphaChanged) {
3469 if (layer->setAlpha(s.alpha))
3470 flags |= eTraversalNeeded;
3471 }
3472 if (what & layer_state_t::eColorChanged) {
3473 if (layer->setColor(s.color))
3474 flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eMatrixChanged) {
3477 if (layer->setMatrix(s.matrix))
3478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eTransparentRegionChanged) {
3481 if (layer->setTransparentRegionHint(s.transparentRegion))
3482 flags |= eTraversalNeeded;
3483 }
3484 if (what & layer_state_t::eFlagsChanged) {
3485 if (layer->setFlags(s.flags, s.mask))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eCropChanged) {
3489 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eFinalCropChanged) {
3493 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3494 flags |= eTraversalNeeded;
3495 }
3496 if (what & layer_state_t::eLayerStackChanged) {
3497 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3498 // We only allow setting layer stacks for top level layers,
3499 // everything else inherits layer stack from its parent.
3500 if (layer->hasParent()) {
3501 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3502 layer->getName().string());
3503 } else if (idx < 0) {
3504 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3505 "that also does not appear in the top level layer list. Something"
3506 " has gone wrong.", layer->getName().string());
3507 } else if (layer->setLayerStack(s.layerStack)) {
3508 mCurrentState.layersSortedByZ.removeAt(idx);
3509 mCurrentState.layersSortedByZ.add(layer);
3510 // we need traversal (state changed)
3511 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003512 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003513 }
3514 }
3515 if (what & layer_state_t::eDeferTransaction) {
3516 if (s.barrierHandle != nullptr) {
3517 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3518 } else if (s.barrierGbp != nullptr) {
3519 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3520 if (authenticateSurfaceTextureLocked(gbp)) {
3521 const auto& otherLayer =
3522 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3523 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3524 } else {
3525 ALOGE("Attempt to defer transaction to to an"
3526 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003527 }
3528 }
chaviw8b3871a2017-11-01 17:41:01 -07003529 // We don't trigger a traversal here because if no other state is
3530 // changed, we don't want this to cause any more work
3531 }
3532 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003533 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003534 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003535 if (!hadParent) {
3536 mCurrentState.layersSortedByZ.remove(layer);
3537 }
chaviw8b3871a2017-11-01 17:41:01 -07003538 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003539 }
chaviw8b3871a2017-11-01 17:41:01 -07003540 }
3541 if (what & layer_state_t::eReparentChildren) {
3542 if (layer->reparentChildren(s.reparentHandle)) {
3543 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003544 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003545 }
chaviw8b3871a2017-11-01 17:41:01 -07003546 if (what & layer_state_t::eDetachChildren) {
3547 layer->detachChildren();
3548 }
3549 if (what & layer_state_t::eOverrideScalingModeChanged) {
3550 layer->setOverrideScalingMode(s.overrideScalingMode);
3551 // We don't trigger a traversal here because if no other state is
3552 // changed, we don't want this to cause any more work
3553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003554 return flags;
3555}
3556
chaviwca27f252018-02-06 16:46:39 -08003557void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3558 const layer_state_t& state = composerState.state;
3559 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3560
3561 sp<Layer> layer(client->getLayerUser(state.surface));
3562 if (layer == nullptr) {
3563 return;
3564 }
3565
3566 if (layer->isPendingRemoval()) {
3567 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3568 return;
3569 }
3570
3571 if (state.what & layer_state_t::eDestroySurface) {
3572 removeLayerLocked(mStateLock, layer);
3573 }
3574}
3575
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003576status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003577 const String8& name,
3578 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003579 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003580 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003581 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003583 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003584 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003585 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003586 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003587 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003588
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 status_t result = NO_ERROR;
3590
3591 sp<Layer> layer;
3592
Cody Northropbc755282017-03-31 12:00:08 -06003593 String8 uniqueName = getUniqueLayerName(name);
3594
Mathias Agopian3165cc22012-08-08 19:42:09 -07003595 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3596 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003597 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003598 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003600
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601 break;
chaviw13fdc492017-06-27 12:40:18 -07003602 case ISurfaceComposerClient::eFXSurfaceColor:
3603 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003604 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003605 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606 break;
3607 default:
3608 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 break;
3610 }
3611
Dan Stoza7d89d062015-04-30 13:29:25 -07003612 if (result != NO_ERROR) {
3613 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003615
Chia-I Wuab0c3192017-08-01 11:29:00 -07003616 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3617 // TODO b/64227542
3618 if (windowType == 441731) {
3619 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3620 layer->setPrimaryDisplayOnly();
3621 }
3622
Albert Chaulk479c60c2017-01-27 14:21:34 -05003623 layer->setInfo(windowType, ownerUid);
3624
Robert Carr1f0a16a2016-10-24 16:27:39 -07003625 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003626 if (result != NO_ERROR) {
3627 return result;
3628 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003629 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003630
3631 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003632 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633}
3634
Cody Northropbc755282017-03-31 12:00:08 -06003635String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3636{
3637 bool matchFound = true;
3638 uint32_t dupeCounter = 0;
3639
3640 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3641 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3642
3643 // Loop over layers until we're sure there is no matching name
3644 while (matchFound) {
3645 matchFound = false;
3646 mDrawingState.traverseInZOrder([&](Layer* layer) {
3647 if (layer->getName() == uniqueName) {
3648 matchFound = true;
3649 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3650 }
3651 });
3652 }
3653
3654 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3655
3656 return uniqueName;
3657}
3658
David Sodman0c69cad2017-08-21 12:12:51 -07003659status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3661 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662{
3663 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003664 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665 case PIXEL_FORMAT_TRANSPARENT:
3666 case PIXEL_FORMAT_TRANSLUCENT:
3667 format = PIXEL_FORMAT_RGBA_8888;
3668 break;
3669 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003670 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671 break;
3672 }
3673
David Sodman0c69cad2017-08-21 12:12:51 -07003674 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3675 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003676 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003677 *handle = layer->getHandle();
3678 *gbp = layer->getProducer();
3679 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003681
David Sodman0c69cad2017-08-21 12:12:51 -07003682 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003683 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684}
3685
chaviw13fdc492017-06-27 12:40:18 -07003686status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003688 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003689{
chaviw13fdc492017-06-27 12:40:18 -07003690 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003692 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003693}
3694
Mathias Agopianac9fa422013-02-11 16:40:36 -08003695status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696{
Robert Carr9524cb32017-02-13 11:32:32 -08003697 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003698 status_t err = NO_ERROR;
3699 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003700 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003701 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003702 err = removeLayer(l);
3703 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3704 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003705 }
3706 return err;
3707}
3708
Mathias Agopian13127d82013-03-05 17:47:11 -08003709status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003710{
Mathias Agopian67106042013-03-14 19:18:13 -07003711 // called by ~LayerCleaner() when all references to the IBinder (handle)
3712 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003713 sp<Layer> l = layer.promote();
3714 if (l == nullptr) {
3715 // The layer has already been removed, carry on
3716 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003717 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003718 // If we have a parent, then we can continue to live as long as it does.
3719 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720}
3721
Mathias Agopianb60314a2012-04-10 22:09:54 -07003722// ---------------------------------------------------------------------------
3723
Andy McFadden13a082e2012-08-24 10:16:42 -07003724void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003725 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003726 Vector<ComposerState> state;
3727 Vector<DisplayState> displays;
3728 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003729 d.what = DisplayState::eDisplayProjectionChanged |
3730 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003731 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003732 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003733 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003734 d.frame.makeInvalid();
3735 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003736 d.width = 0;
3737 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003738 displays.add(d);
3739 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003740 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3741 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003742
David Sodman105b7dc2017-11-04 20:28:14 -07003743 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003744 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003745 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003746
Brian Andersond0010582017-03-07 13:20:31 -08003747 // Use phase of 0 since phase is not known.
3748 // Use latency of 0, which will snap to the ideal latency.
3749 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003750}
3751
3752void SurfaceFlinger::initializeDisplays() {
3753 class MessageScreenInitialized : public MessageBase {
3754 SurfaceFlinger* flinger;
3755 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003756 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003757 virtual bool handler() {
3758 flinger->onInitializeDisplays();
3759 return true;
3760 }
3761 };
3762 sp<MessageBase> msg = new MessageScreenInitialized(this);
3763 postMessageAsync(msg); // we may be called from main thread, use async message
3764}
3765
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003767 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003768 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3769 this);
3770 int32_t type = hw->getDisplayType();
3771 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003772
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 return;
3775 }
3776
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 hw->setPowerMode(mode);
3778 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3779 ALOGW("Trying to set power mode for virtual display");
3780 return;
3781 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003782
Lloyd Pique4d234852018-01-22 17:21:36 -08003783 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003784 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003785 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3786 if (idx < 0) {
3787 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3788 return;
3789 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003790 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003791 }
3792
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003794 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003796 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3797 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003798 // FIXME: eventthread only knows about the main display right now
3799 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003800 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003801 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003804 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003805 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003806
3807 struct sched_param param = {0};
3808 param.sched_priority = 1;
3809 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3810 ALOGW("Couldn't set SCHED_FIFO on display on");
3811 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003813 // Turn off the display
3814 struct sched_param param = {0};
3815 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3816 ALOGW("Couldn't set SCHED_OTHER on display off");
3817 }
3818
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003819 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3820 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003821 disableHardwareVsync(true); // also cancels any in-progress resync
3822
Mathias Agopiancde87a32012-09-13 14:09:01 -07003823 // FIXME: eventthread only knows about the main display right now
3824 mEventThread->onScreenReleased();
3825 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003826
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003827 getHwComposer().setPowerMode(type, mode);
3828 mVisibleRegionsDirty = true;
3829 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003830 } else if (mode == HWC_POWER_MODE_DOZE ||
3831 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003832 // Update display while dozing
3833 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003834 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3835 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003836 // FIXME: eventthread only knows about the main display right now
3837 mEventThread->onScreenAcquired();
3838 resyncToHardwareVsync(true);
3839 }
3840 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3841 // Leave display going to doze
3842 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3843 disableHardwareVsync(true); // also cancels any in-progress resync
3844 // FIXME: eventthread only knows about the main display right now
3845 mEventThread->onScreenReleased();
3846 }
3847 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003848 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003849 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003850 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003851 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003852 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003853}
3854
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003855void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3856 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003857 SurfaceFlinger& mFlinger;
3858 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003860 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003861 MessageSetPowerMode(SurfaceFlinger& flinger,
3862 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3863 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003864 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003865 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003866 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003867 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003868 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003869 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003870 ALOGW("Attempt to set power mode = %d for virtual display",
3871 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003872 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003873 mFlinger.setPowerModeInternal(
3874 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003875 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003876 return true;
3877 }
3878 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003879 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003880 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003881}
3882
3883// ---------------------------------------------------------------------------
3884
Lloyd Pique755e3192018-01-31 16:46:15 -08003885status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3886 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003888
Mathias Agopianbd115332013-04-18 16:41:04 -07003889 IPCThreadState* ipc = IPCThreadState::self();
3890 const int pid = ipc->getCallingPid();
3891 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003892
Mathias Agopianbd115332013-04-18 16:41:04 -07003893 if ((uid != AID_SHELL) &&
3894 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003895 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003896 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003898 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003899 // (this would indicate SF is stuck, but we want to be able to
3900 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003901 status_t err = mStateLock.timedLock(s2ns(1));
3902 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003903 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003904 result.appendFormat(
3905 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3906 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003907 }
3908
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909 bool dumpAll = true;
3910 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003911 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003912
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003913 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003914 if ((index < numArgs) &&
3915 (args[index] == String16("--list"))) {
3916 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003918 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919 }
3920
3921 if ((index < numArgs) &&
3922 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003923 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003924 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003925 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003927
3928 if ((index < numArgs) &&
3929 (args[index] == String16("--latency-clear"))) {
3930 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003931 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003932 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003933 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003934
3935 if ((index < numArgs) &&
3936 (args[index] == String16("--dispsync"))) {
3937 index++;
3938 mPrimaryDispSync.dump(result);
3939 dumpAll = false;
3940 }
Dan Stozab90cf072015-03-05 11:05:59 -08003941
3942 if ((index < numArgs) &&
3943 (args[index] == String16("--static-screen"))) {
3944 index++;
3945 dumpStaticScreenStats(result);
3946 dumpAll = false;
3947 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003948
3949 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003950 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003951 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003952 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003953 dumpAll = false;
3954 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003955
3956 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3957 index++;
3958 dumpWideColorInfo(result);
3959 dumpAll = false;
3960 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003961
3962 if ((index < numArgs) &&
3963 (args[index] == String16("--enable-layer-stats"))) {
3964 index++;
3965 mLayerStats.enable();
3966 dumpAll = false;
3967 }
3968
3969 if ((index < numArgs) &&
3970 (args[index] == String16("--disable-layer-stats"))) {
3971 index++;
3972 mLayerStats.disable();
3973 dumpAll = false;
3974 }
3975
3976 if ((index < numArgs) &&
3977 (args[index] == String16("--clear-layer-stats"))) {
3978 index++;
3979 mLayerStats.clear();
3980 dumpAll = false;
3981 }
3982
3983 if ((index < numArgs) &&
3984 (args[index] == String16("--dump-layer-stats"))) {
3985 index++;
3986 mLayerStats.dump(result);
3987 dumpAll = false;
3988 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003989
3990 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3991 index++;
3992 mTimeStats.parseArgs(asProto, args, index, result);
3993 dumpAll = false;
3994 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003995 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003996
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003997 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003998 if (asProto) {
3999 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4000 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4001 } else {
4002 dumpAllLocked(args, index, result);
4003 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004004 }
4005
Mathias Agopian9795c422009-08-26 16:36:26 -07004006 if (locked) {
4007 mStateLock.unlock();
4008 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 }
4010 write(fd, result.string(), result.size());
4011 return NO_ERROR;
4012}
4013
Dan Stozac7014012014-02-14 15:03:43 -08004014void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4015 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004016{
Robert Carr2047fae2016-11-28 14:09:09 -08004017 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004018 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004019 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004020}
4021
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004022void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004023 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004024{
4025 String8 name;
4026 if (index < args.size()) {
4027 name = String8(args[index]);
4028 index++;
4029 }
4030
David Sodman105b7dc2017-11-04 20:28:14 -07004031 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004032 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004033 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004034
4035 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004036 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004037 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004038 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004039 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004040 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004041 }
Robert Carr2047fae2016-11-28 14:09:09 -08004042 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004043 }
4044}
4045
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004046void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004047 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004048{
4049 String8 name;
4050 if (index < args.size()) {
4051 name = String8(args[index]);
4052 index++;
4053 }
4054
Robert Carr2047fae2016-11-28 14:09:09 -08004055 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004056 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004057 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058 }
Robert Carr2047fae2016-11-28 14:09:09 -08004059 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004060
Svetoslavd85084b2014-03-20 10:28:31 -07004061 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004062}
4063
Jamie Gennis6547ff42013-07-16 20:12:42 -07004064// This should only be called from the main thread. Otherwise it would need
4065// the lock and should use mCurrentState rather than mDrawingState.
4066void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004067 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004068 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004069 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004070
4071 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4072}
4073
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004074void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004075{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004076 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004077
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004078 if (isLayerTripleBufferingDisabled())
4079 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004080
4081 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004082 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004083 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004084 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004085 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4086 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004087 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004088}
4089
Dan Stozab90cf072015-03-05 11:05:59 -08004090void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4091{
4092 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004093 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4094 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004095 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004096 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004097 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4098 b + 1, bucketTimeSec, percent);
4099 }
David Sodman4a36e932017-11-07 14:29:47 -08004100 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004101 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004102 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004103 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004104 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004105}
4106
Dan Stozae77c7662016-05-13 11:37:28 -07004107void SurfaceFlinger::recordBufferingStats(const char* layerName,
4108 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004109 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4110 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004111 for (const auto& segment : history) {
4112 if (!segment.usedThirdBuffer) {
4113 stats.twoBufferTime += segment.totalTime;
4114 }
4115 if (segment.occupancyAverage < 1.0f) {
4116 stats.doubleBufferedTime += segment.totalTime;
4117 } else if (segment.occupancyAverage < 2.0f) {
4118 stats.tripleBufferedTime += segment.totalTime;
4119 }
4120 ++stats.numSegments;
4121 stats.totalTime += segment.totalTime;
4122 }
4123}
4124
Brian Andersond6927fb2016-07-23 23:37:30 -07004125void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4126 result.appendFormat("Layer frame timestamps:\n");
4127
4128 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4129 const size_t count = currentLayers.size();
4130 for (size_t i=0 ; i<count ; i++) {
4131 currentLayers[i]->dumpFrameEvents(result);
4132 }
4133}
4134
Dan Stozae77c7662016-05-13 11:37:28 -07004135void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4136 result.append("Buffering stats:\n");
4137 result.append(" [Layer name] <Active time> <Two buffer> "
4138 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004139 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004140 typedef std::tuple<std::string, float, float, float> BufferTuple;
4141 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004142 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004143 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004144 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004145 if (stats.numSegments == 0) {
4146 continue;
4147 }
4148 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4149 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4150 stats.totalTime;
4151 float doubleBufferRatio = static_cast<float>(
4152 stats.doubleBufferedTime) / stats.totalTime;
4153 float tripleBufferRatio = static_cast<float>(
4154 stats.tripleBufferedTime) / stats.totalTime;
4155 sorted.insert({activeTime, {name, twoBufferRatio,
4156 doubleBufferRatio, tripleBufferRatio}});
4157 }
4158 for (const auto& sortedPair : sorted) {
4159 float activeTime = sortedPair.first;
4160 const BufferTuple& values = sortedPair.second;
4161 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4162 std::get<0>(values).c_str(), activeTime,
4163 std::get<1>(values), std::get<2>(values),
4164 std::get<3>(values));
4165 }
4166 result.append("\n");
4167}
4168
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004169void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4170 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004171 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004172
4173 // TODO: print out if wide-color mode is active or not
4174
4175 for (size_t d = 0; d < mDisplays.size(); d++) {
4176 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4177 int32_t hwcId = displayDevice->getHwcDisplayId();
4178 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4179 continue;
4180 }
4181
4182 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004183 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004184 for (auto&& mode : modes) {
4185 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4186 }
4187
Peiyong Lina52f0292018-03-14 17:26:31 -07004188 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004189 result.appendFormat(" Current color mode: %s (%d)\n",
4190 decodeColorMode(currentMode).c_str(), currentMode);
4191 }
4192 result.append("\n");
4193}
4194
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004195LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004196 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004197 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4198 const State& state = useDrawing ? mDrawingState : mCurrentState;
4199 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004200 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004201 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004202 });
4203
4204 return layersProto;
4205}
4206
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004207LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4208 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004209 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004210
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004211 SizeProto* resolution = layersProto.mutable_resolution();
4212 resolution->set_w(displayDevice->getWidth());
4213 resolution->set_h(displayDevice->getHeight());
4214
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004215 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4216 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4217 layersProto.set_global_transform(
4218 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4219
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004220 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004221 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004222 LayerProto* layerProto = layersProto.add_layers();
4223 layer->writeToProto(layerProto, hwcId);
4224 }
4225 });
4226
4227 return layersProto;
4228}
4229
Mathias Agopian74d211a2013-04-22 16:55:35 +02004230void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4231 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004233 bool colorize = false;
4234 if (index < args.size()
4235 && (args[index] == String16("--color"))) {
4236 colorize = true;
4237 index++;
4238 }
4239
4240 Colorizer colorizer(colorize);
4241
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242 // figure out if we're stuck somewhere
4243 const nsecs_t now = systemTime();
4244 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4245 const nsecs_t inTransaction(mDebugInTransaction);
4246 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4247 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4248
4249 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004250 * Dump library configuration.
4251 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004252
4253 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004254 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004255 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004256 appendSfConfigString(result);
4257 appendUiConfigString(result);
4258 appendGuiConfigString(result);
4259 result.append("\n");
4260
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004261 result.append("\nWide-Color information:\n");
4262 dumpWideColorInfo(result);
4263
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004264 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004265 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004266 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004267 result.append(SyncFeatures::getInstance().toString());
4268 result.append("\n");
4269
David Sodman105b7dc2017-11-04 20:28:14 -07004270 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004271
Andy McFadden41d67d72014-04-25 16:58:34 -07004272 colorizer.bold(result);
4273 result.append("DispSync configuration: ");
4274 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004275 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4276 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4277 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004278 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004279 result.append("\n");
4280
Dan Stozab90cf072015-03-05 11:05:59 -08004281 // Dump static screen stats
4282 result.append("\n");
4283 dumpStaticScreenStats(result);
4284 result.append("\n");
4285
Dan Stozae77c7662016-05-13 11:37:28 -07004286 dumpBufferingStats(result);
4287
Andy McFadden4803b742012-09-24 19:07:20 -07004288 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289 * Dump the visible layer list
4290 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004292 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004293 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4294 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004295 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004296
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004297 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004298 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004299 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004300 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004301
4302 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004303 * Dump Display state
4304 */
4305
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004306 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004307 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004308 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004309 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4310 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004311 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004312 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004313 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004314
4315 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316 * Dump SurfaceFlinger global state
4317 */
4318
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004319 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004320 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004321 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004322
Mathias Agopian888c8222012-08-04 21:10:38 -07004323 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004324 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004325
David Sodmanbc815282017-11-05 18:57:52 -08004326 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004327
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004328 if (hw) {
4329 hw->undefinedRegion.dump(result, "undefinedRegion");
4330 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4331 hw->getOrientation(), hw->isDisplayOn());
4332 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004333 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334 " last eglSwapBuffers() time: %f us\n"
4335 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004336 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337 " refresh-rate : %f fps\n"
4338 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004339 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004340 " gpu_to_cpu_unsupported : %d\n"
4341 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342 mLastSwapBufferTime/1000.0,
4343 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004344 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004345 1e9 / activeConfig->getVsyncPeriod(),
4346 activeConfig->getDpiX(),
4347 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004348 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004349
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
Mathias Agopian74d211a2013-04-22 16:55:35 +02004353 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
4356 /*
4357 * VSYNC state
4358 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004360 result.append("\n");
4361
4362 /*
4363 * HWC layer minidump
4364 */
4365 for (size_t d = 0; d < mDisplays.size(); d++) {
4366 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4367 int32_t hwcId = displayDevice->getHwcDisplayId();
4368 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4369 continue;
4370 }
4371
4372 result.appendFormat("Display %d HWC layers:\n", hwcId);
4373 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004374 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004375 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004376 });
Dan Stozae22aec72016-08-01 13:20:59 -07004377 result.append("\n");
4378 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004379
4380 /*
4381 * Dump HWComposer state
4382 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004383 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004384 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004385 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004386 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004387 result.appendFormat(" h/w composer %s\n",
4388 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004389 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390
4391 /*
4392 * Dump gralloc state
4393 */
4394 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4395 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004396
4397 /*
4398 * Dump VrFlinger state if in use.
4399 */
4400 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4401 result.append("VrFlinger state:\n");
4402 result.append(mVrFlinger->Dump().c_str());
4403 result.append("\n");
4404 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405}
4406
Mathias Agopian13127d82013-03-05 17:47:11 -08004407const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004408SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004409 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004410 wp<IBinder> dpy;
4411 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4412 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4413 dpy = mDisplays.keyAt(i);
4414 break;
4415 }
4416 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004417 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004418 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4419 // Just use the primary display so we have something to return
4420 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4421 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004422 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004423}
4424
Keun young Park63f165f2012-08-31 10:53:36 -07004425bool SurfaceFlinger::startDdmConnection()
4426{
4427 void* libddmconnection_dso =
4428 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4429 if (!libddmconnection_dso) {
4430 return false;
4431 }
4432 void (*DdmConnection_start)(const char* name);
4433 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004434 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004435 if (!DdmConnection_start) {
4436 dlclose(libddmconnection_dso);
4437 return false;
4438 }
4439 (*DdmConnection_start)(getServiceName());
4440 return true;
4441}
4442
Chia-I Wu28f320b2018-05-03 11:02:56 -07004443void SurfaceFlinger::updateColorMatrixLocked() {
4444 mat4 colorMatrix;
4445 if (mGlobalSaturationFactor != 1.0f) {
4446 // Rec.709 luma coefficients
4447 float3 luminance{0.213f, 0.715f, 0.072f};
4448 luminance *= 1.0f - mGlobalSaturationFactor;
4449 mat4 saturationMatrix = mat4(
4450 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4451 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4452 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4453 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4454 );
4455 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4456 } else {
4457 colorMatrix = mClientColorMatrix * mDaltonizer();
4458 }
4459
4460 if (mCurrentState.colorMatrix != colorMatrix) {
4461 mCurrentState.colorMatrix = colorMatrix;
4462 mCurrentState.colorMatrixChanged = true;
4463 setTransactionFlags(eTransactionNeeded);
4464 }
4465}
4466
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004467status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 switch (code) {
4469 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004470 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004472 case CLEAR_ANIMATION_FRAME_STATS:
4473 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004474 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004475 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004476 case ENABLE_VSYNC_INJECTIONS:
4477 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 {
4479 // codes that require permission check
4480 IPCThreadState* ipc = IPCThreadState::self();
4481 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004482 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004483 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004484 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004485 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004486 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004488 break;
4489 }
Robert Carr1db73f62016-12-21 12:58:51 -08004490 /*
4491 * Calling setTransactionState is safe, because you need to have been
4492 * granted a reference to Client* and Handle* to do anything with it.
4493 *
4494 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4495 */
4496 case SET_TRANSACTION_STATE:
4497 case CREATE_SCOPED_CONNECTION:
4498 {
4499 return OK;
4500 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004501 case CAPTURE_SCREEN:
4502 {
4503 // codes that require permission check
4504 IPCThreadState* ipc = IPCThreadState::self();
4505 const int pid = ipc->getCallingPid();
4506 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004507 if ((uid != AID_GRAPHICS) &&
4508 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004509 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004510 return PERMISSION_DENIED;
4511 }
4512 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 }
chaviwa76b2712017-09-20 12:02:26 -07004514 case CAPTURE_LAYERS: {
4515 IPCThreadState* ipc = IPCThreadState::self();
4516 const int pid = ipc->getCallingPid();
4517 const int uid = ipc->getCallingUid();
4518 if ((uid != AID_GRAPHICS) &&
4519 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4520 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4521 return PERMISSION_DENIED;
4522 }
4523 break;
4524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004526 return OK;
4527}
4528
4529status_t SurfaceFlinger::onTransact(
4530 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4531{
4532 status_t credentialCheck = CheckTransactCodeCredentials(code);
4533 if (credentialCheck != OK) {
4534 return credentialCheck;
4535 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004537 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4538 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004539 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004540 IPCThreadState* ipc = IPCThreadState::self();
4541 const int uid = ipc->getCallingUid();
4542 if (CC_UNLIKELY(uid != AID_SYSTEM
4543 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004544 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004545 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004546 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004547 return PERMISSION_DENIED;
4548 }
4549 int n;
4550 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004551 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004552 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 return NO_ERROR;
4554 case 1002: // SHOW_UPDATES
4555 n = data.readInt32();
4556 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004557 invalidateHwcGeometry();
4558 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004561 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004564 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004565 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004566 setTransactionFlags(
4567 eTransactionNeeded|
4568 eDisplayTransactionNeeded|
4569 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004570 return NO_ERROR;
4571 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004572 case 1006:{ // send empty update
4573 signalRefresh();
4574 return NO_ERROR;
4575 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004576 case 1008: // toggle use of hw composer
4577 n = data.readInt32();
4578 mDebugDisableHWC = n ? 1 : 0;
4579 invalidateHwcGeometry();
4580 repaintEverything();
4581 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004582 case 1009: // toggle use of transform hint
4583 n = data.readInt32();
4584 mDebugDisableTransformHint = n ? 1 : 0;
4585 invalidateHwcGeometry();
4586 repaintEverything();
4587 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004588 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004589 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 reply->writeInt32(0);
4591 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004592 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004593 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 return NO_ERROR;
4595 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004596 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004597 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004598 return NO_ERROR;
4599 }
4600 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004601 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004602 // daltonize
4603 n = data.readInt32();
4604 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004605 case 1:
4606 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4607 break;
4608 case 2:
4609 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4610 break;
4611 case 3:
4612 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4613 break;
4614 default:
4615 mDaltonizer.setType(ColorBlindnessType::None);
4616 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004617 }
4618 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004619 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004620 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004621 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004622 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004623
4624 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004625 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004626 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004627 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004628 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004629 // apply a color matrix
4630 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004631 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004632 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004633 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004634 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004635 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004636 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004637 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004638 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004639 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004640 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004641
4642 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4643 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004645 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4646 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4647 }
4648
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004650 return NO_ERROR;
4651 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004652 // This is an experimental interface
4653 // Needs to be shifted to proper binder interface when we productize
4654 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004655 n = data.readInt32();
4656 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004657 return NO_ERROR;
4658 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004659 case 1017: {
4660 n = data.readInt32();
4661 mForceFullDamage = static_cast<bool>(n);
4662 return NO_ERROR;
4663 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004664 case 1018: { // Modify Choreographer's phase offset
4665 n = data.readInt32();
4666 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4667 return NO_ERROR;
4668 }
4669 case 1019: { // Modify SurfaceFlinger's phase offset
4670 n = data.readInt32();
4671 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4672 return NO_ERROR;
4673 }
Irvel468051e2016-06-13 16:44:44 -07004674 case 1020: { // Layer updates interceptor
4675 n = data.readInt32();
4676 if (n) {
4677 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004678 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004679 }
4680 else{
4681 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004682 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004683 }
4684 return NO_ERROR;
4685 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004686 case 1021: { // Disable HWC virtual displays
4687 n = data.readInt32();
4688 mUseHwcVirtualDisplays = !n;
4689 return NO_ERROR;
4690 }
Romain Guy0147a172017-06-01 13:53:56 -07004691 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004692 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004693 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004694
Chia-I Wu28f320b2018-05-03 11:02:56 -07004695 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004696 return NO_ERROR;
4697 }
Romain Guy54f154a2017-10-24 21:40:32 +01004698 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004699 int32_t value = data.readInt32();
4700 if (value > 2) {
4701 return BAD_VALUE;
4702 }
4703 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4704 return BAD_VALUE;
4705 }
Romain Guy54f154a2017-10-24 21:40:32 +01004706
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004707 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004708 invalidateHwcGeometry();
4709 repaintEverything();
4710 return NO_ERROR;
4711 }
4712 case 1024: { // Is wide color gamut rendering/color management supported?
4713 reply->writeBool(hasWideColorDisplay);
4714 return NO_ERROR;
4715 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004716 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004717 n = data.readInt32();
4718 if (n) {
4719 ALOGV("LayerTracing enabled");
4720 mTracing.enable();
4721 doTracing("tracing.enable");
4722 reply->writeInt32(NO_ERROR);
4723 } else {
4724 ALOGV("LayerTracing disabled");
4725 status_t err = mTracing.disable();
4726 reply->writeInt32(err);
4727 }
4728 return NO_ERROR;
4729 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004730 case 1026: { // Get layer tracing status
4731 reply->writeBool(mTracing.isEnabled());
4732 return NO_ERROR;
4733 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004734 // Is a DisplayColorSetting supported?
4735 case 1027: {
4736 int32_t value = data.readInt32();
4737 switch (value) {
4738 case 0:
4739 reply->writeBool(hasWideColorDisplay);
4740 return NO_ERROR;
4741 case 1:
4742 reply->writeBool(true);
4743 return NO_ERROR;
4744 case 2:
4745 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4746 return NO_ERROR;
4747 default:
4748 return BAD_VALUE;
4749 }
4750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004751 }
4752 }
4753 return err;
4754}
4755
Steven Thomas6d8110b2017-08-31 18:24:21 -07004756void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004757 android_atomic_or(1, &mRepaintEverything);
4758 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004759}
4760
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004761// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4762class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004763public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004764 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4765 ~WindowDisconnector() {
4766 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004767 }
4768
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004769private:
4770 ANativeWindow* mWindow;
4771 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004772};
4773
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004774status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4775 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4776 int32_t minLayerZ, int32_t maxLayerZ,
4777 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004778 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004779 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004780
chaviwa76b2712017-09-20 12:02:26 -07004781 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4782
4783 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004784 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4785
chaviwa76b2712017-09-20 12:02:26 -07004786 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4787
4788 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4789 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004790 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004791}
4792
4793status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004794 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004795 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004796 ATRACE_CALL();
4797
4798 class LayerRenderArea : public RenderArea {
4799 public:
Robert Carr578038f2018-03-09 12:25:24 -08004800 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4801 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004802 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004803 mLayer(layer),
4804 mCrop(crop),
4805 mFlinger(flinger),
4806 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004807 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004808 Rect getBounds() const override {
4809 const Layer::State& layerState(mLayer->getDrawingState());
4810 return Rect(layerState.active.w, layerState.active.h);
4811 }
4812 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4813 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4814 bool isSecure() const override { return false; }
4815 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004816 Rect getSourceCrop() const override {
4817 if (mCrop.isEmpty()) {
4818 return getBounds();
4819 } else {
4820 return mCrop;
4821 }
4822 }
4823 bool getWideColorSupport() const override { return false; }
4824 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004825 float getDisplayMaxLuminance() const override {
4826 return DisplayDevice::sDefaultMaxLumiance;
4827 }
Robert Carr578038f2018-03-09 12:25:24 -08004828
4829 class ReparentForDrawing {
4830 public:
4831 const sp<Layer>& oldParent;
4832 const sp<Layer>& newParent;
4833
4834 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4835 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004836 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004837 }
Robert Carr15eae092018-03-23 13:43:53 -07004838 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004839 };
4840
4841 void render(std::function<void()> drawLayers) override {
4842 if (!mChildrenOnly) {
4843 mTransform = mLayer->getTransform().inverse();
4844 drawLayers();
4845 } else {
4846 Rect bounds = getBounds();
4847 screenshotParentLayer =
4848 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4849 bounds.getWidth(), bounds.getHeight(), 0);
4850
4851 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4852 drawLayers();
4853 }
4854 }
chaviwa76b2712017-09-20 12:02:26 -07004855
chaviwa76b2712017-09-20 12:02:26 -07004856 private:
chaviw7206d492017-11-10 16:16:12 -08004857 const sp<Layer> mLayer;
4858 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004859
4860 // In the "childrenOnly" case we reparent the children to a screenshot
4861 // layer which has no properties set and which does not draw.
4862 sp<ContainerLayer> screenshotParentLayer;
4863 Transform mTransform;
4864
4865 SurfaceFlinger* mFlinger;
4866 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004867 };
4868
4869 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4870 auto parent = layerHandle->owner.promote();
4871
chaviw7206d492017-11-10 16:16:12 -08004872 if (parent == nullptr || parent->isPendingRemoval()) {
4873 ALOGE("captureLayers called with a removed parent");
4874 return NAME_NOT_FOUND;
4875 }
4876
Robert Carr578038f2018-03-09 12:25:24 -08004877 const int uid = IPCThreadState::self()->getCallingUid();
4878 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4879 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4880 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4881 return PERMISSION_DENIED;
4882 }
4883
chaviw7206d492017-11-10 16:16:12 -08004884 Rect crop(sourceCrop);
4885 if (sourceCrop.width() <= 0) {
4886 crop.left = 0;
4887 crop.right = parent->getCurrentState().active.w;
4888 }
4889
4890 if (sourceCrop.height() <= 0) {
4891 crop.top = 0;
4892 crop.bottom = parent->getCurrentState().active.h;
4893 }
4894
4895 int32_t reqWidth = crop.width() * frameScale;
4896 int32_t reqHeight = crop.height() * frameScale;
4897
Robert Carr578038f2018-03-09 12:25:24 -08004898 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004899
Robert Carr578038f2018-03-09 12:25:24 -08004900 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004901 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4902 if (!layer->isVisible()) {
4903 return;
Robert Carr578038f2018-03-09 12:25:24 -08004904 } else if (childrenOnly && layer == parent.get()) {
4905 return;
chaviwa76b2712017-09-20 12:02:26 -07004906 }
4907 visitor(layer);
4908 });
4909 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004910 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004911}
4912
4913status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4914 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004915 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004916 bool useIdentityTransform) {
4917 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004918
chaviwa76b2712017-09-20 12:02:26 -07004919 renderArea.updateDimensions();
4920
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004921 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4922 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4923 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4924 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004925
4926 // This mutex protects syncFd and captureResult for communication of the return values from the
4927 // main thread back to this Binder thread
4928 std::mutex captureMutex;
4929 std::condition_variable captureCondition;
4930 std::unique_lock<std::mutex> captureLock(captureMutex);
4931 int syncFd = -1;
4932 std::optional<status_t> captureResult;
4933
Robert Carr03480e22018-01-04 16:02:06 -08004934 const int uid = IPCThreadState::self()->getCallingUid();
4935 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4936
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004937 sp<LambdaMessage> message = new LambdaMessage([&]() {
4938 // If there is a refresh pending, bug out early and tell the binder thread to try again
4939 // after the refresh.
4940 if (mRefreshPending) {
4941 ATRACE_NAME("Skipping screenshot for now");
4942 std::unique_lock<std::mutex> captureLock(captureMutex);
4943 captureResult = std::make_optional<status_t>(EAGAIN);
4944 captureCondition.notify_one();
4945 return;
4946 }
4947
4948 status_t result = NO_ERROR;
4949 int fd = -1;
4950 {
4951 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004952 renderArea.render([&]() {
4953 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4954 useIdentityTransform, forSystem, &fd);
4955 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004956 }
4957
4958 {
4959 std::unique_lock<std::mutex> captureLock(captureMutex);
4960 syncFd = fd;
4961 captureResult = std::make_optional<status_t>(result);
4962 captureCondition.notify_one();
4963 }
4964 });
4965
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004966 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004967 if (result == NO_ERROR) {
4968 captureCondition.wait(captureLock, [&]() { return captureResult; });
4969 while (*captureResult == EAGAIN) {
4970 captureResult.reset();
4971 result = postMessageAsync(message);
4972 if (result != NO_ERROR) {
4973 return result;
4974 }
4975 captureCondition.wait(captureLock, [&]() { return captureResult; });
4976 }
4977 result = *captureResult;
4978 }
4979
4980 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004981 sync_wait(syncFd, -1);
4982 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004983 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004984
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004985 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004986}
4987
chaviwa76b2712017-09-20 12:02:26 -07004988void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4989 TraverseLayersFunction traverseLayers, bool yswap,
4990 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004991 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004992
Lloyd Pique144e1162017-12-20 16:44:52 -08004993 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004994
4995 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004996 const auto raWidth = renderArea.getWidth();
4997 const auto raHeight = renderArea.getHeight();
4998
4999 const auto reqWidth = renderArea.getReqWidth();
5000 const auto reqHeight = renderArea.getReqHeight();
5001 Rect sourceCrop = renderArea.getSourceCrop();
5002
5003 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5004 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005005
Dan Stozac1879002014-05-22 15:59:05 -07005006 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005007 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005008 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005009 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005010 }
5011
5012 // ensure that sourceCrop is inside screen
5013 if (sourceCrop.left < 0) {
5014 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5015 }
chaviwa76b2712017-09-20 12:02:26 -07005016 if (sourceCrop.right > raWidth) {
5017 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005018 }
5019 if (sourceCrop.top < 0) {
5020 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5021 }
chaviwa76b2712017-09-20 12:02:26 -07005022 if (sourceCrop.bottom > raHeight) {
5023 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005024 }
5025
Peiyong Lin34beb7a2018-03-28 11:57:12 -07005026 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005027 if (renderArea.getWideColorSupport()) {
5028 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08005029 }
Peiyong Linfb069302018-04-25 14:34:31 -07005030 engine.setOutputDataSpace(outputDataspace);
5031 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07005032
Mathias Agopian180f10d2013-04-10 22:55:41 -07005033 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005034 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005035
5036 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005037 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5038 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005039 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005040
chaviw50da5042018-04-09 13:49:37 -07005041 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005042 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005043 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005044
chaviwa76b2712017-09-20 12:02:26 -07005045 traverseLayers([&](Layer* layer) {
5046 if (filtering) layer->setFiltering(true);
5047 layer->draw(renderArea, useIdentityTransform);
5048 if (filtering) layer->setFiltering(false);
5049 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005050}
5051
chaviwa76b2712017-09-20 12:02:26 -07005052status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5053 TraverseLayersFunction traverseLayers,
5054 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005055 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005056 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005057 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005058 ATRACE_CALL();
5059
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005060 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005061
5062 traverseLayers([&](Layer* layer) {
5063 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5064 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005065
Robert Carr03480e22018-01-04 16:02:06 -08005066 // We allow the system server to take screenshots of secure layers for
5067 // use in situations like the Screen-rotation animation and place
5068 // the impetus on WindowManager to not persist them.
5069 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005070 ALOGW("FB is protected: PERMISSION_DENIED");
5071 return PERMISSION_DENIED;
5072 }
5073
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005074 // this binds the given EGLImage as a framebuffer for the
5075 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005076 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005077 if (bufferBond.getStatus() != NO_ERROR) {
5078 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005079 return INVALID_OPERATION;
5080 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005081
Dan Stozaabcda352017-06-01 14:37:39 -07005082 // this will in fact render into our dequeued buffer
5083 // via an FBO, which means we didn't have to create
5084 // an EGLSurface and therefore we're not
5085 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005086 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005087
Dan Stozaabcda352017-06-01 14:37:39 -07005088 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005089 getRenderEngine().finish();
5090 *outSyncFd = -1;
5091
chaviwa76b2712017-09-20 12:02:26 -07005092 const auto reqWidth = renderArea.getReqWidth();
5093 const auto reqHeight = renderArea.getReqHeight();
5094
Dan Stozaabcda352017-06-01 14:37:39 -07005095 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5096 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005097 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005098 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005099 } else {
5100 base::unique_fd syncFd = getRenderEngine().flush();
5101 if (syncFd < 0) {
5102 getRenderEngine().finish();
5103 }
5104 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005105 }
5106
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005107 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005108}
5109
Mathias Agopiand5556842013-09-19 17:08:37 -07005110void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005111 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005112 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005113 for (size_t y = 0; y < h; y++) {
5114 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5115 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005116 if (p[x] != 0xFF000000) return;
5117 }
5118 }
chaviwa76b2712017-09-20 12:02:26 -07005119 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005120
Robert Carr2047fae2016-11-28 14:09:09 -08005121 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005122 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005123 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005124 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5125 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5126 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5127 static_cast<float>(state.color.a));
5128 i++;
5129 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005130 }
5131}
5132
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005133// ---------------------------------------------------------------------------
5134
Dan Stoza412903f2017-04-27 13:42:17 -07005135void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5136 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005137}
5138
Dan Stoza412903f2017-04-27 13:42:17 -07005139void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5140 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005141}
5142
chaviwa76b2712017-09-20 12:02:26 -07005143void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5144 int32_t maxLayerZ,
5145 const LayerVector::Visitor& visitor) {
5146 // We loop through the first level of layers without traversing,
5147 // as we need to interpret min/max layer Z in the top level Z space.
5148 for (const auto& layer : mDrawingState.layersSortedByZ) {
5149 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5150 continue;
5151 }
5152 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005153 // relative layers are traversed in Layer::traverseInZOrder
5154 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005155 continue;
5156 }
5157 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005158 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5159 return;
5160 }
chaviwa76b2712017-09-20 12:02:26 -07005161 if (!layer->isVisible()) {
5162 return;
5163 }
5164 visitor(layer);
5165 });
5166 }
5167}
5168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005169}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005170
5171
5172#if defined(__gl_h_)
5173#error "don't include gl/gl.h in this file"
5174#endif
5175
5176#if defined(__gl2_h_)
5177#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005178#endif