blob: 01f855b33a0da31aaf28c017af8cd4a16dbdd174 [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 Lindd9b2ae2018-03-01 16:22:45 -08001022 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001023 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001025 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001027
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028 // Natural Mode means it's color managed and the color must be right,
1029 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1030 // Native Mode means the display is not color managed, and whichever
1031 // render intent is picked doesn't matter, thus return
1032 // RenderIntent::COLORIMETRIC as default here.
1033 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1034
1035 // In Auto Color Mode, we want to strech to panel color space, right now
1036 // only the built-in display supports it.
1037 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1038 mBuiltinDisplaySupportsEnhance &&
1039 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1040 renderIntent = RenderIntent::ENHANCE;
1041 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042
1043 if (mode == currentMode && dataSpace == currentDataSpace &&
1044 renderIntent == currentRenderIntent) {
1045 return;
1046 }
1047
1048 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1049 ALOGW("Trying to set config for virtual display");
1050 return;
1051 }
1052
1053 hw->setActiveColorMode(mode);
1054 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001055 hw->setActiveRenderIntent(renderIntent);
1056 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1057
1058 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1059 decodeColorMode(mode).c_str(), mode,
1060 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1061 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001062}
1063
1064
1065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001067 class MessageSetActiveColorMode: public MessageBase {
1068 SurfaceFlinger& mFlinger;
1069 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 public:
1072 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1075 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 mFlinger.getDisplayColorModes(mDisplay, &modes);
1078 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001080 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1081 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return true;
1083 }
1084 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1085 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001088 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001089 ALOGW("Attempt to set active color mode %s %d for virtual display",
1090 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001092 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
1094 return true;
1095 }
1096 };
1097 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1098 postMessageSync(msg);
1099 return NO_ERROR;
1100}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001101
Svetoslavd85084b2014-03-20 10:28:31 -07001102status_t SurfaceFlinger::clearAnimationFrameStats() {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.clearStats();
1105 return NO_ERROR;
1106}
1107
1108status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1109 Mutex::Autolock _l(mStateLock);
1110 mAnimFrameTracker.getStats(outStats);
1111 return NO_ERROR;
1112}
1113
Dan Stozac4f471e2016-03-24 09:31:08 -07001114status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1115 HdrCapabilities* outCapabilities) const {
1116 Mutex::Autolock _l(mStateLock);
1117
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001118 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001119 if (displayDevice == nullptr) {
1120 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1121 return BAD_VALUE;
1122 }
1123
Peiyong Linfb069302018-04-25 14:34:31 -07001124 // At this point the DisplayDeivce should already be set up,
1125 // meaning the luminance information is already queried from
1126 // hardware composer and stored properly.
1127 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1128 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1129 capabilities.getDesiredMaxLuminance(),
1130 capabilities.getDesiredMaxAverageLuminance(),
1131 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001132
1133 return NO_ERROR;
1134}
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1138 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 if (mInjectVSyncs == enable) {
1141 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143
1144 if (enable) {
1145 ALOGV("VSync Injections enabled");
1146 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001147 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001148 mInjectorEventThread =
1149 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1150 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001152 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 } else {
1154 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001155 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 }
1157
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 });
1160 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 return NO_ERROR;
1162}
1163
1164status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 Mutex::Autolock _l(mStateLock);
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 if (!mInjectVSyncs) {
1168 ALOGE("VSync Injections not enabled");
1169 return BAD_VALUE;
1170 }
1171 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1172 ALOGV("Injecting VSync inside SurfaceFlinger");
1173 mVSyncInjector->onInjectSyncEvent(when);
1174 }
1175 return NO_ERROR;
1176}
1177
Lloyd Pique755e3192018-01-31 16:46:15 -08001178status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1179 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001180 IPCThreadState* ipc = IPCThreadState::self();
1181 const int pid = ipc->getCallingPid();
1182 const int uid = ipc->getCallingUid();
1183 if ((uid != AID_SHELL) &&
1184 !PermissionCache::checkPermission(sDump, pid, uid)) {
1185 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1186 return PERMISSION_DENIED;
1187 }
1188
1189 // Try to acquire a lock for 1s, fail gracefully
1190 const status_t err = mStateLock.timedLock(s2ns(1));
1191 const bool locked = (err == NO_ERROR);
1192 if (!locked) {
1193 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1194 return TIMED_OUT;
1195 }
1196
1197 outLayers->clear();
1198 mCurrentState.traverseInZOrder([&](Layer* layer) {
1199 outLayers->push_back(layer->getLayerDebugInfo());
1200 });
1201
1202 mStateLock.unlock();
1203 return NO_ERROR;
1204}
1205
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001206// ----------------------------------------------------------------------------
1207
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001208sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1209 ISurfaceComposer::VsyncSource vsyncSource) {
1210 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1211 return mSFEventThread->createEventConnection();
1212 } else {
1213 return mEventThread->createEventConnection();
1214 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001215}
1216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001218
1219void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001220 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001224 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001232 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001237 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001238 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001242 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001243 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244 if (res == NO_ERROR) {
1245 msg->wait();
1246 }
1247 return res;
1248}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001250void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001251 do {
1252 waitForEvent();
1253 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254}
1255
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256void SurfaceFlinger::enableHardwareVsync() {
1257 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1261 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001263 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264}
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 Mutex::Autolock _l(mHWVsyncLock);
1268
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 if (makeAvailable) {
1270 mHWVsyncAvailable = true;
1271 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001272 // Hardware vsync is not currently available, so abort the resync
1273 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 return;
1275 }
1276
David Sodman105b7dc2017-11-04 20:28:14 -07001277 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001278 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279
1280 mPrimaryDispSync.reset();
1281 mPrimaryDispSync.setPeriod(period);
1282
1283 if (!mPrimaryHWVsyncEnabled) {
1284 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001285 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1286 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 mPrimaryHWVsyncEnabled = true;
1288 }
1289}
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 Mutex::Autolock _l(mHWVsyncLock);
1293 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1295 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryDispSync.endResync();
1297 mPrimaryHWVsyncEnabled = false;
1298 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (makeUnavailable) {
1300 mHWVsyncAvailable = false;
1301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304void SurfaceFlinger::resyncWithRateLimit() {
1305 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001306
1307 // No explicit locking is needed here since EventThread holds a lock while calling this method
1308 static nsecs_t sLastResyncAttempted = 0;
1309 const nsecs_t now = systemTime();
1310 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001311 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312 }
Dan Stoza57164302017-05-08 14:03:54 -07001313 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314}
1315
Steven Thomasb02664d2017-07-26 18:48:28 -07001316void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1317 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 return;
1322 }
1323
1324 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 return;
1327 }
1328
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 { // Scope for the lock
1332 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001336 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001337
1338 if (needsHwVsync) {
1339 enableHardwareVsync();
1340 } else {
1341 disableHardwareVsync(false);
1342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343}
1344
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001345void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001346 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1347 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001348}
1349
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1351 HWC2::Connection connection) {
1352 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1353 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354
Lloyd Piqueba04e622017-12-14 17:11:26 -08001355 // Ignore events that do not have the right sequenceId.
1356 if (sequenceId != getBE().mComposerSequenceId) {
1357 return;
1358 }
1359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Only lock if we're not on the main thread. This function is normally
1361 // called on a hwbinder thread, but for the primary display it's called on
1362 // the main thread with the state lock already held, so don't attempt to
1363 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365
Lloyd Pique715a2c12017-12-14 17:18:08 -08001366 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001367
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001368 if (std::this_thread::get_id() == mMainThreadId) {
1369 // Process all pending hot plug events immediately if we are on the main thread.
1370 processDisplayHotplugEventsLocked();
1371 }
1372
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001374}
1375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::onRefreshReceived(int sequenceId,
1377 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001379 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001382 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001383}
1384
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001386 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 getHwComposer().setVsyncEnabled(disp,
1389 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001390}
1391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001393void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 // Clear the drawing state so that the logic inside of
1396 // handleTransactionLocked will fire. It will determine the delta between
1397 // mCurrentState and mDrawingState and re-apply all changes when we make the
1398 // transition.
1399 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001400 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 mDisplays.clear();
1402}
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404void SurfaceFlinger::updateVrFlinger() {
1405 if (!mVrFlinger)
1406 return;
1407 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 return;
1410 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 ALOGE("Vr flinger is only supported for remote hardware composer"
1414 " service connections. Ignoring request to transition to vr"
1415 " flinger.");
1416 mVrFlingerRequestsDisplay = false;
1417 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 int currentDisplayPowerMode = getDisplayDeviceLocked(
1423 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001430 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001431 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1432 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001433 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434
David Sodman105b7dc2017-11-04 20:28:14 -07001435 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1436 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001437
1438 if (vrFlingerRequestsDisplay) {
1439 mVrFlinger->GrantDisplayOwnership();
1440 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
1444 mVisibleRegionsDirty = true;
1445 invalidateHwcGeometry();
1446
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1449 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1450 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001453 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 const nsecs_t period = activeConfig->getVsyncPeriod();
1455 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Use phase of 0 since phase is not known.
1458 // Use latency of 0, which will snap to the ideal latency.
1459 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001460
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461 android_atomic_or(1, &mRepaintEverything);
1462 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463}
1464
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001466 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001469 bool frameMissed = !mHadClientComposition &&
1470 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001471 (mPreviousPresentFence->getSignalTime() ==
1472 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001473 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001474 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001475 signalLayerUpdate();
1476 break;
1477 }
1478
Steven Thomas050b2c82017-03-06 11:45:16 -08001479 // Now that we're going to make it to the handleMessageTransaction()
1480 // call below it's safe to call updateVrFlinger(), which will
1481 // potentially trigger a display handoff.
1482 updateVrFlinger();
1483
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 bool refreshNeeded = handleMessageTransaction();
1485 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001486 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001488 // Signal a refresh if a transaction modified the window state,
1489 // a new buffer was latched, or if HWC has requested a full
1490 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 signalRefresh();
1492 }
1493 break;
1494 }
1495 case MessageQueue::REFRESH: {
1496 handleMessageRefresh();
1497 break;
1498 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001499 }
1500}
1501
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001503 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001505 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509}
1510
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
1516void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001519 mRefreshPending = false;
1520
Pablo Ceballos40845df2016-01-25 17:41:15 -08001521 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001522
Brian Andersond6927fb2016-07-23 23:37:30 -07001523 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001524 rebuildLayerStacks();
1525 setUpHWComposer();
1526 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001527 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001528 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001529 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001530 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001531
David Sodman105b7dc2017-11-04 20:28:14 -07001532 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001533
1534 mHadClientComposition = false;
1535 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1536 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1537 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001538 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001539 }
Dan Stoza2713c302018-03-28 17:07:36 -07001540 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001541
Dan Stoza9e56aa02015-11-02 13:00:03 -08001542 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001544
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545void SurfaceFlinger::doDebugFlashRegions()
1546{
1547 // is debugging enabled
1548 if (CC_LIKELY(!mDebugRegion))
1549 return;
1550
1551 const bool repaintEverything = mRepaintEverything;
1552 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1553 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001554 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 // transform the dirty region into this screen's coordinate space
1556 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1557 if (!dirtyRegion.isEmpty()) {
1558 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001559 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560
1561 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001563 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001564 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1565
Mathias Agopianda27af92012-09-13 18:17:13 -07001566 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 }
1568 }
1569 }
1570
1571 postFramebuffer();
1572
1573 if (mDebugRegion > 1) {
1574 usleep(mDebugRegion * 1000);
1575 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001576
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001578 auto& displayDevice = mDisplays[displayId];
1579 if (!displayDevice->isDisplayOn()) {
1580 continue;
1581 }
1582
David Sodman105b7dc2017-11-04 20:28:14 -07001583 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1584 ALOGE_IF(result != NO_ERROR,
1585 "prepareFrame for display %zd failed:"
1586 " %d (%s)",
1587 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001588 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589}
1590
Adrian Roos1e1a1282017-11-01 19:05:31 +01001591void SurfaceFlinger::doTracing(const char* where) {
1592 ATRACE_CALL();
1593 ATRACE_NAME(where);
1594 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001595 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001596 }
1597}
1598
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001599void SurfaceFlinger::logLayerStats() {
1600 ATRACE_CALL();
1601 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1602 int32_t hwcId = -1;
1603 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1604 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1605 if (displayDevice->isPrimary()) {
1606 hwcId = displayDevice->getHwcDisplayId();
1607 break;
1608 }
1609 }
1610 if (hwcId < 0) {
1611 ALOGE("LayerStats: Hmmm, no primary display?");
1612 return;
1613 }
1614 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1615 }
1616}
1617
Brian Andersond6927fb2016-07-23 23:37:30 -07001618void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001620 ATRACE_CALL();
1621 ALOGV("preComposition");
1622
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001624 mDrawingState.traverseInZOrder([&](Layer* layer) {
1625 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001626 needExtraInvalidate = true;
1627 }
Robert Carr2047fae2016-11-28 14:09:09 -08001628 });
1629
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630 if (needExtraInvalidate) {
1631 signalLayerUpdate();
1632 }
1633}
1634
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635void SurfaceFlinger::updateCompositorTiming(
1636 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1637 std::shared_ptr<FenceTime>& presentFenceTime) {
1638 // Update queue of past composite+present times and determine the
1639 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001640 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001641 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001642 while (!getBE().mCompositePresentTimes.empty()) {
1643 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001644 // Cached values should have been updated before calling this method,
1645 // which helps avoid duplicate syscalls.
1646 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1647 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1648 break;
1649 }
1650 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001651 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 }
1653
1654 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001655 while (getBE().mCompositePresentTimes.size() > 16) {
1656 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 }
1658
Brian Andersond0010582017-03-07 13:20:31 -08001659 setCompositorTimingSnapped(
1660 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1661}
1662
1663void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1664 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665 // Integer division and modulo round toward 0 not -inf, so we need to
1666 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001667 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1669 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1670
Brian Andersond0010582017-03-07 13:20:31 -08001671 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1672 if (idealLatency <= 0) {
1673 idealLatency = vsyncInterval;
1674 }
1675
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 // Snap the latency to a value that removes scheduling jitter from the
1677 // composition and present times, which often have >1ms of jitter.
1678 // Reducing jitter is important if an app attempts to extrapolate
1679 // something (such as user input) to an accurate diasplay time.
1680 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1681 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001682 nsecs_t bias = vsyncInterval / 2;
1683 int64_t extraVsyncs =
1684 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1685 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1686 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687
David Sodman99974d22017-11-28 12:04:33 -08001688 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1689 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1690 getBE().mCompositorTiming.interval = vsyncInterval;
1691 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692}
1693
1694void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 ATRACE_CALL();
1697 ALOGV("postComposition");
1698
Brian Anderson3546a3f2016-07-14 11:51:14 -07001699 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001700 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001702 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001703 }
1704
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001705 // |mStateLock| not needed as we are on the main thread
1706 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707
David Sodman73beded2017-11-15 11:56:06 -08001708 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001710 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 glCompositionDoneFenceTime =
1712 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001713 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001714 } else {
1715 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1716 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001717
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001719 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001720 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001721 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001723 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1724 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1725
1726 // We use the refreshStartTime which might be sampled a little later than
1727 // when we started doing work for this frame, but that should be okay
1728 // since updateCompositorTiming has snapping logic.
1729 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001730 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001731 CompositorTiming compositorTiming;
1732 {
David Sodman99974d22017-11-28 12:04:33 -08001733 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1734 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001735 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736
Robert Carr2047fae2016-11-28 14:09:09 -08001737 mDrawingState.traverseInZOrder([&](Layer* layer) {
1738 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001739 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001740 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001741 recordBufferingStats(layer->getName().string(),
1742 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001743 }
Robert Carr2047fae2016-11-28 14:09:09 -08001744 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001745
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001746 if (presentFenceTime->isValid()) {
1747 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001748 enableHardwareVsync();
1749 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001750 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001751 }
1752 }
1753
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001754 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001755 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001756 enableHardwareVsync();
1757 }
1758 }
1759
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001760 if (mAnimCompositionPending) {
1761 mAnimCompositionPending = false;
1762
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001765 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001766 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001767 // The HWC doesn't support present fences, so use the refresh
1768 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001769 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001770 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001771 mAnimFrameTracker.setActualPresentTime(presentTime);
1772 }
1773 mAnimFrameTracker.advanceFrame();
1774 }
Dan Stozab90cf072015-03-05 11:05:59 -08001775
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001776 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1777 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001778 return;
1779 }
1780
1781 nsecs_t currentTime = systemTime();
1782 if (mHasPoweredOff) {
1783 mHasPoweredOff = false;
1784 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001785 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001787 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1788 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001789 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001790 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001791 }
David Sodman4a36e932017-11-07 14:29:47 -08001792 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001793 }
David Sodman4a36e932017-11-07 14:29:47 -08001794 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001795}
1796
1797void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001798 ATRACE_CALL();
1799 ALOGV("rebuildLayerStacks");
1800
Mathias Agopiancd60f992012-08-16 16:28:27 -07001801 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001803 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001804 mVisibleRegionsDirty = false;
1805 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001806
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1808 Region opaqueRegion;
1809 Region dirtyRegion;
1810 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001811 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1813 const Transform& tr(displayDevice->getTransform());
1814 const Rect bounds(displayDevice->getBounds());
1815 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001816 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001817
Jeff Sharkey76488112017-02-27 14:15:18 -07001818 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001819 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001820 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1821 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 Region drawRegion(tr.transform(
1823 layer->visibleNonTransparentRegion));
1824 drawRegion.andSelf(bounds);
1825 if (!drawRegion.isEmpty()) {
1826 layersSortedByZ.add(layer);
1827 } else {
1828 // Clear out the HWC layer if this layer was
1829 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001830 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001831 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001832 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001833 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001834 // WM changes displayDevice->layerStack upon sleep/awake.
1835 // Here we make sure we delete the HWC layers even if
1836 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001837 hwcLayerDestroyed = layer->destroyHwcLayer(
1838 displayDevice->getHwcDisplayId());
1839 }
1840
1841 // If a layer is not going to get a release fence because
1842 // it is invisible, but it is also going to release its
1843 // old buffer, add it to the list of layers needing
1844 // fences.
1845 if (hwcLayerDestroyed) {
1846 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1847 mLayersWithQueuedFrames.cend(), layer);
1848 if (found != mLayersWithQueuedFrames.cend()) {
1849 layersNeedingFences.add(layer);
1850 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001851 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001852 });
1853 }
1854 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001855 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001856 displayDevice->undefinedRegion.set(bounds);
1857 displayDevice->undefinedRegion.subtractSelf(
1858 tr.transform(opaqueRegion));
1859 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001860 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001861 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001863
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001864// Returns a dataspace that fits all visible layers. The returned dataspace
1865// can only be one of
1866//
1867// - Dataspace::V0_SRGB
1868// - Dataspace::DISPLAY_P3
1869// - Dataspace::V0_SCRGB_LINEAR
1870// TODO(b/73825729) Add BT2020 data space.
1871ui::Dataspace SurfaceFlinger::getBestDataspace(
1872 const sp<const DisplayDevice>& displayDevice) const {
1873 Dataspace bestDataspace = Dataspace::V0_SRGB;
1874 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1875 switch (layer->getDataSpace()) {
1876 case Dataspace::V0_SCRGB:
1877 case Dataspace::V0_SCRGB_LINEAR:
1878 // return immediately
1879 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001880 case Dataspace::DISPLAY_P3:
1881 bestDataspace = Dataspace::DISPLAY_P3;
1882 break;
1883 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1884 // since SurfaceFlinger simulates HDR support now, it should honor
1885 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886 case Dataspace::BT2020_PQ:
1887 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001888 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001889 return Dataspace::V0_SCRGB_LINEAR;
1890 }
1891 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001892 case Dataspace::BT2020_HLG:
1893 case Dataspace::BT2020_ITU_HLG:
1894 if (!displayDevice->hasHLGSupport()) {
1895 return Dataspace::V0_SCRGB_LINEAR;
1896 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897 break;
1898 default:
1899 break;
1900 }
Romain Guy54f154a2017-10-24 21:40:32 +01001901 }
1902
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001904}
1905
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906// Pick the ColorMode / Dataspace for the display device.
1907// TODO(b/73825729) Add BT2020 color mode.
1908void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1909 ColorMode* outMode, Dataspace* outDataSpace) const {
1910 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1911 *outMode = ColorMode::NATIVE;
1912 *outDataSpace = Dataspace::UNKNOWN;
1913 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001914 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001915
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916 switch (getBestDataspace(displayDevice)) {
1917 case Dataspace::DISPLAY_P3:
1918 case Dataspace::V0_SCRGB_LINEAR:
1919 *outMode = ColorMode::DISPLAY_P3;
1920 *outDataSpace = Dataspace::DISPLAY_P3;
1921 break;
1922 default:
1923 *outMode = ColorMode::SRGB;
1924 *outDataSpace = Dataspace::V0_SRGB;
1925 break;
1926 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001927}
1928
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 ATRACE_CALL();
1931 ALOGV("setUpHWComposer");
1932
Jesse Hall028dc8f2013-08-20 16:35:32 -07001933 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001934 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001935 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1936 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1937
1938 // If nothing has changed (!dirty), don't recompose.
1939 // If something changed, but we don't currently have any visible layers,
1940 // and didn't when we last did a composition, then skip it this time.
1941 // The second rule does two things:
1942 // - When all layers are removed from a display, we'll emit one black
1943 // frame, then nothing more until we get new layers.
1944 // - When a display is created with a private layer stack, we won't
1945 // emit any black frames until a layer is added to the layer stack.
1946 bool mustRecompose = dirty && !(empty && wasEmpty);
1947
1948 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1949 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1950 mustRecompose ? "doing" : "skipping",
1951 dirty ? "+" : "-",
1952 empty ? "+" : "-",
1953 wasEmpty ? "+" : "-");
1954
Dan Stoza71433162014-02-04 16:22:36 -08001955 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001956
1957 if (mustRecompose) {
1958 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1959 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001960 }
1961
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 // build the h/w work list
1963 if (CC_UNLIKELY(mGeometryInvalid)) {
1964 mGeometryInvalid = false;
1965 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1966 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1967 const auto hwcId = displayDevice->getHwcDisplayId();
1968 if (hwcId >= 0) {
1969 const Vector<sp<Layer>>& currentLayers(
1970 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001971 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001972 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001974 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001977 }
1978 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001979
Robert Carrae060832016-11-28 10:51:00 -08001980 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001981 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001983 }
1984 }
1985 }
1986 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001987 }
Riley Andrews03414a12014-07-01 14:22:59 -07001988
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 // Set the per-frame data
1990 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1991 auto& displayDevice = mDisplays[displayId];
1992 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001993
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 if (hwcId < 0) {
1995 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001996 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07001997 if (mDrawingState.colorMatrixChanged) {
1998 displayDevice->setColorTransform(mDrawingState.colorMatrix);
1999 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002000 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2001 "display %zd: %d", displayId, result);
2002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002004 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2005 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002006 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002007 layer->forceClientComposition(hwcId);
2008 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002009 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2010 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2011 !displayDevice->hasHLGSupport()) {
2012 layer->forceClientComposition(hwcId);
2013 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002014
chaviwc9232ed2017-11-14 15:31:15 -08002015 if (layer->getForceClientComposition(hwcId)) {
2016 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2017 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2018 continue;
2019 }
2020
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 layer->setPerFrameData(displayDevice);
2022 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002023
2024 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002025 ColorMode colorMode;
2026 Dataspace dataSpace;
2027 pickColorMode(displayDevice, &colorMode, &dataSpace);
2028 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002029 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 }
2031
Chia-I Wu28f320b2018-05-03 11:02:56 -07002032 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002033
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002035 auto& displayDevice = mDisplays[displayId];
2036 if (!displayDevice->isDisplayOn()) {
2037 continue;
2038 }
2039
David Sodman105b7dc2017-11-04 20:28:14 -07002040 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2042 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002043 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002044}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002045
Mathias Agopiancd60f992012-08-16 16:28:27 -07002046void SurfaceFlinger::doComposition() {
2047 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 ALOGV("doComposition");
2049
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002050 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002051 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002052 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002053 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054 // transform the dirty region into this screen's coordinate space
2055 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002056
2057 // repaint the framebuffer (if needed)
2058 doDisplayComposition(hw, dirtyRegion);
2059
Mathias Agopiancd60f992012-08-16 16:28:27 -07002060 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002061 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002062 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002063 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002064 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002065}
2066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067void SurfaceFlinger::postFramebuffer()
2068{
Mathias Agopian841cde52012-03-01 15:44:37 -08002069 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002071
Mathias Agopiana44b0412011-10-16 18:46:35 -07002072 const nsecs_t now = systemTime();
2073 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002074
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2076 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002077 if (!displayDevice->isDisplayOn()) {
2078 continue;
2079 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 const auto hwcId = displayDevice->getHwcDisplayId();
2081 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002082 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002083 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002084 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002085 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002087 // The layer buffer from the previous frame (if any) is released
2088 // by HWC only when the release fence from this frame (if any) is
2089 // signaled. Always get the release fence from HWC first.
2090 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002091 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002092
2093 // If the layer was client composited in the previous frame, we
2094 // need to merge with the previous client target acquire fence.
2095 // Since we do not track that, always merge with the current
2096 // client target acquire fence when it is available, even though
2097 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002098 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002099 releaseFence = Fence::merge("LayerRelease", releaseFence,
2100 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002101 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002102
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 layer->onLayerDisplayed(releaseFence);
2104 }
Chia-I Wu83806892017-11-16 10:50:20 -08002105
2106 // We've got a list of layers needing fences, that are disjoint with
2107 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2108 // supply them with the present fence.
2109 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002110 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002111 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2112 layer->onLayerDisplayed(presentFence);
2113 }
2114 }
2115
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002117 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002118 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002119 }
2120
Mathias Agopiana44b0412011-10-16 18:46:35 -07002121 mLastSwapBufferTime = systemTime() - now;
2122 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002123
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002124 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002125 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2126 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2127 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2128 logFrameStats();
2129 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002130 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131}
2132
Mathias Agopian87baae12012-07-31 12:38:26 -07002133void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134{
Mathias Agopian841cde52012-03-01 15:44:37 -08002135 ATRACE_CALL();
2136
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002137 // here we keep a copy of the drawing state (that is the state that's
2138 // going to be overwritten by handleTransactionLocked()) outside of
2139 // mStateLock so that the side-effects of the State assignment
2140 // don't happen with mStateLock held (which can cause deadlocks).
2141 State drawingState(mDrawingState);
2142
Mathias Agopianca4d3602011-05-19 15:38:14 -07002143 Mutex::Autolock _l(mStateLock);
2144 const nsecs_t now = systemTime();
2145 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146
Mathias Agopianca4d3602011-05-19 15:38:14 -07002147 // Here we're guaranteed that some transaction flags are set
2148 // so we can call handleTransactionLocked() unconditionally.
2149 // We call getTransactionFlags(), which will also clear the flags,
2150 // with mStateLock held to guarantee that mCurrentState won't change
2151 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002152
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002153 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002155 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002156
Mathias Agopianca4d3602011-05-19 15:38:14 -07002157 mLastTransactionTime = systemTime() - now;
2158 mDebugInTransaction = 0;
2159 invalidateHwcGeometry();
2160 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002161}
2162
Lloyd Pique715a2c12017-12-14 17:18:08 -08002163DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002164 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002165 // Figure out whether the event is for the primary display or an
2166 // external display by matching the Hwc display id against one for a
2167 // connected display. If we did not find a match, we then check what
2168 // displays are not already connected to determine the type. If we don't
2169 // have a connected primary display, we assume the new display is meant to
2170 // be the primary display, and then if we don't have an external display,
2171 // we assume it is that.
2172 const auto primaryDisplayId =
2173 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2174 const auto externalDisplayId =
2175 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2176 if (primaryDisplayId && primaryDisplayId == display) {
2177 return DisplayDevice::DISPLAY_PRIMARY;
2178 } else if (externalDisplayId && externalDisplayId == display) {
2179 return DisplayDevice::DISPLAY_EXTERNAL;
2180 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2181 return DisplayDevice::DISPLAY_PRIMARY;
2182 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2183 return DisplayDevice::DISPLAY_EXTERNAL;
2184 }
2185
2186 return DisplayDevice::DISPLAY_ID_INVALID;
2187}
2188
Lloyd Piqueba04e622017-12-14 17:11:26 -08002189void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2190 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002191 auto displayType = determineDisplayType(event.display, event.connection);
2192 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2193 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2194 continue;
2195 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002196
2197 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2198 ALOGE("External displays are not supported by the vr hardware composer.");
2199 continue;
2200 }
2201
Lloyd Pique715a2c12017-12-14 17:18:08 -08002202 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002203
2204 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002205 if (!mBuiltinDisplays[displayType].get()) {
2206 ALOGV("Creating built in display %d", displayType);
2207 mBuiltinDisplays[displayType] = new BBinder();
2208 // All non-virtual displays are currently considered secure.
2209 DisplayDeviceState info(displayType, true);
2210 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2211 "Built-in Screen" : "External Screen";
2212 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002213 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002214 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002215 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002216 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002217
Lloyd Piquefcd86612017-12-14 17:15:36 -08002218 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2219 if (idx >= 0) {
2220 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002221 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002222 mCurrentState.displays.removeItemsAt(idx);
2223 }
2224 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002225 }
2226
2227 processDisplayChangesLocked();
2228 }
2229
2230 mPendingHotplugEvents.clear();
2231}
2232
Lloyd Pique09594832018-01-22 17:48:03 -08002233sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2234 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2235 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002236 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002237 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002239 for (ColorMode colorMode : modes) {
2240 switch (colorMode) {
2241 case ColorMode::DISPLAY_P3:
2242 case ColorMode::ADOBE_RGB:
2243 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002244 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002245 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002246 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002247 default:
2248 break;
2249 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250
2251 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2252 colorMode);
2253 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2254 for (auto intent : renderIntents) {
2255 if (intent == RenderIntent::ENHANCE) {
2256 mBuiltinDisplaySupportsEnhance = true;
2257 break;
2258 }
2259 }
2260 }
Lloyd Pique09594832018-01-22 17:48:03 -08002261 }
2262 }
2263
Peiyong Lin62665892018-04-16 11:07:44 -07002264 HdrCapabilities hdrCapabilities;
2265 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002266
2267 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2268 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2269
2270 /*
2271 * Create our display's surface
2272 */
2273 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2274 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2275 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2276 renderSurface->setNativeWindow(nativeWindow.get());
2277 const int displayWidth = renderSurface->queryWidth();
2278 const int displayHeight = renderSurface->queryHeight();
2279
2280 // Make sure that composition can never be stalled by a virtual display
2281 // consumer that isn't processing buffers fast enough. We have to do this
2282 // in two places:
2283 // * Here, in case the display is composed entirely by HWC.
2284 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2285 // window's swap interval in eglMakeCurrent, so they'll override the
2286 // interval we set here.
2287 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2288 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2289 }
2290
2291 // virtual displays are always considered enabled
2292 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2293 : HWC_POWER_MODE_OFF;
2294
2295 sp<DisplayDevice> hw =
2296 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2297 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002298 hasWideColorGamut, hdrCapabilities,
2299 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2300 initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002301
2302 if (maxFrameBufferAcquiredBuffers >= 3) {
2303 nativeWindowSurface->preallocateBuffers();
2304 }
2305
2306 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2308 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002309 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002311 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002312 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002313 hw->setLayerStack(state.layerStack);
2314 hw->setProjection(state.orientation, state.viewport, state.frame);
2315 hw->setDisplayName(state.displayName);
2316
2317 return hw;
2318}
2319
Lloyd Pique347200f2017-12-14 17:00:15 -08002320void SurfaceFlinger::processDisplayChangesLocked() {
2321 // here we take advantage of Vector's copy-on-write semantics to
2322 // improve performance by skipping the transaction entirely when
2323 // know that the lists are identical
2324 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2325 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2326 if (!curr.isIdenticalTo(draw)) {
2327 mVisibleRegionsDirty = true;
2328 const size_t cc = curr.size();
2329 size_t dc = draw.size();
2330
2331 // find the displays that were removed
2332 // (ie: in drawing state but not in current state)
2333 // also handle displays that changed
2334 // (ie: displays that are in both lists)
2335 for (size_t i = 0; i < dc;) {
2336 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2337 if (j < 0) {
2338 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002339 // Call makeCurrent() on the primary display so we can
2340 // be sure that nothing associated with this display
2341 // is current.
2342 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2343 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2344 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2345 if (hw != nullptr) hw->disconnect(getHwComposer());
2346 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2347 mEventThread->onHotplugReceived(draw[i].type, false);
2348 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002349 } else {
2350 // this display is in both lists. see if something changed.
2351 const DisplayDeviceState& state(curr[j]);
2352 const wp<IBinder>& display(curr.keyAt(j));
2353 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2354 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2355 if (state_binder != draw_binder) {
2356 // changing the surface is like destroying and
2357 // recreating the DisplayDevice, so we just remove it
2358 // from the drawing state, so that it get re-added
2359 // below.
2360 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2361 if (hw != nullptr) hw->disconnect(getHwComposer());
2362 mDisplays.removeItem(display);
2363 mDrawingState.displays.removeItemsAt(i);
2364 dc--;
2365 // at this point we must loop to the next item
2366 continue;
2367 }
2368
2369 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2370 if (disp != nullptr) {
2371 if (state.layerStack != draw[i].layerStack) {
2372 disp->setLayerStack(state.layerStack);
2373 }
2374 if ((state.orientation != draw[i].orientation) ||
2375 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2376 disp->setProjection(state.orientation, state.viewport, state.frame);
2377 }
2378 if (state.width != draw[i].width || state.height != draw[i].height) {
2379 disp->setDisplaySize(state.width, state.height);
2380 }
2381 }
2382 }
2383 ++i;
2384 }
2385
2386 // find displays that were added
2387 // (ie: in current state but not in drawing state)
2388 for (size_t i = 0; i < cc; i++) {
2389 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2390 const DisplayDeviceState& state(curr[i]);
2391
2392 sp<DisplaySurface> dispSurface;
2393 sp<IGraphicBufferProducer> producer;
2394 sp<IGraphicBufferProducer> bqProducer;
2395 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002396 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002397
2398 int32_t hwcId = -1;
2399 if (state.isVirtualDisplay()) {
2400 // Virtual displays without a surface are dormant:
2401 // they have external state (layer stack, projection,
2402 // etc.) but no internal state (i.e. a DisplayDevice).
2403 if (state.surface != nullptr) {
2404 // Allow VR composer to use virtual displays.
2405 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2406 int width = 0;
2407 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2408 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2409 int height = 0;
2410 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2411 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2412 int intFormat = 0;
2413 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2414 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002415 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416
2417 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2418 }
2419
2420 // TODO: Plumb requested format back up to consumer
2421
2422 sp<VirtualDisplaySurface> vds =
2423 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2424 bqProducer, bqConsumer,
2425 state.displayName);
2426
2427 dispSurface = vds;
2428 producer = vds;
2429 }
2430 } else {
2431 ALOGE_IF(state.surface != nullptr,
2432 "adding a supported display, but rendering "
2433 "surface is provided (%p), ignoring it",
2434 state.surface.get());
2435
2436 hwcId = state.type;
2437 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2438 producer = bqProducer;
2439 }
2440
2441 const wp<IBinder>& display(curr.keyAt(i));
2442 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002443 mDisplays.add(display,
2444 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2445 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002446 if (!state.isVirtualDisplay()) {
2447 mEventThread->onHotplugReceived(state.type, true);
2448 }
2449 }
2450 }
2451 }
2452 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002453
2454 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002455}
2456
Mathias Agopian87baae12012-07-31 12:38:26 -07002457void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002458{
Dan Stoza7dde5992015-05-22 09:51:44 -07002459 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002460 mCurrentState.traverseInZOrder([](Layer* layer) {
2461 layer->notifyAvailableFrames();
2462 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002463
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464 /*
2465 * Traversal of the children
2466 * (perform the transaction for each of them if needed)
2467 */
2468
Mathias Agopian3559b072012-08-15 13:46:03 -07002469 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002470 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002472 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473
2474 const uint32_t flags = layer->doTransaction(0);
2475 if (flags & Layer::eVisibleRegion)
2476 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002477 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 }
2479
2480 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002481 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 */
2483
Mathias Agopiane57f2922012-08-09 16:29:12 -07002484 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002486 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002489 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002490 // The transform hint might have changed for some layers
2491 // (either because a display has changed, or because a layer
2492 // as changed).
2493 //
2494 // Walk through all the layers in currentLayers,
2495 // and update their transform hint.
2496 //
2497 // If a layer is visible only on a single display, then that
2498 // display is used to calculate the hint, otherwise we use the
2499 // default display.
2500 //
2501 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2502 // the hint is set before we acquire a buffer from the surface texture.
2503 //
2504 // NOTE: layer transactions have taken place already, so we use their
2505 // drawing state. However, SurfaceFlinger's own transaction has not
2506 // happened yet, so we must use the current state layer list
2507 // (soon to become the drawing state list).
2508 //
2509 sp<const DisplayDevice> disp;
2510 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002511 bool first = true;
2512 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002513 // NOTE: we rely on the fact that layers are sorted by
2514 // layerStack first (so we don't have to traverse the list
2515 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002516 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002517 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002518 currentlayerStack = layerStack;
2519 // figure out if this layerstack is mirrored
2520 // (more than one display) if so, pick the default display,
2521 // if not, pick the only display it's on.
2522 disp.clear();
2523 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2524 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002525 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002526 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002527 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002528 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002529 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002530 break;
2531 }
2532 }
2533 }
2534 }
Chet Haase91d25932013-04-11 15:24:55 -07002535
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002536 if (disp == nullptr) {
2537 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2538 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002539
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002540 // could be null when this layer is using a layerStack
2541 // that is not visible on any display. Also can occur at
2542 // screen off/on times.
2543 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002544 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002545
2546 // disp can be null if there is no display available at all to get
2547 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002548 if (disp != nullptr) {
2549 layer->updateTransformHint(disp);
2550 }
Robert Carr2047fae2016-11-28 14:09:09 -08002551
2552 first = false;
2553 });
Mathias Agopian84300952012-11-21 16:02:13 -08002554 }
2555
2556
Mathias Agopian3559b072012-08-15 13:46:03 -07002557 /*
2558 * Perform our own transaction if needed
2559 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002560
2561 if (mLayersAdded) {
2562 mLayersAdded = false;
2563 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002564 mVisibleRegionsDirty = true;
2565 }
2566
2567 // some layers might have been removed, so
2568 // we need to update the regions they're exposing.
2569 if (mLayersRemoved) {
2570 mLayersRemoved = false;
2571 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002572 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002574 // this layer is not visible anymore
2575 // TODO: we could traverse the tree from front to back and
2576 // compute the actual visible region
2577 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578 Region visibleReg;
2579 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002580 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002581 }
Robert Carr2047fae2016-11-28 14:09:09 -08002582 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 }
2584
2585 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002586
2587 updateCursorAsync();
2588}
2589
2590void SurfaceFlinger::updateCursorAsync()
2591{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2593 auto& displayDevice = mDisplays[displayId];
2594 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002595 continue;
2596 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002597
2598 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2599 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002600 }
2601 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002602}
2603
2604void SurfaceFlinger::commitTransaction()
2605{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002606 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002607 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002608 for (const auto& l : mLayersPendingRemoval) {
2609 recordBufferingStats(l->getName().string(),
2610 l->getOccupancyHistory(true));
2611 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002612 }
2613 mLayersPendingRemoval.clear();
2614 }
2615
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002616 // If this transaction is part of a window animation then the next frame
2617 // we composite should be considered an animation as well.
2618 mAnimCompositionPending = mAnimTransactionPending;
2619
Mathias Agopian4fec8732012-06-29 14:12:52 -07002620 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002621 // clear the "changed" flags in current state
2622 mCurrentState.colorMatrixChanged = false;
2623
Robert Carr1f0a16a2016-10-24 16:27:39 -07002624 mDrawingState.traverseInZOrder([](Layer* layer) {
2625 layer->commitChildList();
2626 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002627 mTransactionPending = false;
2628 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002629 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630}
2631
Chia-I Wuab0c3192017-08-01 11:29:00 -07002632void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002633 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634{
Mathias Agopian841cde52012-03-01 15:44:37 -08002635 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002636 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638 Region aboveOpaqueLayers;
2639 Region aboveCoveredLayers;
2640 Region dirty;
2641
Mathias Agopian87baae12012-07-31 12:38:26 -07002642 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643
Robert Carr2047fae2016-11-28 14:09:09 -08002644 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002646 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
Jesse Hall01e29052013-02-19 16:13:35 -08002648 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002649 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002650 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002651
Mathias Agopianab028732010-03-16 16:41:46 -07002652 /*
2653 * opaqueRegion: area of a surface that is fully opaque.
2654 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002656
2657 /*
2658 * visibleRegion: area of a surface that is visible on screen
2659 * and not fully transparent. This is essentially the layer's
2660 * footprint minus the opaque regions above it.
2661 * Areas covered by a translucent surface are considered visible.
2662 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002664
2665 /*
2666 * coveredRegion: area of a surface that is covered by all
2667 * visible regions above it (which includes the translucent areas).
2668 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002670
Jesse Halla8026d22012-09-25 13:25:04 -07002671 /*
2672 * transparentRegion: area of a surface that is hinted to be completely
2673 * transparent. This is only used to tell when the layer has no visible
2674 * non-transparent regions and can be removed from the layer list. It
2675 * does not affect the visibleRegion of this layer or any layers
2676 * beneath it. The hint may not be correct if apps don't respect the
2677 * SurfaceView restrictions (which, sadly, some don't).
2678 */
2679 Region transparentRegion;
2680
Mathias Agopianab028732010-03-16 16:41:46 -07002681
2682 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002683 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002684 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002687 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002688 if (!visibleRegion.isEmpty()) {
2689 // Remove the transparent area from the visible region
2690 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002691 if (tr.preserveRects()) {
2692 // transform the transparent region
2693 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002694 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002695 // transformation too complex, can't do the
2696 // transparent region optimization.
2697 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002698 }
Mathias Agopianab028732010-03-16 16:41:46 -07002699 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700
Mathias Agopianab028732010-03-16 16:41:46 -07002701 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002702 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002703 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002704 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2705 // the opaque region is the layer's footprint
2706 opaqueRegion = visibleRegion;
2707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 }
2709 }
2710
Robert Carre5f4f692018-01-12 13:12:28 -08002711 if (visibleRegion.isEmpty()) {
2712 layer->clearVisibilityRegions();
2713 return;
2714 }
2715
Mathias Agopianab028732010-03-16 16:41:46 -07002716 // Clip the covered region to the visible region
2717 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2718
2719 // Update aboveCoveredLayers for next (lower) layer
2720 aboveCoveredLayers.orSelf(visibleRegion);
2721
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 // subtract the opaque region covered by the layers above us
2723 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724
2725 // compute this layer's dirty region
2726 if (layer->contentDirty) {
2727 // we need to invalidate the whole region
2728 dirty = visibleRegion;
2729 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 layer->contentDirty = false;
2732 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002733 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002734 * the exposed region consists of two components:
2735 * 1) what's VISIBLE now and was COVERED before
2736 * 2) what's EXPOSED now less what was EXPOSED before
2737 *
2738 * note that (1) is conservative, we start with the whole
2739 * visible region but only keep what used to be covered by
2740 * something -- which mean it may have been exposed.
2741 *
2742 * (2) handles areas that were not covered by anything but got
2743 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002744 */
Mathias Agopianab028732010-03-16 16:41:46 -07002745 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 const Region oldVisibleRegion = layer->visibleRegion;
2747 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002748 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2749 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 }
2751 dirty.subtractSelf(aboveOpaqueLayers);
2752
2753 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002754 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755
Mathias Agopianab028732010-03-16 16:41:46 -07002756 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002758
Jesse Halla8026d22012-09-25 13:25:04 -07002759 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 layer->setVisibleRegion(visibleRegion);
2761 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002762 layer->setVisibleNonTransparentRegion(
2763 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002764 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765
Mathias Agopian87baae12012-07-31 12:38:26 -07002766 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767}
2768
Chia-I Wuab0c3192017-08-01 11:29:00 -07002769void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002770 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002771 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002772 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002773 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002774 }
2775 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002776}
2777
Dan Stoza6b9454d2014-11-07 16:00:59 -08002778bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 ALOGV("handlePageFlip");
2781
Brian Andersond6927fb2016-07-23 23:37:30 -07002782 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783
Mathias Agopian4fec8732012-06-29 14:12:52 -07002784 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002785 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002786 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002787
2788 // Store the set of layers that need updates. This set must not change as
2789 // buffers are being latched, as this could result in a deadlock.
2790 // Example: Two producers share the same command stream and:
2791 // 1.) Layer 0 is latched
2792 // 2.) Layer 0 gets a new frame
2793 // 2.) Layer 1 gets a new frame
2794 // 3.) Layer 1 is latched.
2795 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2796 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002797 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 if (layer->hasQueuedFrame()) {
2799 frameQueued = true;
2800 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002801 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002802 } else {
2803 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002804 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002805 } else {
2806 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807 }
Robert Carr2047fae2016-11-28 14:09:09 -08002808 });
2809
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002811 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002812 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002813 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002814 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002815 newDataLatched = true;
2816 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002817 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002818
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002819 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820
2821 // If we will need to wake up at some time in the future to deal with a
2822 // queued frame that shouldn't be displayed during this vsync period, wake
2823 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002824 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825 signalLayerUpdate();
2826 }
2827
2828 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002829 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830}
2831
Mathias Agopianad456f92011-01-13 17:53:01 -08002832void SurfaceFlinger::invalidateHwcGeometry()
2833{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002835}
2836
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002837
Fabien Sanglard830b8472016-11-30 16:35:58 -08002838void SurfaceFlinger::doDisplayComposition(
2839 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002840 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841{
Dan Stoza71433162014-02-04 16:22:36 -08002842 // We only need to actually compose the display if:
2843 // 1) It is being handled by hardware composer, which may need this to
2844 // keep its virtual display state machine in sync, or
2845 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002846 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002847 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002849 return;
2850 }
2851
Dan Stoza9e56aa02015-11-02 13:00:03 -08002852 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002853 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002854
2855 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002856 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857}
2858
Chia-I Wub02087d2017-11-09 10:19:54 -08002859bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002860{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002862
Chia-I Wub02087d2017-11-09 10:19:54 -08002863 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002864 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002866 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2867 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2868 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2869 HWC2::Capability::SkipClientColorTransform);
2870 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002871
2872 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002873 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2874 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002875 if (applyColorMatrix) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07002876 oldColorMatrix = getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
2877 legacySrgbSaturationMatrix = mDrawingState.colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002878 }
2879
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 if (hasClientComposition) {
2881 ALOGV("hasClientComposition");
2882
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002883 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002884 if (displayDevice->hasWideColorGamut()) {
2885 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002886 }
2887 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002888 getBE().mRenderEngine->setDisplayMaxLuminance(
2889 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002890
Chia-I Wu7f402902017-11-09 12:51:10 -08002891 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002892 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002894 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002895
2896 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002897 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002898 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2899 }
2900 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002901 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002902
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002903 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002905 // when using overlays, we assume a fully transparent framebuffer
2906 // NOTE: we could reduce how much we need to clear, for instance
2907 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002908 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002909 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002910 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002911 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002912 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002913 // we're left with the letterbox region
2914 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002916
2917 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002919
Mathias Agopianb9494d52012-04-18 02:28:45 -07002920 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002921 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002922 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002925 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002926
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002928 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002929 // scissor on the main display. It should never be needed
2930 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 const Rect& bounds(displayDevice->getBounds());
2932 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002933 if (scissor != bounds) {
2934 // scissor doesn't match the screen's dimensions, so we
2935 // need to clear everything outside of it and enable
2936 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002937
Mathias Agopianf45c5102012-10-24 16:29:17 -07002938 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002940 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002941 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002942 }
2943 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002944 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002945
Mathias Agopian85d751c2012-08-29 16:59:24 -07002946 /*
2947 * and then, render the layers targeted at the framebuffer
2948 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002949
Dan Stoza9e56aa02015-11-02 13:00:03 -08002950 ALOGV("Rendering client layers");
2951 const Transform& displayTransform = displayDevice->getTransform();
2952 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002953 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 bool firstLayer = true;
2955 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002956 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 displayTransform.transform(layer->visibleRegion)));
2958 ALOGV("Layer: %s", layer->getName().string());
2959 ALOGV(" Composition type: %s",
2960 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 switch (layer->getCompositionType(hwcId)) {
2963 case HWC2::Composition::Cursor:
2964 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002965 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002967 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002969 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002971 // never clear the very first layer since we're
2972 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002973 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002974 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002975 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002976 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002978 // Only apply saturation matrix layer that is legacy SRGB dataspace
2979 // when auto color mode is on.
2980 bool restore = false;
2981 mat4 savedMatrix;
2982 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2983 layer->isLegacySrgbDataSpace()) {
2984 savedMatrix =
2985 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
2986 restore = true;
2987 }
chaviwa76b2712017-09-20 12:02:26 -07002988 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002989 if (restore) {
2990 getRenderEngine().setupColorTransform(savedMatrix);
2991 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002992 break;
2993 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002995 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002996 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 } else {
2998 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002999 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003000 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003001 }
3002 } else {
3003 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003004 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003005 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003007 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003008 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003009 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003010 }
3011 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003012
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003013 if (applyColorMatrix) {
3014 getRenderEngine().setupColorTransform(oldColorMatrix);
3015 }
3016
Mathias Agopianf45c5102012-10-24 16:29:17 -07003017 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003018 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003019 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020}
3021
Fabien Sanglard830b8472016-11-30 16:35:58 -08003022void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3023 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003024 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003025 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003026}
3027
Dan Stoza7d89d062015-04-30 13:29:25 -07003028status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003029 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003030 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003031 const sp<Layer>& lbc,
3032 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003033{
Dan Stoza7d89d062015-04-30 13:29:25 -07003034 // add this layer to the current state list
3035 {
3036 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003037 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003038 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3039 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003040 return NO_MEMORY;
3041 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003042 if (parent == nullptr) {
3043 mCurrentState.layersSortedByZ.add(lbc);
3044 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003045 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003046 ALOGE("addClientLayer called with a removed parent");
3047 return NAME_NOT_FOUND;
3048 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003049 parent->addChild(lbc);
3050 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003051
Dan Stoza101d8dc2018-02-27 15:42:25 -08003052 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003053 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3054 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3055 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3056 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3057 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 mLayersAdded = true;
3059 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003060 }
3061
Mathias Agopian96f08192010-06-02 23:28:45 -07003062 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003063 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003064
Dan Stoza7d89d062015-04-30 13:29:25 -07003065 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003066}
3067
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003068status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003069 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003070 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3071}
Robert Carr7f9b8992017-03-10 11:08:39 -08003072
chaviwca27f252018-02-06 16:46:39 -08003073status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3074 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003075 if (layer->isPendingRemoval()) {
3076 return NO_ERROR;
3077 }
3078
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003080 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003081 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003082 if (topLevelOnly) {
3083 return NO_ERROR;
3084 }
3085
Chia-I Wu98f1c102017-05-30 14:54:08 -07003086 sp<Layer> ancestor = p;
3087 while (ancestor->getParent() != nullptr) {
3088 ancestor = ancestor->getParent();
3089 }
3090 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3091 ALOGE("removeLayer called with a layer whose parent has been removed");
3092 return NAME_NOT_FOUND;
3093 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003094
3095 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003096 } else {
3097 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003098 }
3099
Robert Carr136e2f62017-02-08 17:54:29 -08003100 // As a matter of normal operation, the LayerCleaner will produce a second
3101 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3102 // so we will succeed in promoting it, but it's already been removed
3103 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3104 // otherwise something has gone wrong and we are leaking the layer.
3105 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3107 layer->getName().string(),
3108 (p != nullptr) ? p->getName().string() : "no-parent");
3109 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003110 } else if (index < 0) {
3111 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003112 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113
Chia-I Wuc6657022017-08-15 11:18:17 -07003114 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 mLayersPendingRemoval.add(layer);
3116 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003117 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 setTransactionFlags(eTransactionNeeded);
3119 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120}
3121
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003122uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003123 return android_atomic_release_load(&mTransactionFlags);
3124}
3125
Mathias Agopian3f844832013-08-07 21:24:32 -07003126uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3128}
3129
Mathias Agopian3f844832013-08-07 21:24:32 -07003130uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003131 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3132}
3133
3134uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3135 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003137 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003139 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 }
3141 return old;
3142}
3143
chaviwca27f252018-02-06 16:46:39 -08003144bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3145 for (const ComposerState& state : states) {
3146 // Here we need to check that the interface we're given is indeed
3147 // one of our own. A malicious client could give us a nullptr
3148 // IInterface, or one of its own or even one of our own but a
3149 // different type. All these situations would cause us to crash.
3150 if (state.client == nullptr) {
3151 return true;
3152 }
3153
3154 sp<IBinder> binder = IInterface::asBinder(state.client);
3155 if (binder == nullptr) {
3156 return true;
3157 }
3158
3159 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3160 return true;
3161 }
3162 }
3163 return false;
3164}
3165
Mathias Agopian8b33f032012-07-24 20:43:54 -07003166void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003167 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003168 const Vector<DisplayState>& displays,
3169 uint32_t flags)
3170{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003171 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003172 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003173 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003174
chaviwca27f252018-02-06 16:46:39 -08003175 if (containsAnyInvalidClientState(states)) {
3176 return;
3177 }
3178
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003179 if (flags & eAnimation) {
3180 // For window updates that are part of an animation we must wait for
3181 // previous animation "frames" to be handled.
3182 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003183 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003184 if (CC_UNLIKELY(err != NO_ERROR)) {
3185 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 // caller after a few seconds.
3187 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3188 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003189 mAnimTransactionPending = false;
3190 break;
3191 }
3192 }
3193 }
3194
chaviwca27f252018-02-06 16:46:39 -08003195 for (const DisplayState& display : displays) {
3196 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003197 }
3198
chaviwca27f252018-02-06 16:46:39 -08003199 for (const ComposerState& state : states) {
3200 transactionFlags |= setClientStateLocked(state);
3201 }
3202
3203 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3204 // as destroyed should only occur after setting all other states. This is to allow for a
3205 // child re-parent to happen before marking its original parent as destroyed (which would
3206 // then mark the child as destroyed).
3207 for (const ComposerState& state : states) {
3208 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003209 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003210
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003211 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3212 // anyway. This can be used as a flush mechanism for previous async transactions.
3213 // Empty animation transaction can be used to simulate back-pressure, so also force a
3214 // transaction for empty animation transactions.
3215 if (transactionFlags == 0 &&
3216 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003217 transactionFlags = eTransactionNeeded;
3218 }
3219
Mathias Agopian386aa982011-11-07 21:58:03 -08003220 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003221 if (mInterceptor->isEnabled()) {
3222 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003223 }
Irvel468051e2016-06-13 16:44:44 -07003224
Mathias Agopian386aa982011-11-07 21:58:03 -08003225 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003226 const auto start = (flags & eEarlyWakeup)
3227 ? VSyncModulator::TransactionStart::EARLY
3228 : VSyncModulator::TransactionStart::NORMAL;
3229 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003230
3231 // if this is a synchronous transaction, wait for it to take effect
3232 // before returning.
3233 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003234 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003235 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003236 if (flags & eAnimation) {
3237 mAnimTransactionPending = true;
3238 }
3239 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003240 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3241 if (CC_UNLIKELY(err != NO_ERROR)) {
3242 // just in case something goes wrong in SF, return to the
3243 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3245 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003246 break;
3247 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003248 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 }
3250}
3251
Mathias Agopiane57f2922012-08-09 16:29:12 -07003252uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3253{
Jesse Hall9a143922012-10-04 16:29:19 -07003254 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3255 if (dpyIdx < 0)
3256 return 0;
3257
Mathias Agopiane57f2922012-08-09 16:29:12 -07003258 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003259 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003260 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003261 const uint32_t what = s.what;
3262 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003263 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003264 disp.surface = s.surface;
3265 flags |= eDisplayTransactionNeeded;
3266 }
3267 }
3268 if (what & DisplayState::eLayerStackChanged) {
3269 if (disp.layerStack != s.layerStack) {
3270 disp.layerStack = s.layerStack;
3271 flags |= eDisplayTransactionNeeded;
3272 }
3273 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003274 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003275 if (disp.orientation != s.orientation) {
3276 disp.orientation = s.orientation;
3277 flags |= eDisplayTransactionNeeded;
3278 }
3279 if (disp.frame != s.frame) {
3280 disp.frame = s.frame;
3281 flags |= eDisplayTransactionNeeded;
3282 }
3283 if (disp.viewport != s.viewport) {
3284 disp.viewport = s.viewport;
3285 flags |= eDisplayTransactionNeeded;
3286 }
3287 }
Michael Lentine47e45402014-07-18 15:34:25 -07003288 if (what & DisplayState::eDisplaySizeChanged) {
3289 if (disp.width != s.width) {
3290 disp.width = s.width;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 if (disp.height != s.height) {
3294 disp.height = s.height;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 }
3299 return flags;
3300}
3301
chaviwca27f252018-02-06 16:46:39 -08003302uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3303 const layer_state_t& s = composerState.state;
3304 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3305
Mathias Agopian13127d82013-03-05 17:47:11 -08003306 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003307 if (layer == nullptr) {
3308 return 0;
3309 }
3310
3311 if (layer->isPendingRemoval()) {
3312 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3313 return 0;
3314 }
3315
3316 uint32_t flags = 0;
3317
3318 const uint32_t what = s.what;
3319 bool geometryAppliesWithResize =
3320 what & layer_state_t::eGeometryAppliesWithResize;
3321 if (what & layer_state_t::ePositionChanged) {
3322 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3323 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324 }
chaviw8b3871a2017-11-01 17:41:01 -07003325 }
3326 if (what & layer_state_t::eLayerChanged) {
3327 // NOTE: index needs to be calculated before we update the state
3328 const auto& p = layer->getParent();
3329 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003330 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003331 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 mCurrentState.layersSortedByZ.removeAt(idx);
3333 mCurrentState.layersSortedByZ.add(layer);
3334 // we need traversal (state changed)
3335 // AND transaction (list changed)
3336 flags |= eTransactionNeeded|eTraversalNeeded;
3337 }
chaviw8b3871a2017-11-01 17:41:01 -07003338 } else {
3339 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003340 flags |= eTransactionNeeded|eTraversalNeeded;
3341 }
3342 }
chaviw8b3871a2017-11-01 17:41:01 -07003343 }
3344 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003345 // NOTE: index needs to be calculated before we update the state
3346 const auto& p = layer->getParent();
3347 if (p == nullptr) {
3348 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3349 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3350 mCurrentState.layersSortedByZ.removeAt(idx);
3351 mCurrentState.layersSortedByZ.add(layer);
3352 // we need traversal (state changed)
3353 // AND transaction (list changed)
3354 flags |= eTransactionNeeded|eTraversalNeeded;
3355 }
3356 } else {
3357 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3358 flags |= eTransactionNeeded|eTraversalNeeded;
3359 }
chaviw8b3871a2017-11-01 17:41:01 -07003360 }
3361 }
3362 if (what & layer_state_t::eSizeChanged) {
3363 if (layer->setSize(s.w, s.h)) {
3364 flags |= eTraversalNeeded;
3365 }
3366 }
3367 if (what & layer_state_t::eAlphaChanged) {
3368 if (layer->setAlpha(s.alpha))
3369 flags |= eTraversalNeeded;
3370 }
3371 if (what & layer_state_t::eColorChanged) {
3372 if (layer->setColor(s.color))
3373 flags |= eTraversalNeeded;
3374 }
3375 if (what & layer_state_t::eMatrixChanged) {
3376 if (layer->setMatrix(s.matrix))
3377 flags |= eTraversalNeeded;
3378 }
3379 if (what & layer_state_t::eTransparentRegionChanged) {
3380 if (layer->setTransparentRegionHint(s.transparentRegion))
3381 flags |= eTraversalNeeded;
3382 }
3383 if (what & layer_state_t::eFlagsChanged) {
3384 if (layer->setFlags(s.flags, s.mask))
3385 flags |= eTraversalNeeded;
3386 }
3387 if (what & layer_state_t::eCropChanged) {
3388 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3389 flags |= eTraversalNeeded;
3390 }
3391 if (what & layer_state_t::eFinalCropChanged) {
3392 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eLayerStackChanged) {
3396 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3397 // We only allow setting layer stacks for top level layers,
3398 // everything else inherits layer stack from its parent.
3399 if (layer->hasParent()) {
3400 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3401 layer->getName().string());
3402 } else if (idx < 0) {
3403 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3404 "that also does not appear in the top level layer list. Something"
3405 " has gone wrong.", layer->getName().string());
3406 } else if (layer->setLayerStack(s.layerStack)) {
3407 mCurrentState.layersSortedByZ.removeAt(idx);
3408 mCurrentState.layersSortedByZ.add(layer);
3409 // we need traversal (state changed)
3410 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003411 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003412 }
3413 }
3414 if (what & layer_state_t::eDeferTransaction) {
3415 if (s.barrierHandle != nullptr) {
3416 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3417 } else if (s.barrierGbp != nullptr) {
3418 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3419 if (authenticateSurfaceTextureLocked(gbp)) {
3420 const auto& otherLayer =
3421 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3422 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3423 } else {
3424 ALOGE("Attempt to defer transaction to to an"
3425 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003426 }
3427 }
chaviw8b3871a2017-11-01 17:41:01 -07003428 // We don't trigger a traversal here because if no other state is
3429 // changed, we don't want this to cause any more work
3430 }
3431 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003432 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003433 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003434 if (!hadParent) {
3435 mCurrentState.layersSortedByZ.remove(layer);
3436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 }
3440 if (what & layer_state_t::eReparentChildren) {
3441 if (layer->reparentChildren(s.reparentHandle)) {
3442 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003443 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 if (what & layer_state_t::eDetachChildren) {
3446 layer->detachChildren();
3447 }
3448 if (what & layer_state_t::eOverrideScalingModeChanged) {
3449 layer->setOverrideScalingMode(s.overrideScalingMode);
3450 // We don't trigger a traversal here because if no other state is
3451 // changed, we don't want this to cause any more work
3452 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 return flags;
3454}
3455
chaviwca27f252018-02-06 16:46:39 -08003456void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3457 const layer_state_t& state = composerState.state;
3458 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3459
3460 sp<Layer> layer(client->getLayerUser(state.surface));
3461 if (layer == nullptr) {
3462 return;
3463 }
3464
3465 if (layer->isPendingRemoval()) {
3466 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3467 return;
3468 }
3469
3470 if (state.what & layer_state_t::eDestroySurface) {
3471 removeLayerLocked(mStateLock, layer);
3472 }
3473}
3474
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003475status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003476 const String8& name,
3477 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003478 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003479 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003480 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003481{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003482 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003483 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003484 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003485 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003486 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003487
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003488 status_t result = NO_ERROR;
3489
3490 sp<Layer> layer;
3491
Cody Northropbc755282017-03-31 12:00:08 -06003492 String8 uniqueName = getUniqueLayerName(name);
3493
Mathias Agopian3165cc22012-08-08 19:42:09 -07003494 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3495 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003496 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003497 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003499
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500 break;
chaviw13fdc492017-06-27 12:40:18 -07003501 case ISurfaceComposerClient::eFXSurfaceColor:
3502 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003503 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003504 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003505 break;
3506 default:
3507 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 break;
3509 }
3510
Dan Stoza7d89d062015-04-30 13:29:25 -07003511 if (result != NO_ERROR) {
3512 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003514
Chia-I Wuab0c3192017-08-01 11:29:00 -07003515 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3516 // TODO b/64227542
3517 if (windowType == 441731) {
3518 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3519 layer->setPrimaryDisplayOnly();
3520 }
3521
Albert Chaulk479c60c2017-01-27 14:21:34 -05003522 layer->setInfo(windowType, ownerUid);
3523
Robert Carr1f0a16a2016-10-24 16:27:39 -07003524 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003525 if (result != NO_ERROR) {
3526 return result;
3527 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003528 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003529
3530 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003531 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532}
3533
Cody Northropbc755282017-03-31 12:00:08 -06003534String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3535{
3536 bool matchFound = true;
3537 uint32_t dupeCounter = 0;
3538
3539 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3540 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3541
3542 // Loop over layers until we're sure there is no matching name
3543 while (matchFound) {
3544 matchFound = false;
3545 mDrawingState.traverseInZOrder([&](Layer* layer) {
3546 if (layer->getName() == uniqueName) {
3547 matchFound = true;
3548 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3549 }
3550 });
3551 }
3552
3553 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3554
3555 return uniqueName;
3556}
3557
David Sodman0c69cad2017-08-21 12:12:51 -07003558status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003559 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3560 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561{
3562 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003563 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564 case PIXEL_FORMAT_TRANSPARENT:
3565 case PIXEL_FORMAT_TRANSLUCENT:
3566 format = PIXEL_FORMAT_RGBA_8888;
3567 break;
3568 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003569 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 break;
3571 }
3572
David Sodman0c69cad2017-08-21 12:12:51 -07003573 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3574 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003575 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003576 *handle = layer->getHandle();
3577 *gbp = layer->getProducer();
3578 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003580
David Sodman0c69cad2017-08-21 12:12:51 -07003581 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003582 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583}
3584
chaviw13fdc492017-06-27 12:40:18 -07003585status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003586 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003587 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588{
chaviw13fdc492017-06-27 12:40:18 -07003589 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003592}
3593
Mathias Agopianac9fa422013-02-11 16:40:36 -08003594status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595{
Robert Carr9524cb32017-02-13 11:32:32 -08003596 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003597 status_t err = NO_ERROR;
3598 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003599 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003600 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003601 err = removeLayer(l);
3602 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3603 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003604 }
3605 return err;
3606}
3607
Mathias Agopian13127d82013-03-05 17:47:11 -08003608status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003609{
Mathias Agopian67106042013-03-14 19:18:13 -07003610 // called by ~LayerCleaner() when all references to the IBinder (handle)
3611 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003612 sp<Layer> l = layer.promote();
3613 if (l == nullptr) {
3614 // The layer has already been removed, carry on
3615 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003616 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003617 // If we have a parent, then we can continue to live as long as it does.
3618 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619}
3620
Mathias Agopianb60314a2012-04-10 22:09:54 -07003621// ---------------------------------------------------------------------------
3622
Andy McFadden13a082e2012-08-24 10:16:42 -07003623void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003624 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003625 Vector<ComposerState> state;
3626 Vector<DisplayState> displays;
3627 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003628 d.what = DisplayState::eDisplayProjectionChanged |
3629 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003630 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003631 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003632 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003633 d.frame.makeInvalid();
3634 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003635 d.width = 0;
3636 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003637 displays.add(d);
3638 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003639 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3640 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003641
David Sodman105b7dc2017-11-04 20:28:14 -07003642 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003643 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003644 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003645
Brian Andersond0010582017-03-07 13:20:31 -08003646 // Use phase of 0 since phase is not known.
3647 // Use latency of 0, which will snap to the ideal latency.
3648 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003649}
3650
3651void SurfaceFlinger::initializeDisplays() {
3652 class MessageScreenInitialized : public MessageBase {
3653 SurfaceFlinger* flinger;
3654 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003655 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003656 virtual bool handler() {
3657 flinger->onInitializeDisplays();
3658 return true;
3659 }
3660 };
3661 sp<MessageBase> msg = new MessageScreenInitialized(this);
3662 postMessageAsync(msg); // we may be called from main thread, use async message
3663}
3664
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003665void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003666 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003667 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3668 this);
3669 int32_t type = hw->getDisplayType();
3670 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003671
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003672 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003673 return;
3674 }
3675
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003676 hw->setPowerMode(mode);
3677 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3678 ALOGW("Trying to set power mode for virtual display");
3679 return;
3680 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003681
Lloyd Pique4d234852018-01-22 17:21:36 -08003682 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003683 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003684 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3685 if (idx < 0) {
3686 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3687 return;
3688 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003689 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003690 }
3691
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003692 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003693 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003694 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003695 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3696 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003697 // FIXME: eventthread only knows about the main display right now
3698 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003699 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003703 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003704 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003705
3706 struct sched_param param = {0};
3707 param.sched_priority = 1;
3708 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3709 ALOGW("Couldn't set SCHED_FIFO on display on");
3710 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003712 // Turn off the display
3713 struct sched_param param = {0};
3714 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3715 ALOGW("Couldn't set SCHED_OTHER on display off");
3716 }
3717
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003718 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3719 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003720 disableHardwareVsync(true); // also cancels any in-progress resync
3721
Mathias Agopiancde87a32012-09-13 14:09:01 -07003722 // FIXME: eventthread only knows about the main display right now
3723 mEventThread->onScreenReleased();
3724 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 getHwComposer().setPowerMode(type, mode);
3727 mVisibleRegionsDirty = true;
3728 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003729 } else if (mode == HWC_POWER_MODE_DOZE ||
3730 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003731 // Update display while dozing
3732 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003733 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3734 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003735 // FIXME: eventthread only knows about the main display right now
3736 mEventThread->onScreenAcquired();
3737 resyncToHardwareVsync(true);
3738 }
3739 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3740 // Leave display going to doze
3741 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3742 disableHardwareVsync(true); // also cancels any in-progress resync
3743 // FIXME: eventthread only knows about the main display right now
3744 mEventThread->onScreenReleased();
3745 }
3746 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003747 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003748 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003750 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003751 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752}
3753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3755 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003756 SurfaceFlinger& mFlinger;
3757 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003760 MessageSetPowerMode(SurfaceFlinger& flinger,
3761 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3762 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003763 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003765 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003767 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003768 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 ALOGW("Attempt to set power mode = %d for virtual display",
3770 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003771 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003772 mFlinger.setPowerModeInternal(
3773 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003774 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775 return true;
3776 }
3777 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003779 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003780}
3781
3782// ---------------------------------------------------------------------------
3783
Lloyd Pique755e3192018-01-31 16:46:15 -08003784status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3785 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003787
Mathias Agopianbd115332013-04-18 16:41:04 -07003788 IPCThreadState* ipc = IPCThreadState::self();
3789 const int pid = ipc->getCallingPid();
3790 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003791
Mathias Agopianbd115332013-04-18 16:41:04 -07003792 if ((uid != AID_SHELL) &&
3793 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003794 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003795 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003797 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003798 // (this would indicate SF is stuck, but we want to be able to
3799 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003800 status_t err = mStateLock.timedLock(s2ns(1));
3801 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003802 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003803 result.appendFormat(
3804 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3805 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003806 }
3807
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003808 bool dumpAll = true;
3809 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003810 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003811
3812 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003813 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003814 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3815 dumpAll = false;
3816 }
3817
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003819 if ((index < numArgs) &&
3820 (args[index] == String16("--list"))) {
3821 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003822 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003823 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003824 }
3825
3826 if ((index < numArgs) &&
3827 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003828 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003829 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003830 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003832
3833 if ((index < numArgs) &&
3834 (args[index] == String16("--latency-clear"))) {
3835 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003836 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003837 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003838 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003839
3840 if ((index < numArgs) &&
3841 (args[index] == String16("--dispsync"))) {
3842 index++;
3843 mPrimaryDispSync.dump(result);
3844 dumpAll = false;
3845 }
Dan Stozab90cf072015-03-05 11:05:59 -08003846
3847 if ((index < numArgs) &&
3848 (args[index] == String16("--static-screen"))) {
3849 index++;
3850 dumpStaticScreenStats(result);
3851 dumpAll = false;
3852 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003853
3854 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003855 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003856 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003857 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003858 dumpAll = false;
3859 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003860
3861 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3862 index++;
3863 dumpWideColorInfo(result);
3864 dumpAll = false;
3865 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003866
3867 if ((index < numArgs) &&
3868 (args[index] == String16("--enable-layer-stats"))) {
3869 index++;
3870 mLayerStats.enable();
3871 dumpAll = false;
3872 }
3873
3874 if ((index < numArgs) &&
3875 (args[index] == String16("--disable-layer-stats"))) {
3876 index++;
3877 mLayerStats.disable();
3878 dumpAll = false;
3879 }
3880
3881 if ((index < numArgs) &&
3882 (args[index] == String16("--clear-layer-stats"))) {
3883 index++;
3884 mLayerStats.clear();
3885 dumpAll = false;
3886 }
3887
3888 if ((index < numArgs) &&
3889 (args[index] == String16("--dump-layer-stats"))) {
3890 index++;
3891 mLayerStats.dump(result);
3892 dumpAll = false;
3893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003895
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003896 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003897 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003898 }
3899
Mathias Agopian9795c422009-08-26 16:36:26 -07003900 if (locked) {
3901 mStateLock.unlock();
3902 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 }
3904 write(fd, result.string(), result.size());
3905 return NO_ERROR;
3906}
3907
Dan Stozac7014012014-02-14 15:03:43 -08003908void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3909 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003910{
Robert Carr2047fae2016-11-28 14:09:09 -08003911 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003912 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003913 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003914}
3915
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003916void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918{
3919 String8 name;
3920 if (index < args.size()) {
3921 name = String8(args[index]);
3922 index++;
3923 }
3924
David Sodman105b7dc2017-11-04 20:28:14 -07003925 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003926 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003927 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003928
3929 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003930 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003931 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003932 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003933 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003934 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003935 }
Robert Carr2047fae2016-11-28 14:09:09 -08003936 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003937 }
3938}
3939
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003940void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003941 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003942{
3943 String8 name;
3944 if (index < args.size()) {
3945 name = String8(args[index]);
3946 index++;
3947 }
3948
Robert Carr2047fae2016-11-28 14:09:09 -08003949 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003950 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003951 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003952 }
Robert Carr2047fae2016-11-28 14:09:09 -08003953 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003954
Svetoslavd85084b2014-03-20 10:28:31 -07003955 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003956}
3957
Jamie Gennis6547ff42013-07-16 20:12:42 -07003958// This should only be called from the main thread. Otherwise it would need
3959// the lock and should use mCurrentState rather than mDrawingState.
3960void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003961 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003962 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003963 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003964
3965 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3966}
3967
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003968void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003969{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003970 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003971
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003972 if (isLayerTripleBufferingDisabled())
3973 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003974
3975 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003976 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003977 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003978 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003979 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3980 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003981 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003982}
3983
Dan Stozab90cf072015-03-05 11:05:59 -08003984void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3985{
3986 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003987 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3988 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003989 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003990 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003991 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3992 b + 1, bucketTimeSec, percent);
3993 }
David Sodman4a36e932017-11-07 14:29:47 -08003994 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003995 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003996 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003997 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003998 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003999}
4000
Dan Stozae77c7662016-05-13 11:37:28 -07004001void SurfaceFlinger::recordBufferingStats(const char* layerName,
4002 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004003 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4004 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004005 for (const auto& segment : history) {
4006 if (!segment.usedThirdBuffer) {
4007 stats.twoBufferTime += segment.totalTime;
4008 }
4009 if (segment.occupancyAverage < 1.0f) {
4010 stats.doubleBufferedTime += segment.totalTime;
4011 } else if (segment.occupancyAverage < 2.0f) {
4012 stats.tripleBufferedTime += segment.totalTime;
4013 }
4014 ++stats.numSegments;
4015 stats.totalTime += segment.totalTime;
4016 }
4017}
4018
Brian Andersond6927fb2016-07-23 23:37:30 -07004019void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4020 result.appendFormat("Layer frame timestamps:\n");
4021
4022 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4023 const size_t count = currentLayers.size();
4024 for (size_t i=0 ; i<count ; i++) {
4025 currentLayers[i]->dumpFrameEvents(result);
4026 }
4027}
4028
Dan Stozae77c7662016-05-13 11:37:28 -07004029void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4030 result.append("Buffering stats:\n");
4031 result.append(" [Layer name] <Active time> <Two buffer> "
4032 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004033 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004034 typedef std::tuple<std::string, float, float, float> BufferTuple;
4035 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004036 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004037 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004038 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004039 if (stats.numSegments == 0) {
4040 continue;
4041 }
4042 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4043 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4044 stats.totalTime;
4045 float doubleBufferRatio = static_cast<float>(
4046 stats.doubleBufferedTime) / stats.totalTime;
4047 float tripleBufferRatio = static_cast<float>(
4048 stats.tripleBufferedTime) / stats.totalTime;
4049 sorted.insert({activeTime, {name, twoBufferRatio,
4050 doubleBufferRatio, tripleBufferRatio}});
4051 }
4052 for (const auto& sortedPair : sorted) {
4053 float activeTime = sortedPair.first;
4054 const BufferTuple& values = sortedPair.second;
4055 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4056 std::get<0>(values).c_str(), activeTime,
4057 std::get<1>(values), std::get<2>(values),
4058 std::get<3>(values));
4059 }
4060 result.append("\n");
4061}
4062
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004063void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4064 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004065 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004066
4067 // TODO: print out if wide-color mode is active or not
4068
4069 for (size_t d = 0; d < mDisplays.size(); d++) {
4070 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4071 int32_t hwcId = displayDevice->getHwcDisplayId();
4072 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4073 continue;
4074 }
4075
4076 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004077 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004078 for (auto&& mode : modes) {
4079 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4080 }
4081
Peiyong Lina52f0292018-03-14 17:26:31 -07004082 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004083 result.appendFormat(" Current color mode: %s (%d)\n",
4084 decodeColorMode(currentMode).c_str(), currentMode);
4085 }
4086 result.append("\n");
4087}
4088
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004089LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004090 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004091 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4092 const State& state = useDrawing ? mDrawingState : mCurrentState;
4093 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004094 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004095 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004096 });
4097
4098 return layersProto;
4099}
4100
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004101LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4102 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004103 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004104
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004105 SizeProto* resolution = layersProto.mutable_resolution();
4106 resolution->set_w(displayDevice->getWidth());
4107 resolution->set_h(displayDevice->getHeight());
4108
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004109 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4110 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4111 layersProto.set_global_transform(
4112 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4113
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004114 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004115 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004116 LayerProto* layerProto = layersProto.add_layers();
4117 layer->writeToProto(layerProto, hwcId);
4118 }
4119 });
4120
4121 return layersProto;
4122}
4123
Mathias Agopian74d211a2013-04-22 16:55:35 +02004124void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4125 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004126{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004127 bool colorize = false;
4128 if (index < args.size()
4129 && (args[index] == String16("--color"))) {
4130 colorize = true;
4131 index++;
4132 }
4133
4134 Colorizer colorizer(colorize);
4135
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136 // figure out if we're stuck somewhere
4137 const nsecs_t now = systemTime();
4138 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4139 const nsecs_t inTransaction(mDebugInTransaction);
4140 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4141 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4142
4143 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004144 * Dump library configuration.
4145 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004146
4147 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004148 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004149 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004150 appendSfConfigString(result);
4151 appendUiConfigString(result);
4152 appendGuiConfigString(result);
4153 result.append("\n");
4154
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004155 result.append("\nWide-Color information:\n");
4156 dumpWideColorInfo(result);
4157
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004158 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004159 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004160 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004161 result.append(SyncFeatures::getInstance().toString());
4162 result.append("\n");
4163
David Sodman105b7dc2017-11-04 20:28:14 -07004164 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004165
Andy McFadden41d67d72014-04-25 16:58:34 -07004166 colorizer.bold(result);
4167 result.append("DispSync configuration: ");
4168 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004169 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4170 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4171 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004172 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004173 result.append("\n");
4174
Dan Stozab90cf072015-03-05 11:05:59 -08004175 // Dump static screen stats
4176 result.append("\n");
4177 dumpStaticScreenStats(result);
4178 result.append("\n");
4179
Dan Stozae77c7662016-05-13 11:37:28 -07004180 dumpBufferingStats(result);
4181
Andy McFadden4803b742012-09-24 19:07:20 -07004182 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004183 * Dump the visible layer list
4184 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004185 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004186 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004187 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4188 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004189 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004190
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004191 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004192 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004193 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004194 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004195
4196 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004197 * Dump Display state
4198 */
4199
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004201 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004203 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4204 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004205 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004206 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004207 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004208
4209 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004210 * Dump SurfaceFlinger global state
4211 */
4212
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004214 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004216
Mathias Agopian888c8222012-08-04 21:10:38 -07004217 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004218 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004219
David Sodmanbc815282017-11-05 18:57:52 -08004220 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004221
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004222 if (hw) {
4223 hw->undefinedRegion.dump(result, "undefinedRegion");
4224 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4225 hw->getOrientation(), hw->isDisplayOn());
4226 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004227 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228 " last eglSwapBuffers() time: %f us\n"
4229 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004230 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231 " refresh-rate : %f fps\n"
4232 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004233 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004234 " gpu_to_cpu_unsupported : %d\n"
4235 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004236 mLastSwapBufferTime/1000.0,
4237 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004238 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004239 1e9 / activeConfig->getVsyncPeriod(),
4240 activeConfig->getDpiX(),
4241 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004242 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004243
Mathias Agopian74d211a2013-04-22 16:55:35 +02004244 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246
Mathias Agopian74d211a2013-04-22 16:55:35 +02004247 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249
4250 /*
4251 * VSYNC state
4252 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004253 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004254 result.append("\n");
4255
4256 /*
4257 * HWC layer minidump
4258 */
4259 for (size_t d = 0; d < mDisplays.size(); d++) {
4260 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4261 int32_t hwcId = displayDevice->getHwcDisplayId();
4262 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4263 continue;
4264 }
4265
4266 result.appendFormat("Display %d HWC layers:\n", hwcId);
4267 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004268 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004269 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004270 });
Dan Stozae22aec72016-08-01 13:20:59 -07004271 result.append("\n");
4272 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004273
4274 /*
4275 * Dump HWComposer state
4276 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004278 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004279 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004280 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004281 result.appendFormat(" h/w composer %s\n",
4282 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004283 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
4286 * Dump gralloc state
4287 */
4288 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4289 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004290
4291 /*
4292 * Dump VrFlinger state if in use.
4293 */
4294 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4295 result.append("VrFlinger state:\n");
4296 result.append(mVrFlinger->Dump().c_str());
4297 result.append("\n");
4298 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299}
4300
Mathias Agopian13127d82013-03-05 17:47:11 -08004301const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004302SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004303 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004304 wp<IBinder> dpy;
4305 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4306 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4307 dpy = mDisplays.keyAt(i);
4308 break;
4309 }
4310 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004311 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004312 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4313 // Just use the primary display so we have something to return
4314 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4315 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004316 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004317}
4318
Keun young Park63f165f2012-08-31 10:53:36 -07004319bool SurfaceFlinger::startDdmConnection()
4320{
4321 void* libddmconnection_dso =
4322 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4323 if (!libddmconnection_dso) {
4324 return false;
4325 }
4326 void (*DdmConnection_start)(const char* name);
4327 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004328 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004329 if (!DdmConnection_start) {
4330 dlclose(libddmconnection_dso);
4331 return false;
4332 }
4333 (*DdmConnection_start)(getServiceName());
4334 return true;
4335}
4336
Chia-I Wu28f320b2018-05-03 11:02:56 -07004337void SurfaceFlinger::updateColorMatrixLocked() {
4338 mat4 colorMatrix;
4339 if (mGlobalSaturationFactor != 1.0f) {
4340 // Rec.709 luma coefficients
4341 float3 luminance{0.213f, 0.715f, 0.072f};
4342 luminance *= 1.0f - mGlobalSaturationFactor;
4343 mat4 saturationMatrix = mat4(
4344 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4345 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4346 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4347 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4348 );
4349 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4350 } else {
4351 colorMatrix = mClientColorMatrix * mDaltonizer();
4352 }
4353
4354 if (mCurrentState.colorMatrix != colorMatrix) {
4355 mCurrentState.colorMatrix = colorMatrix;
4356 mCurrentState.colorMatrixChanged = true;
4357 setTransactionFlags(eTransactionNeeded);
4358 }
4359}
4360
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004361status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 switch (code) {
4363 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004364 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004366 case CLEAR_ANIMATION_FRAME_STATS:
4367 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004368 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004369 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004370 case ENABLE_VSYNC_INJECTIONS:
4371 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 {
4373 // codes that require permission check
4374 IPCThreadState* ipc = IPCThreadState::self();
4375 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004376 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004377 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004378 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004379 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004380 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004382 break;
4383 }
Robert Carr1db73f62016-12-21 12:58:51 -08004384 /*
4385 * Calling setTransactionState is safe, because you need to have been
4386 * granted a reference to Client* and Handle* to do anything with it.
4387 *
4388 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4389 */
4390 case SET_TRANSACTION_STATE:
4391 case CREATE_SCOPED_CONNECTION:
4392 {
4393 return OK;
4394 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004395 case CAPTURE_SCREEN:
4396 {
4397 // codes that require permission check
4398 IPCThreadState* ipc = IPCThreadState::self();
4399 const int pid = ipc->getCallingPid();
4400 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004401 if ((uid != AID_GRAPHICS) &&
4402 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004403 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004404 return PERMISSION_DENIED;
4405 }
4406 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004407 }
chaviwa76b2712017-09-20 12:02:26 -07004408 case CAPTURE_LAYERS: {
4409 IPCThreadState* ipc = IPCThreadState::self();
4410 const int pid = ipc->getCallingPid();
4411 const int uid = ipc->getCallingUid();
4412 if ((uid != AID_GRAPHICS) &&
4413 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4414 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4415 return PERMISSION_DENIED;
4416 }
4417 break;
4418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004420 return OK;
4421}
4422
4423status_t SurfaceFlinger::onTransact(
4424 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4425{
4426 status_t credentialCheck = CheckTransactCodeCredentials(code);
4427 if (credentialCheck != OK) {
4428 return credentialCheck;
4429 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4432 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004433 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004434 IPCThreadState* ipc = IPCThreadState::self();
4435 const int uid = ipc->getCallingUid();
4436 if (CC_UNLIKELY(uid != AID_SYSTEM
4437 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004438 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004439 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004440 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 return PERMISSION_DENIED;
4442 }
4443 int n;
4444 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004445 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004446 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return NO_ERROR;
4448 case 1002: // SHOW_UPDATES
4449 n = data.readInt32();
4450 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004451 invalidateHwcGeometry();
4452 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004455 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004456 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004457 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004458 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004459 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004460 setTransactionFlags(
4461 eTransactionNeeded|
4462 eDisplayTransactionNeeded|
4463 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004464 return NO_ERROR;
4465 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004466 case 1006:{ // send empty update
4467 signalRefresh();
4468 return NO_ERROR;
4469 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004470 case 1008: // toggle use of hw composer
4471 n = data.readInt32();
4472 mDebugDisableHWC = n ? 1 : 0;
4473 invalidateHwcGeometry();
4474 repaintEverything();
4475 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004476 case 1009: // toggle use of transform hint
4477 n = data.readInt32();
4478 mDebugDisableTransformHint = n ? 1 : 0;
4479 invalidateHwcGeometry();
4480 repaintEverything();
4481 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004482 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004483 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 reply->writeInt32(0);
4485 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004486 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004487 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004488 return NO_ERROR;
4489 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004490 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004491 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004492 return NO_ERROR;
4493 }
4494 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004495 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004496 // daltonize
4497 n = data.readInt32();
4498 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004499 case 1:
4500 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4501 break;
4502 case 2:
4503 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4504 break;
4505 case 3:
4506 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4507 break;
4508 default:
4509 mDaltonizer.setType(ColorBlindnessType::None);
4510 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004511 }
4512 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004513 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004514 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004515 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004516 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004517
4518 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004519 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004521 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004522 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004523 // apply a color matrix
4524 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004525 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004526 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004527 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004528 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004529 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004530 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004531 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004533 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004534 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004535
4536 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4537 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004538 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004539 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4540 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4541 }
4542
Chia-I Wu28f320b2018-05-03 11:02:56 -07004543 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004544 return NO_ERROR;
4545 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004546 // This is an experimental interface
4547 // Needs to be shifted to proper binder interface when we productize
4548 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004549 n = data.readInt32();
4550 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004551 return NO_ERROR;
4552 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004553 case 1017: {
4554 n = data.readInt32();
4555 mForceFullDamage = static_cast<bool>(n);
4556 return NO_ERROR;
4557 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004558 case 1018: { // Modify Choreographer's phase offset
4559 n = data.readInt32();
4560 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4561 return NO_ERROR;
4562 }
4563 case 1019: { // Modify SurfaceFlinger's phase offset
4564 n = data.readInt32();
4565 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4566 return NO_ERROR;
4567 }
Irvel468051e2016-06-13 16:44:44 -07004568 case 1020: { // Layer updates interceptor
4569 n = data.readInt32();
4570 if (n) {
4571 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004572 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004573 }
4574 else{
4575 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004576 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004577 }
4578 return NO_ERROR;
4579 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004580 case 1021: { // Disable HWC virtual displays
4581 n = data.readInt32();
4582 mUseHwcVirtualDisplays = !n;
4583 return NO_ERROR;
4584 }
Romain Guy0147a172017-06-01 13:53:56 -07004585 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004586 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004587 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004588
Chia-I Wu28f320b2018-05-03 11:02:56 -07004589 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004590 return NO_ERROR;
4591 }
Romain Guy54f154a2017-10-24 21:40:32 +01004592 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004593 int32_t value = data.readInt32();
4594 if (value > 2) {
4595 return BAD_VALUE;
4596 }
4597 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4598 return BAD_VALUE;
4599 }
Romain Guy54f154a2017-10-24 21:40:32 +01004600
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004601 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004602 invalidateHwcGeometry();
4603 repaintEverything();
4604 return NO_ERROR;
4605 }
4606 case 1024: { // Is wide color gamut rendering/color management supported?
4607 reply->writeBool(hasWideColorDisplay);
4608 return NO_ERROR;
4609 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004610 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004611 n = data.readInt32();
4612 if (n) {
4613 ALOGV("LayerTracing enabled");
4614 mTracing.enable();
4615 doTracing("tracing.enable");
4616 reply->writeInt32(NO_ERROR);
4617 } else {
4618 ALOGV("LayerTracing disabled");
4619 status_t err = mTracing.disable();
4620 reply->writeInt32(err);
4621 }
4622 return NO_ERROR;
4623 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004624 case 1026: { // Get layer tracing status
4625 reply->writeBool(mTracing.isEnabled());
4626 return NO_ERROR;
4627 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004628 // Is a DisplayColorSetting supported?
4629 case 1027: {
4630 int32_t value = data.readInt32();
4631 switch (value) {
4632 case 0:
4633 reply->writeBool(hasWideColorDisplay);
4634 return NO_ERROR;
4635 case 1:
4636 reply->writeBool(true);
4637 return NO_ERROR;
4638 case 2:
4639 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4640 return NO_ERROR;
4641 default:
4642 return BAD_VALUE;
4643 }
4644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004645 }
4646 }
4647 return err;
4648}
4649
Steven Thomas6d8110b2017-08-31 18:24:21 -07004650void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004651 android_atomic_or(1, &mRepaintEverything);
4652 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004653}
4654
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004655// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4656class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004657public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004658 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4659 ~WindowDisconnector() {
4660 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004661 }
4662
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663private:
4664 ANativeWindow* mWindow;
4665 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004666};
4667
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004668status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4669 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4670 int32_t minLayerZ, int32_t maxLayerZ,
4671 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004672 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004673 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004674
chaviwa76b2712017-09-20 12:02:26 -07004675 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4676
4677 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004678 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4679
chaviwa76b2712017-09-20 12:02:26 -07004680 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4681
4682 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4683 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004684 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004685}
4686
4687status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004688 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004689 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004690 ATRACE_CALL();
4691
4692 class LayerRenderArea : public RenderArea {
4693 public:
Robert Carr578038f2018-03-09 12:25:24 -08004694 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4695 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004696 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004697 mLayer(layer),
4698 mCrop(crop),
4699 mFlinger(flinger),
4700 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004701 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004702 Rect getBounds() const override {
4703 const Layer::State& layerState(mLayer->getDrawingState());
4704 return Rect(layerState.active.w, layerState.active.h);
4705 }
4706 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4707 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4708 bool isSecure() const override { return false; }
4709 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004710 Rect getSourceCrop() const override {
4711 if (mCrop.isEmpty()) {
4712 return getBounds();
4713 } else {
4714 return mCrop;
4715 }
4716 }
4717 bool getWideColorSupport() const override { return false; }
4718 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004719 float getDisplayMaxLuminance() const override {
4720 return DisplayDevice::sDefaultMaxLumiance;
4721 }
Robert Carr578038f2018-03-09 12:25:24 -08004722
4723 class ReparentForDrawing {
4724 public:
4725 const sp<Layer>& oldParent;
4726 const sp<Layer>& newParent;
4727
4728 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4729 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004730 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004731 }
Robert Carr15eae092018-03-23 13:43:53 -07004732 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004733 };
4734
4735 void render(std::function<void()> drawLayers) override {
4736 if (!mChildrenOnly) {
4737 mTransform = mLayer->getTransform().inverse();
4738 drawLayers();
4739 } else {
4740 Rect bounds = getBounds();
4741 screenshotParentLayer =
4742 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4743 bounds.getWidth(), bounds.getHeight(), 0);
4744
4745 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4746 drawLayers();
4747 }
4748 }
chaviwa76b2712017-09-20 12:02:26 -07004749
chaviwa76b2712017-09-20 12:02:26 -07004750 private:
chaviw7206d492017-11-10 16:16:12 -08004751 const sp<Layer> mLayer;
4752 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004753
4754 // In the "childrenOnly" case we reparent the children to a screenshot
4755 // layer which has no properties set and which does not draw.
4756 sp<ContainerLayer> screenshotParentLayer;
4757 Transform mTransform;
4758
4759 SurfaceFlinger* mFlinger;
4760 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004761 };
4762
4763 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4764 auto parent = layerHandle->owner.promote();
4765
chaviw7206d492017-11-10 16:16:12 -08004766 if (parent == nullptr || parent->isPendingRemoval()) {
4767 ALOGE("captureLayers called with a removed parent");
4768 return NAME_NOT_FOUND;
4769 }
4770
Robert Carr578038f2018-03-09 12:25:24 -08004771 const int uid = IPCThreadState::self()->getCallingUid();
4772 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4773 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4774 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4775 return PERMISSION_DENIED;
4776 }
4777
chaviw7206d492017-11-10 16:16:12 -08004778 Rect crop(sourceCrop);
4779 if (sourceCrop.width() <= 0) {
4780 crop.left = 0;
4781 crop.right = parent->getCurrentState().active.w;
4782 }
4783
4784 if (sourceCrop.height() <= 0) {
4785 crop.top = 0;
4786 crop.bottom = parent->getCurrentState().active.h;
4787 }
4788
4789 int32_t reqWidth = crop.width() * frameScale;
4790 int32_t reqHeight = crop.height() * frameScale;
4791
Robert Carr578038f2018-03-09 12:25:24 -08004792 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004793
Robert Carr578038f2018-03-09 12:25:24 -08004794 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004795 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4796 if (!layer->isVisible()) {
4797 return;
Robert Carr578038f2018-03-09 12:25:24 -08004798 } else if (childrenOnly && layer == parent.get()) {
4799 return;
chaviwa76b2712017-09-20 12:02:26 -07004800 }
4801 visitor(layer);
4802 });
4803 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004804 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004805}
4806
4807status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4808 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004809 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004810 bool useIdentityTransform) {
4811 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004812
chaviwa76b2712017-09-20 12:02:26 -07004813 renderArea.updateDimensions();
4814
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004815 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4816 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4817 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4818 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004819
4820 // This mutex protects syncFd and captureResult for communication of the return values from the
4821 // main thread back to this Binder thread
4822 std::mutex captureMutex;
4823 std::condition_variable captureCondition;
4824 std::unique_lock<std::mutex> captureLock(captureMutex);
4825 int syncFd = -1;
4826 std::optional<status_t> captureResult;
4827
Robert Carr03480e22018-01-04 16:02:06 -08004828 const int uid = IPCThreadState::self()->getCallingUid();
4829 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4830
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004831 sp<LambdaMessage> message = new LambdaMessage([&]() {
4832 // If there is a refresh pending, bug out early and tell the binder thread to try again
4833 // after the refresh.
4834 if (mRefreshPending) {
4835 ATRACE_NAME("Skipping screenshot for now");
4836 std::unique_lock<std::mutex> captureLock(captureMutex);
4837 captureResult = std::make_optional<status_t>(EAGAIN);
4838 captureCondition.notify_one();
4839 return;
4840 }
4841
4842 status_t result = NO_ERROR;
4843 int fd = -1;
4844 {
4845 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004846 renderArea.render([&]() {
4847 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4848 useIdentityTransform, forSystem, &fd);
4849 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004850 }
4851
4852 {
4853 std::unique_lock<std::mutex> captureLock(captureMutex);
4854 syncFd = fd;
4855 captureResult = std::make_optional<status_t>(result);
4856 captureCondition.notify_one();
4857 }
4858 });
4859
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004860 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004861 if (result == NO_ERROR) {
4862 captureCondition.wait(captureLock, [&]() { return captureResult; });
4863 while (*captureResult == EAGAIN) {
4864 captureResult.reset();
4865 result = postMessageAsync(message);
4866 if (result != NO_ERROR) {
4867 return result;
4868 }
4869 captureCondition.wait(captureLock, [&]() { return captureResult; });
4870 }
4871 result = *captureResult;
4872 }
4873
4874 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004875 sync_wait(syncFd, -1);
4876 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004877 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004878
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004879 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004880}
4881
chaviwa76b2712017-09-20 12:02:26 -07004882void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4883 TraverseLayersFunction traverseLayers, bool yswap,
4884 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004885 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004886
Lloyd Pique144e1162017-12-20 16:44:52 -08004887 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004888
4889 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004890 const auto raWidth = renderArea.getWidth();
4891 const auto raHeight = renderArea.getHeight();
4892
4893 const auto reqWidth = renderArea.getReqWidth();
4894 const auto reqHeight = renderArea.getReqHeight();
4895 Rect sourceCrop = renderArea.getSourceCrop();
4896
4897 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4898 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004899
Dan Stozac1879002014-05-22 15:59:05 -07004900 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004901 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004902 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004903 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004904 }
4905
4906 // ensure that sourceCrop is inside screen
4907 if (sourceCrop.left < 0) {
4908 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4909 }
chaviwa76b2712017-09-20 12:02:26 -07004910 if (sourceCrop.right > raWidth) {
4911 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004912 }
4913 if (sourceCrop.top < 0) {
4914 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4915 }
chaviwa76b2712017-09-20 12:02:26 -07004916 if (sourceCrop.bottom > raHeight) {
4917 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004918 }
4919
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004920 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004921 if (renderArea.getWideColorSupport()) {
4922 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004923 }
Peiyong Linfb069302018-04-25 14:34:31 -07004924 engine.setOutputDataSpace(outputDataspace);
4925 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004926
Mathias Agopian180f10d2013-04-10 22:55:41 -07004927 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004928 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004929
4930 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004931 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4932 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004933 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004934
chaviw50da5042018-04-09 13:49:37 -07004935 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004936 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004937 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004938
chaviwa76b2712017-09-20 12:02:26 -07004939 traverseLayers([&](Layer* layer) {
4940 if (filtering) layer->setFiltering(true);
4941 layer->draw(renderArea, useIdentityTransform);
4942 if (filtering) layer->setFiltering(false);
4943 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004944}
4945
chaviwa76b2712017-09-20 12:02:26 -07004946status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4947 TraverseLayersFunction traverseLayers,
4948 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004949 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004950 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004951 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004952 ATRACE_CALL();
4953
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004954 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004955
4956 traverseLayers([&](Layer* layer) {
4957 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4958 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004959
Robert Carr03480e22018-01-04 16:02:06 -08004960 // We allow the system server to take screenshots of secure layers for
4961 // use in situations like the Screen-rotation animation and place
4962 // the impetus on WindowManager to not persist them.
4963 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004964 ALOGW("FB is protected: PERMISSION_DENIED");
4965 return PERMISSION_DENIED;
4966 }
4967
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004968 // this binds the given EGLImage as a framebuffer for the
4969 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004970 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004971 if (bufferBond.getStatus() != NO_ERROR) {
4972 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004973 return INVALID_OPERATION;
4974 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004975
Dan Stozaabcda352017-06-01 14:37:39 -07004976 // this will in fact render into our dequeued buffer
4977 // via an FBO, which means we didn't have to create
4978 // an EGLSurface and therefore we're not
4979 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004980 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004981
Dan Stozaabcda352017-06-01 14:37:39 -07004982 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004983 getRenderEngine().finish();
4984 *outSyncFd = -1;
4985
chaviwa76b2712017-09-20 12:02:26 -07004986 const auto reqWidth = renderArea.getReqWidth();
4987 const auto reqHeight = renderArea.getReqHeight();
4988
Dan Stozaabcda352017-06-01 14:37:39 -07004989 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4990 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004991 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004992 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004993 } else {
4994 base::unique_fd syncFd = getRenderEngine().flush();
4995 if (syncFd < 0) {
4996 getRenderEngine().finish();
4997 }
4998 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004999 }
5000
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005001 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005002}
5003
Mathias Agopiand5556842013-09-19 17:08:37 -07005004void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005005 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005006 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005007 for (size_t y = 0; y < h; y++) {
5008 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5009 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005010 if (p[x] != 0xFF000000) return;
5011 }
5012 }
chaviwa76b2712017-09-20 12:02:26 -07005013 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005014
Robert Carr2047fae2016-11-28 14:09:09 -08005015 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005016 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005017 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005018 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5019 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5020 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5021 static_cast<float>(state.color.a));
5022 i++;
5023 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005024 }
5025}
5026
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005027// ---------------------------------------------------------------------------
5028
Dan Stoza412903f2017-04-27 13:42:17 -07005029void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5030 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005031}
5032
Dan Stoza412903f2017-04-27 13:42:17 -07005033void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5034 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005035}
5036
chaviwa76b2712017-09-20 12:02:26 -07005037void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5038 int32_t maxLayerZ,
5039 const LayerVector::Visitor& visitor) {
5040 // We loop through the first level of layers without traversing,
5041 // as we need to interpret min/max layer Z in the top level Z space.
5042 for (const auto& layer : mDrawingState.layersSortedByZ) {
5043 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5044 continue;
5045 }
5046 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005047 // relative layers are traversed in Layer::traverseInZOrder
5048 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005049 continue;
5050 }
5051 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005052 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5053 return;
5054 }
chaviwa76b2712017-09-20 12:02:26 -07005055 if (!layer->isVisible()) {
5056 return;
5057 }
5058 visitor(layer);
5059 });
5060 }
5061}
5062
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005063}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005064
5065
5066#if defined(__gl_h_)
5067#error "don't include gl/gl.h in this file"
5068#endif
5069
5070#if defined(__gl2_h_)
5071#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005072#endif