blob: 63163c38d48b588fedec819eee1dc1096bd0de30 [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 Lin9f034472018-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 Pique99d3da52018-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 Piqueac648ee2018-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),
Romain Guya9638732017-06-01 12:05:21 -0700247 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800248 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800249 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700250 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800251 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800252 mCreateBufferQueue(&BufferQueue::createBufferQueue),
253 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800254
255SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800257
258 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
260
261 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
263
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700267 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
269
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700270 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
272
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
275
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 // Vr flinger is only enabled on Daydream ready devices.
277 useVrFlinger = getBool< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::useVrFlinger>(false);
279
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
282
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283 hasWideColorDisplay =
284 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
285
David Sodman99974d22017-11-28 12:04:33 -0800286 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 // debugging stuff...
289 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700290
Mathias Agopianb4b17302013-03-20 18:36:41 -0700291 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700292 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294 property_get("debug.sf.showupdates", value, "0");
295 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700297 property_get("debug.sf.ddms", value, "0");
298 mDebugDDMS = atoi(value);
299 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700300 if (!startDdmConnection()) {
301 // start failed, and DDMS debugging not enabled
302 mDebugDDMS = 0;
303 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700304 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700305 ALOGI_IF(mDebugRegion, "showupdates enabled");
306 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700307
308 property_get("debug.sf.disable_backpressure", value, "0");
309 mPropagateBackpressure = !atoi(value);
310 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700311
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800312 property_get("debug.sf.enable_hwc_vds", value, "0");
313 mUseHwcVirtualDisplays = atoi(value);
314 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800315
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800316 property_get("ro.sf.disable_triple_buffer", value, "1");
317 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800318 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700319
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 // TODO (b/74616334): Reduce the default value once we isolate the leak
321 const size_t defaultListSize = 4 * MAX_LAYERS;
322 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
323 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
324
Dan Stoza84d619e2018-03-28 17:07:36 -0700325 property_get("debug.sf.early_phase_offset_ns", value, "0");
326 const int earlyWakeupOffsetOffsetNs = atoi(value);
327 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
328 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
329 sfVsyncPhaseOffsetNs);
330
Romain Guy11d63f42017-07-20 12:47:14 -0700331 // We should be reading 'persist.sys.sf.color_saturation' here
332 // but since /data may be encrypted, we need to wait until after vold
333 // comes online to attempt to read the property. The property is
334 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800335
336 if (useTrebleTestingOverride()) {
337 // Without the override SurfaceFlinger cannot connect to HIDL
338 // services that are not listed in the manifests. Considered
339 // deriving the setting from the set service name, but it
340 // would be brittle if the name that's not 'default' is used
341 // for production purposes later on.
342 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344}
345
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800346void SurfaceFlinger::onFirstRef()
347{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800348 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351SurfaceFlinger::~SurfaceFlinger()
352{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Dan Stozac7014012014-02-14 15:03:43 -0800355void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356{
357 // the window manager died on us. prepare its eulogy.
358
Andy McFadden13a082e2012-08-24 10:16:42 -0700359 // restore initial conditions (default device unblank, etc)
360 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800361
362 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700363 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800364}
365
Robert Carr1db73f62016-12-21 12:58:51 -0800366static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700367 status_t err = client->initCheck();
368 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 }
Robert Carr1db73f62016-12-21 12:58:51 -0800371 return nullptr;
372}
373
374sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
375 return initClient(new Client(this));
376}
377
378sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
379 const sp<IGraphicBufferProducer>& gbp) {
380 if (authenticateSurfaceTexture(gbp) == false) {
381 return nullptr;
382 }
383 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
384 if (layer == nullptr) {
385 return nullptr;
386 }
387
388 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700391sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
392 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700393{
394 class DisplayToken : public BBinder {
395 sp<SurfaceFlinger> flinger;
396 virtual ~DisplayToken() {
397 // no more references, this display must be terminated
398 Mutex::Autolock _l(flinger->mStateLock);
399 flinger->mCurrentState.displays.removeItem(this);
400 flinger->setTransactionFlags(eDisplayTransactionNeeded);
401 }
402 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700403 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 : flinger(flinger) {
405 }
406 };
407
408 sp<BBinder> token = new DisplayToken(this);
409
410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700411 DisplayDeviceState info;
412 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700413 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700414 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800416 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417 return token;
418}
419
Jesse Hall6c913be2013-08-08 12:15:49 -0700420void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
421 Mutex::Autolock _l(mStateLock);
422
423 ssize_t idx = mCurrentState.displays.indexOfKey(display);
424 if (idx < 0) {
425 ALOGW("destroyDisplay: invalid display token");
426 return;
427 }
428
429 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700430 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 ALOGE("destroyDisplay called for non-virtual display");
432 return;
433 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700434 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700435 mCurrentState.displays.removeItemsAt(idx);
436 setTransactionFlags(eDisplayTransactionNeeded);
437}
438
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700440 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800442 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 }
Jesse Hall692c7232012-11-08 15:41:56 -0800444 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445}
446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447void SurfaceFlinger::bootFinished()
448{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700449 if (mStartPropertySetThread->join() != NO_ERROR) {
450 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 const nsecs_t now = systemTime();
453 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000454 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700455
456 // wait patiently for the window manager death
457 const String16 name("window");
458 sp<IBinder> window(defaultServiceManager()->getService(name));
459 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700460 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700461 }
462
Steven Thomas050b2c82017-03-06 11:45:16 -0800463 if (mVrFlinger) {
464 mVrFlinger->OnBootFinished();
465 }
466
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700467 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700468 // formerly we would just kill the process, but we now ask it to exit so it
469 // can choose where to stop the animation.
470 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700471
472 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
473 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
474 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700475
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700477 readPersistentProperties();
478 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700479 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480}
481
Mathias Agopian3f844832013-08-07 21:24:32 -0700482void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700485 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800487 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
488 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700489 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700490 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491 return true;
492 }
493 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700494 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700495}
496
Lloyd Piquee83f9312018-02-01 12:53:17 -0800497class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 const char* name) :
501 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
505 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 mDispSync(dispSync),
507 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508 mVsyncMutex(),
509 mPhaseOffset(phaseOffset),
510 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700511
Lloyd Piquee83f9312018-02-01 12:53:17 -0800512 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513
Lloyd Piquee83f9312018-02-01 12:53:17 -0800514 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000517 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 static_cast<DispSync::Callback*>(this));
519 if (err != NO_ERROR) {
520 ALOGE("error registering vsync callback: %s (%d)",
521 strerror(-err), err);
522 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700523 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 } else {
525 status_t err = mDispSync->removeEventListener(
526 static_cast<DispSync::Callback*>(this));
527 if (err != NO_ERROR) {
528 ALOGE("error unregistering vsync callback: %s (%d)",
529 strerror(-err), err);
530 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 }
535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 mCallback = callback;
539 }
540
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542 Mutex::Autolock lock(mVsyncMutex);
543
544 // Normalize phaseOffset to [0, period)
545 auto period = mDispSync->getPeriod();
546 phaseOffset %= period;
547 if (phaseOffset < 0) {
548 // If we're here, then phaseOffset is in (-period, 0). After this
549 // operation, it will be in (0, period)
550 phaseOffset += period;
551 }
552 mPhaseOffset = phaseOffset;
553
554 // If we're not enabled, we don't need to mess with the listeners
555 if (!mEnabled) {
556 return;
557 }
558
Dan Stoza84d619e2018-03-28 17:07:36 -0700559 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
560 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700562 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700563 strerror(-err), err);
564 }
565 }
566
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567private:
568 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700572 callback = mCallback;
573
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 if (mTraceVsync) {
575 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700577 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 }
579
Peiyong Lin566a3b42018-01-09 18:22:43 -0800580 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581 callback->onVSyncEvent(when);
582 }
583 }
584
Tim Murray4a4e4a22016-04-19 16:29:23 +0000585 const char* const mName;
586
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587 int mValue;
588
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700590 const String8 mVsyncOnLabel;
591 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700592
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800596 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597
598 Mutex mVsyncMutex; // Protects the following
599 nsecs_t mPhaseOffset;
600 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601};
602
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 InjectVSyncSource() = default;
606 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607
Lloyd Piquee83f9312018-02-01 12:53:17 -0800608 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700609 std::lock_guard<std::mutex> lock(mCallbackMutex);
610 mCallback = callback;
611 }
612
Lloyd Piquee83f9312018-02-01 12:53:17 -0800613 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700615 if (mCallback) {
616 mCallback->onVSyncEvent(when);
617 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618 }
619
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 void setVSyncEnabled(bool) override {}
621 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622
623private:
624 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800625 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700626};
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
633
Thierry Strudel2924d012017-08-14 15:19:37 -0700634 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800639 mEventThreadSource =
640 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
641 true, "app");
642 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
643 "appEventThread");
644 mSfEventThreadSource =
645 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
646 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800648 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
649 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800650 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700651 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800654 getBE().mRenderEngine =
655 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
656 hasWideColorDisplay
657 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
658 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800659 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700660
661 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
662 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800663 getBE().mHwc.reset(
664 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700665 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800666 // Process any initial hotplug and resulting display changes.
667 processDisplayHotplugEventsLocked();
668 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
669 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Lloyd Piquefcd86612017-12-14 17:15:36 -0800671 // make the default display GLContext current so that we can create textures
672 // when creating Layers (which may happens before we render something)
673 getDefaultDisplayDeviceLocked()->makeCurrent();
674
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (useVrFlinger) {
676 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 // This callback is called from the vr flinger dispatch thread. We
678 // need to call signalTransaction(), which requires holding
679 // mStateLock when we're not on the main thread. Acquiring
680 // mStateLock from the vr flinger dispatch thread might trigger a
681 // deadlock in surface flinger (see b/66916578), so post a message
682 // to be handled on the main thread instead.
683 sp<LambdaMessage> message = new LambdaMessage([=]() {
684 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
685 mVrFlingerRequestsDisplay = requestDisplay;
686 signalTransaction();
687 });
688 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
David Sodman105b7dc2017-11-04 20:28:14 -0700690 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
691 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800692 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (!mVrFlinger) {
694 ALOGE("Failed to start vrflinger");
695 }
696 }
697
Lloyd Pique379adc12018-01-22 17:31:47 -0800698 mEventControlThread = std::make_unique<impl::EventControlThread>(
699 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700700
Mathias Agopian92a979a2012-08-02 18:32:23 -0700701 // initialize our drawing state
702 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700703
Andy McFadden13a082e2012-08-24 10:16:42 -0700704 // set initial conditions (e.g. unblank default device)
705 initializeDisplays();
706
David Sodmanbc815282017-11-05 18:57:52 -0800707 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700708
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 // Inform native graphics APIs whether the present timestamp is supported:
710 if (getHwComposer().hasCapability(
711 HWC2::Capability::PresentFenceIsNotReliable)) {
712 mStartPropertySetThread = new StartPropertySetThread(false);
713 } else {
714 mStartPropertySetThread = new StartPropertySetThread(true);
715 }
716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
722 Dataspace::SRGB_LINEAR);
723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700725}
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727void SurfaceFlinger::readPersistentProperties() {
728 char value[PROPERTY_VALUE_MAX];
729
730 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 mGlobalSaturationFactor = atof(value);
732 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);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928 int currentMode = hw->getActiveConfig();
929
930 if (mode == currentMode) {
931 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
932 return;
933 }
934
Dominik Laskowski281644e2018-04-19 15:47:35 -0700935 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 ALOGW("Trying to set config for virtual display");
937 return;
938 }
939
940 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700941 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942}
943
944status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
945 class MessageSetActiveConfig: public MessageBase {
946 SurfaceFlinger& mFlinger;
947 sp<IBinder> mDisplay;
948 int mMode;
949 public:
950 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
951 int mode) :
952 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
953 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700954 Vector<DisplayInfo> configs;
955 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700956 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700957 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700958 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700959 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700960 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800962 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700964 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700965 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 ALOGW("Attempt to set active config = %d for virtual display",
967 mMode);
968 } else {
969 mFlinger.setActiveConfigInternal(hw, mMode);
970 }
971 return true;
972 }
973 };
974 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
975 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700976 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700977}
Michael Wright28f24d02016-07-12 13:30:53 -0700978status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700979 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
981 return BAD_VALUE;
982 }
983
984 if (!display.get()) {
985 return NAME_NOT_FOUND;
986 }
987
988 int32_t type = NAME_NOT_FOUND;
989 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
990 if (display == mBuiltinDisplays[i]) {
991 type = i;
992 break;
993 }
994 }
995
996 if (type < 0) {
997 return type;
998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
1004 modes = getHwComposer().getColorModes(type);
1005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001013 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001014 if (device != nullptr) {
1015 return device->getActiveColorMode();
1016 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001017 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001018}
1019
1020void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001021 ColorMode mode, Dataspace dataSpace) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001023 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001024 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001025
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026 // Natural Mode means it's color managed and the color must be right,
1027 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1028 // Native Mode means the display is not color managed, and whichever
1029 // render intent is picked doesn't matter, thus return
1030 // RenderIntent::COLORIMETRIC as default here.
1031 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1032
1033 // In Auto Color Mode, we want to strech to panel color space, right now
1034 // only the built-in display supports it.
Dominik Laskowski281644e2018-04-19 15:47:35 -07001035 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED && mBuiltinDisplaySupportsEnhance &&
1036 hw->isPrimary()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001037 renderIntent = RenderIntent::ENHANCE;
1038 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001039
1040 if (mode == currentMode && dataSpace == currentDataSpace &&
1041 renderIntent == currentRenderIntent) {
1042 return;
1043 }
1044
Dominik Laskowski281644e2018-04-19 15:47:35 -07001045 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001046 ALOGW("Trying to set config for virtual display");
1047 return;
1048 }
1049
1050 hw->setActiveColorMode(mode);
1051 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001052 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001053 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001054
1055 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1056 decodeColorMode(mode).c_str(), mode,
1057 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1058 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001059}
1060
1061
1062status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 class MessageSetActiveColorMode: public MessageBase {
1065 SurfaceFlinger& mFlinger;
1066 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001068 public:
1069 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001071 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1072 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger.getDisplayColorModes(mDisplay, &modes);
1075 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001077 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1078 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001079 return true;
1080 }
1081 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1082 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001083 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1084 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001085 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGW("Attempt to set active color mode %s %d for virtual display",
1087 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001088 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001089 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001090 }
1091 return true;
1092 }
1093 };
1094 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1095 postMessageSync(msg);
1096 return NO_ERROR;
1097}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001098
Svetoslavd85084b2014-03-20 10:28:31 -07001099status_t SurfaceFlinger::clearAnimationFrameStats() {
1100 Mutex::Autolock _l(mStateLock);
1101 mAnimFrameTracker.clearStats();
1102 return NO_ERROR;
1103}
1104
1105status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1106 Mutex::Autolock _l(mStateLock);
1107 mAnimFrameTracker.getStats(outStats);
1108 return NO_ERROR;
1109}
1110
Dan Stozac4f471e2016-03-24 09:31:08 -07001111status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1112 HdrCapabilities* outCapabilities) const {
1113 Mutex::Autolock _l(mStateLock);
1114
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001115 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001116 if (displayDevice == nullptr) {
1117 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1118 return BAD_VALUE;
1119 }
1120
Peiyong Lin62665892018-04-16 11:07:44 -07001121 HdrCapabilities capabilities;
1122 int status = getBE().mHwc->getHdrCapabilities(
1123 displayDevice->getHwcDisplayId(), &capabilities);
1124 if (status == NO_ERROR) {
1125 if (displayDevice->hasWideColorGamut() &&
1126 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001127 // insert HDR10 as we will force client composition for HDR10
1128 // layers
Peiyong Lin62665892018-04-16 11:07:44 -07001129 std::vector<Hdr> types = capabilities.getSupportedHdrTypes();
1130 types.push_back(Hdr::HDR10);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001131
1132 *outCapabilities = HdrCapabilities(types,
Peiyong Lin62665892018-04-16 11:07:44 -07001133 capabilities.getDesiredMaxLuminance(),
1134 capabilities.getDesiredMaxAverageLuminance(),
1135 capabilities.getDesiredMinLuminance());
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001136 } else {
Peiyong Lin62665892018-04-16 11:07:44 -07001137 *outCapabilities = std::move(capabilities);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001138 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001139 } else {
1140 return BAD_VALUE;
1141 }
1142
1143 return NO_ERROR;
1144}
1145
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1148 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150 if (mInjectVSyncs == enable) {
1151 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001152 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153
1154 if (enable) {
1155 ALOGV("VSync Injections enabled");
1156 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001157 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001158 mInjectorEventThread =
1159 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1160 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 } else {
1164 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 }
1167
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001168 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001169 });
1170 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001171 return NO_ERROR;
1172}
1173
1174status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 Mutex::Autolock _l(mStateLock);
1176
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177 if (!mInjectVSyncs) {
1178 ALOGE("VSync Injections not enabled");
1179 return BAD_VALUE;
1180 }
1181 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1182 ALOGV("Injecting VSync inside SurfaceFlinger");
1183 mVSyncInjector->onInjectSyncEvent(when);
1184 }
1185 return NO_ERROR;
1186}
1187
Lloyd Pique755e3192018-01-31 16:46:15 -08001188status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1189 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001190 IPCThreadState* ipc = IPCThreadState::self();
1191 const int pid = ipc->getCallingPid();
1192 const int uid = ipc->getCallingUid();
1193 if ((uid != AID_SHELL) &&
1194 !PermissionCache::checkPermission(sDump, pid, uid)) {
1195 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1196 return PERMISSION_DENIED;
1197 }
1198
1199 // Try to acquire a lock for 1s, fail gracefully
1200 const status_t err = mStateLock.timedLock(s2ns(1));
1201 const bool locked = (err == NO_ERROR);
1202 if (!locked) {
1203 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1204 return TIMED_OUT;
1205 }
1206
1207 outLayers->clear();
1208 mCurrentState.traverseInZOrder([&](Layer* layer) {
1209 outLayers->push_back(layer->getLayerDebugInfo());
1210 });
1211
1212 mStateLock.unlock();
1213 return NO_ERROR;
1214}
1215
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001216// ----------------------------------------------------------------------------
1217
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001218sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1219 ISurfaceComposer::VsyncSource vsyncSource) {
1220 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1221 return mSFEventThread->createEventConnection();
1222 } else {
1223 return mEventThread->createEventConnection();
1224 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001225}
1226
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001227// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001228
1229void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001230 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001231}
1232
1233void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001234 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001235}
1236
1237void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001238 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001242 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001243 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244}
1245
1246status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001247 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001248 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249}
1250
1251status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001252 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001253 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001254 if (res == NO_ERROR) {
1255 msg->wait();
1256 }
1257 return res;
1258}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001259
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001260void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001261 do {
1262 waitForEvent();
1263 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001264}
1265
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266void SurfaceFlinger::enableHardwareVsync() {
1267 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001268 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001270 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1271 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001273 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274}
1275
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 Mutex::Autolock _l(mHWVsyncLock);
1278
Jesse Hall948fe0c2013-10-14 12:56:09 -07001279 if (makeAvailable) {
1280 mHWVsyncAvailable = true;
1281 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001282 // Hardware vsync is not currently available, so abort the resync
1283 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 return;
1285 }
1286
David Sodman105b7dc2017-11-04 20:28:14 -07001287 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001288 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
1290 mPrimaryDispSync.reset();
1291 mPrimaryDispSync.setPeriod(period);
1292
1293 if (!mPrimaryHWVsyncEnabled) {
1294 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1296 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryHWVsyncEnabled = true;
1298 }
1299}
1300
Jesse Hall948fe0c2013-10-14 12:56:09 -07001301void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302 Mutex::Autolock _l(mHWVsyncLock);
1303 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001304 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1305 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306 mPrimaryDispSync.endResync();
1307 mPrimaryHWVsyncEnabled = false;
1308 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309 if (makeUnavailable) {
1310 mHWVsyncAvailable = false;
1311 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312}
1313
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314void SurfaceFlinger::resyncWithRateLimit() {
1315 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001316
1317 // No explicit locking is needed here since EventThread holds a lock while calling this method
1318 static nsecs_t sLastResyncAttempted = 0;
1319 const nsecs_t now = systemTime();
1320 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001321 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001322 }
Dan Stoza57164302017-05-08 14:03:54 -07001323 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001324}
1325
Steven Thomasb02664d2017-07-26 18:48:28 -07001326void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1327 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001328 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001330 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 return;
1332 }
1333
1334 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001335 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001336 return;
1337 }
1338
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340
Jamie Gennisd1700752013-10-14 12:22:52 -07001341 { // Scope for the lock
1342 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001346 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001347
1348 if (needsHwVsync) {
1349 enableHardwareVsync();
1350 } else {
1351 disableHardwareVsync(false);
1352 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001353}
1354
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001355void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001356 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1357 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001358}
1359
Lloyd Pique715a2c12017-12-14 17:18:08 -08001360void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1361 HWC2::Connection connection) {
1362 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1363 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001364
Lloyd Piqueba04e622017-12-14 17:11:26 -08001365 // Ignore events that do not have the right sequenceId.
1366 if (sequenceId != getBE().mComposerSequenceId) {
1367 return;
1368 }
1369
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 // Only lock if we're not on the main thread. This function is normally
1371 // called on a hwbinder thread, but for the primary display it's called on
1372 // the main thread with the state lock already held, so don't attempt to
1373 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001374 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001375
Lloyd Pique715a2c12017-12-14 17:18:08 -08001376 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001377
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001378 if (std::this_thread::get_id() == mMainThreadId) {
1379 // Process all pending hot plug events immediately if we are on the main thread.
1380 processDisplayHotplugEventsLocked();
1381 }
1382
Lloyd Piqueba04e622017-12-14 17:11:26 -08001383 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001384}
1385
Steven Thomasb02664d2017-07-26 18:48:28 -07001386void SurfaceFlinger::onRefreshReceived(int sequenceId,
1387 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001391 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001392 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001393}
1394
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398 getHwComposer().setVsyncEnabled(disp,
1399 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001400}
1401
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001403void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405 // Clear the drawing state so that the logic inside of
1406 // handleTransactionLocked will fire. It will determine the delta between
1407 // mCurrentState and mDrawingState and re-apply all changes when we make the
1408 // transition.
1409 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001410 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411 mDisplays.clear();
1412}
1413
Steven Thomas050b2c82017-03-06 11:45:16 -08001414void SurfaceFlinger::updateVrFlinger() {
1415 if (!mVrFlinger)
1416 return;
1417 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 return;
1420 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
David Sodman105b7dc2017-11-04 20:28:14 -07001422 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 ALOGE("Vr flinger is only supported for remote hardware composer"
1424 " service connections. Ignoring request to transition to vr"
1425 " flinger.");
1426 mVrFlingerRequestsDisplay = false;
1427 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001428 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 int currentDisplayPowerMode = getDisplayDeviceLocked(
1433 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001436 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001440 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001441 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1442 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001443 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001444
David Sodman105b7dc2017-11-04 20:28:14 -07001445 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1446 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001447
1448 if (vrFlingerRequestsDisplay) {
1449 mVrFlinger->GrantDisplayOwnership();
1450 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001453
1454 mVisibleRegionsDirty = true;
1455 invalidateHwcGeometry();
1456
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001457 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1459 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1460 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001461
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001463 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 const nsecs_t period = activeConfig->getVsyncPeriod();
1465 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Use phase of 0 since phase is not known.
1468 // Use latency of 0, which will snap to the ideal latency.
1469 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001470
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471 android_atomic_or(1, &mRepaintEverything);
1472 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473}
1474
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001476 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001477 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001479 bool frameMissed = !mHadClientComposition &&
1480 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481 (mPreviousPresentFence->getSignalTime() ==
1482 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001483 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001484 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001485 signalLayerUpdate();
1486 break;
1487 }
1488
Steven Thomas050b2c82017-03-06 11:45:16 -08001489 // Now that we're going to make it to the handleMessageTransaction()
1490 // call below it's safe to call updateVrFlinger(), which will
1491 // potentially trigger a display handoff.
1492 updateVrFlinger();
1493
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 bool refreshNeeded = handleMessageTransaction();
1495 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001496 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001498 // Signal a refresh if a transaction modified the window state,
1499 // a new buffer was latched, or if HWC has requested a full
1500 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001501 signalRefresh();
1502 }
1503 break;
1504 }
1505 case MessageQueue::REFRESH: {
1506 handleMessageRefresh();
1507 break;
1508 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001509 }
1510}
1511
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001513 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001515 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519}
1520
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524}
1525
1526void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001528
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001529 mRefreshPending = false;
1530
Chia-I Wu30505fb2018-03-26 16:20:31 -07001531 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
Chia-I Wu30505fb2018-03-26 16:20:31 -07001533 preComposition(refreshStartTime);
1534 rebuildLayerStacks();
1535 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001536 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001537 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001538 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001539 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001540 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001541
David Sodman105b7dc2017-11-04 20:28:14 -07001542 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001543
1544 mHadClientComposition = false;
1545 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1546 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1547 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001548 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001549 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001550 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001551
Dan Stoza9e56aa02015-11-02 13:00:03 -08001552 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001554
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555void SurfaceFlinger::doDebugFlashRegions()
1556{
1557 // is debugging enabled
1558 if (CC_LIKELY(!mDebugRegion))
1559 return;
1560
1561 const bool repaintEverything = mRepaintEverything;
1562 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1563 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001564 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 // transform the dirty region into this screen's coordinate space
1566 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1567 if (!dirtyRegion.isEmpty()) {
1568 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001569 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570
1571 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001573 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001574 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1575
Mathias Agopianda27af92012-09-13 18:17:13 -07001576 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 }
1578 }
1579 }
1580
1581 postFramebuffer();
1582
1583 if (mDebugRegion > 1) {
1584 usleep(mDebugRegion * 1000);
1585 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001586
Dan Stoza9e56aa02015-11-02 13:00:03 -08001587 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001588 auto& displayDevice = mDisplays[displayId];
1589 if (!displayDevice->isDisplayOn()) {
1590 continue;
1591 }
1592
David Sodman105b7dc2017-11-04 20:28:14 -07001593 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1594 ALOGE_IF(result != NO_ERROR,
1595 "prepareFrame for display %zd failed:"
1596 " %d (%s)",
1597 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001598 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599}
1600
Adrian Roos1e1a1282017-11-01 19:05:31 +01001601void SurfaceFlinger::doTracing(const char* where) {
1602 ATRACE_CALL();
1603 ATRACE_NAME(where);
1604 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001605 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001606 }
1607}
1608
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001609void SurfaceFlinger::logLayerStats() {
1610 ATRACE_CALL();
1611 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1612 int32_t hwcId = -1;
1613 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1614 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1615 if (displayDevice->isPrimary()) {
1616 hwcId = displayDevice->getHwcDisplayId();
1617 break;
1618 }
1619 }
1620 if (hwcId < 0) {
1621 ALOGE("LayerStats: Hmmm, no primary display?");
1622 return;
1623 }
1624 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1625 }
1626}
1627
Chia-I Wu30505fb2018-03-26 16:20:31 -07001628void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001630 ATRACE_CALL();
1631 ALOGV("preComposition");
1632
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001634 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001635 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636 needExtraInvalidate = true;
1637 }
Robert Carr2047fae2016-11-28 14:09:09 -08001638 });
1639
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640 if (needExtraInvalidate) {
1641 signalLayerUpdate();
1642 }
1643}
1644
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645void SurfaceFlinger::updateCompositorTiming(
1646 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1647 std::shared_ptr<FenceTime>& presentFenceTime) {
1648 // Update queue of past composite+present times and determine the
1649 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001650 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001652 while (!getBE().mCompositePresentTimes.empty()) {
1653 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 // Cached values should have been updated before calling this method,
1655 // which helps avoid duplicate syscalls.
1656 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1657 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1658 break;
1659 }
1660 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001661 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662 }
1663
1664 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001665 while (getBE().mCompositePresentTimes.size() > 16) {
1666 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 }
1668
Brian Andersond0010582017-03-07 13:20:31 -08001669 setCompositorTimingSnapped(
1670 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1671}
1672
1673void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1674 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001675 // Integer division and modulo round toward 0 not -inf, so we need to
1676 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001677 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1679 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1680
Brian Andersond0010582017-03-07 13:20:31 -08001681 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1682 if (idealLatency <= 0) {
1683 idealLatency = vsyncInterval;
1684 }
1685
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686 // Snap the latency to a value that removes scheduling jitter from the
1687 // composition and present times, which often have >1ms of jitter.
1688 // Reducing jitter is important if an app attempts to extrapolate
1689 // something (such as user input) to an accurate diasplay time.
1690 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1691 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001692 nsecs_t bias = vsyncInterval / 2;
1693 int64_t extraVsyncs =
1694 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1695 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1696 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697
David Sodman99974d22017-11-28 12:04:33 -08001698 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1699 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1700 getBE().mCompositorTiming.interval = vsyncInterval;
1701 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702}
1703
Chia-I Wu30505fb2018-03-26 16:20:31 -07001704void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706 ATRACE_CALL();
1707 ALOGV("postComposition");
1708
Brian Anderson3546a3f2016-07-14 11:51:14 -07001709 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001710 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001711 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001712 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001713 }
1714
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001715 // |mStateLock| not needed as we are on the main thread
1716 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001717
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001720 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 glCompositionDoneFenceTime =
1722 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 } else {
1725 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1726 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001727
David Sodman73beded2017-11-15 11:56:06 -08001728 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001729 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001730 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001731 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001732
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1734 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1735
Chia-I Wu30505fb2018-03-26 16:20:31 -07001736 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 // when we started doing work for this frame, but that should be okay
1738 // since updateCompositorTiming has snapping logic.
1739 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001740 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001741 CompositorTiming compositorTiming;
1742 {
David Sodman99974d22017-11-28 12:04:33 -08001743 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1744 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001745 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001746
Robert Carr2047fae2016-11-28 14:09:09 -08001747 mDrawingState.traverseInZOrder([&](Layer* layer) {
1748 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001749 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001750 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001751 recordBufferingStats(layer->getName().string(),
1752 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001753 }
Robert Carr2047fae2016-11-28 14:09:09 -08001754 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001755
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001756 if (presentFenceTime->isValid()) {
1757 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001758 enableHardwareVsync();
1759 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001760 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001761 }
1762 }
1763
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001764 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001765 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001766 enableHardwareVsync();
1767 }
1768 }
1769
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001770 if (mAnimCompositionPending) {
1771 mAnimCompositionPending = false;
1772
Brian Anderson4e606e32017-03-16 15:34:57 -07001773 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001774 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001775 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001776 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001777 // The HWC doesn't support present fences, so use the refresh
1778 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001780 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001781 mAnimFrameTracker.setActualPresentTime(presentTime);
1782 }
1783 mAnimFrameTracker.advanceFrame();
1784 }
Dan Stozab90cf072015-03-05 11:05:59 -08001785
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001786 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1787 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001788 return;
1789 }
1790
1791 nsecs_t currentTime = systemTime();
1792 if (mHasPoweredOff) {
1793 mHasPoweredOff = false;
1794 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001795 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001797 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1798 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001799 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001800 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001801 }
David Sodman4a36e932017-11-07 14:29:47 -08001802 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001803 }
David Sodman4a36e932017-11-07 14:29:47 -08001804 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001805}
1806
1807void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001808 ATRACE_CALL();
1809 ALOGV("rebuildLayerStacks");
1810
Mathias Agopiancd60f992012-08-16 16:28:27 -07001811 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001813 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 mVisibleRegionsDirty = false;
1815 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001816
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1818 Region opaqueRegion;
1819 Region dirtyRegion;
1820 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001821 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1823 const Transform& tr(displayDevice->getTransform());
1824 const Rect bounds(displayDevice->getBounds());
1825 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001826 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001827
Jeff Sharkey76488112017-02-27 14:15:18 -07001828 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001829 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001830 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1831 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001832 Region drawRegion(tr.transform(
1833 layer->visibleNonTransparentRegion));
1834 drawRegion.andSelf(bounds);
1835 if (!drawRegion.isEmpty()) {
1836 layersSortedByZ.add(layer);
1837 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001838 // Clear out the HWC layer if this layer was
1839 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001840 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001841 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001842 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001843 } else {
1844 // WM changes displayDevice->layerStack upon sleep/awake.
1845 // Here we make sure we delete the HWC layers even if
1846 // WM changed their layer stack.
1847 hwcLayerDestroyed = layer->destroyHwcLayer(
1848 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001849 }
1850
1851 // If a layer is not going to get a release fence because
1852 // it is invisible, but it is also going to release its
1853 // old buffer, add it to the list of layers needing
1854 // fences.
1855 if (hwcLayerDestroyed) {
1856 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1857 mLayersWithQueuedFrames.cend(), layer);
1858 if (found != mLayersWithQueuedFrames.cend()) {
1859 layersNeedingFences.add(layer);
1860 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001861 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001862 });
1863 }
1864 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001865 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001866 displayDevice->undefinedRegion.set(bounds);
1867 displayDevice->undefinedRegion.subtractSelf(
1868 tr.transform(opaqueRegion));
1869 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001870 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001871 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001873
Romain Guy0147a172017-06-01 13:53:56 -07001874mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001875 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001876 return mat4();
1877 }
1878
1879 // Rec.709 luma coefficients
1880 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001881 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001882 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001883 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1884 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1885 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001886 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1887 );
1888}
1889
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001890// Returns a dataspace that fits all visible layers. The returned dataspace
1891// can only be one of
1892//
1893// - Dataspace::V0_SRGB
1894// - Dataspace::DISPLAY_P3
1895// - Dataspace::V0_SCRGB_LINEAR
1896// TODO(b/73825729) Add BT2020 data space.
1897ui::Dataspace SurfaceFlinger::getBestDataspace(
1898 const sp<const DisplayDevice>& displayDevice) const {
1899 Dataspace bestDataspace = Dataspace::V0_SRGB;
1900 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1901 switch (layer->getDataSpace()) {
1902 case Dataspace::V0_SCRGB:
1903 case Dataspace::V0_SCRGB_LINEAR:
1904 // return immediately
1905 return Dataspace::V0_SCRGB_LINEAR;
1906 case Dataspace::BT2020_PQ:
1907 case Dataspace::BT2020_ITU_PQ:
1908 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1909 // since SurfaceFlinger simulates HDR support now, it should honor
1910 // them unless there is also native support.
Peiyong Lin62665892018-04-16 11:07:44 -07001911 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return Dataspace::V0_SCRGB_LINEAR;
1913 }
1914 break;
1915 case Dataspace::DISPLAY_P3:
1916 bestDataspace = Dataspace::DISPLAY_P3;
1917 break;
1918 default:
1919 break;
1920 }
Romain Guy54f154a2017-10-24 21:40:32 +01001921 }
1922
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001923 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001924}
1925
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926// Pick the ColorMode / Dataspace for the display device.
1927// TODO(b/73825729) Add BT2020 color mode.
1928void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1929 ColorMode* outMode, Dataspace* outDataSpace) const {
1930 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1931 *outMode = ColorMode::NATIVE;
1932 *outDataSpace = Dataspace::UNKNOWN;
1933 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001934 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001935
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936 switch (getBestDataspace(displayDevice)) {
1937 case Dataspace::DISPLAY_P3:
1938 case Dataspace::V0_SCRGB_LINEAR:
1939 *outMode = ColorMode::DISPLAY_P3;
1940 *outDataSpace = Dataspace::DISPLAY_P3;
1941 break;
1942 default:
1943 *outMode = ColorMode::SRGB;
1944 *outDataSpace = Dataspace::V0_SRGB;
1945 break;
1946 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001947}
1948
Chia-I Wu30505fb2018-03-26 16:20:31 -07001949void SurfaceFlinger::setUpHWComposer() {
1950 ATRACE_CALL();
1951 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952
Jesse Hall028dc8f2013-08-20 16:35:32 -07001953 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001954 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001955 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1956 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1957
1958 // If nothing has changed (!dirty), don't recompose.
1959 // If something changed, but we don't currently have any visible layers,
1960 // and didn't when we last did a composition, then skip it this time.
1961 // The second rule does two things:
1962 // - When all layers are removed from a display, we'll emit one black
1963 // frame, then nothing more until we get new layers.
1964 // - When a display is created with a private layer stack, we won't
1965 // emit any black frames until a layer is added to the layer stack.
1966 bool mustRecompose = dirty && !(empty && wasEmpty);
1967
Dominik Laskowski281644e2018-04-19 15:47:35 -07001968 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001969 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1970 mustRecompose ? "doing" : "skipping",
1971 dirty ? "+" : "-",
1972 empty ? "+" : "-",
1973 wasEmpty ? "+" : "-");
1974
Dan Stoza71433162014-02-04 16:22:36 -08001975 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001976
1977 if (mustRecompose) {
1978 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1979 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001980 }
1981
Chia-I Wu30505fb2018-03-26 16:20:31 -07001982 // build the h/w work list
1983 if (CC_UNLIKELY(mGeometryInvalid)) {
1984 mGeometryInvalid = false;
1985 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1986 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1987 const auto hwcId = displayDevice->getHwcDisplayId();
1988 if (hwcId >= 0) {
1989 const Vector<sp<Layer>>& currentLayers(
1990 displayDevice->getVisibleLayersSortedByZ());
1991 for (size_t i = 0; i < currentLayers.size(); i++) {
1992 const auto& layer = currentLayers[i];
1993 if (!layer->hasHwcLayer(hwcId)) {
1994 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1995 layer->forceClientComposition(hwcId);
1996 continue;
1997 }
1998 }
1999
2000 layer->setGeometry(displayDevice, i);
2001 if (mDebugDisableHWC || mDebugRegion) {
2002 layer->forceClientComposition(hwcId);
2003 }
2004 }
2005 }
2006 }
2007 }
2008
2009
2010 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
2011
2012 // Set the per-frame data
2013 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2014 auto& displayDevice = mDisplays[displayId];
2015 const auto hwcId = displayDevice->getHwcDisplayId();
2016
2017 if (hwcId < 0) {
2018 continue;
2019 }
2020 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08002021 displayDevice->setColorTransform(colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002022 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
2023 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2024 "display %zd: %d", displayId, result);
2025 }
2026 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002027 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2028 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002029 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002030 layer->forceClientComposition(hwcId);
2031 }
2032
2033 if (layer->getForceClientComposition(hwcId)) {
2034 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2035 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2036 continue;
2037 }
2038
2039 layer->setPerFrameData(displayDevice);
2040 }
2041
2042 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002043 ColorMode colorMode;
2044 Dataspace dataSpace;
2045 pickColorMode(displayDevice, &colorMode, &dataSpace);
2046 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002047 }
2048 }
2049
2050 mPreviousColorMatrix = colorMatrix;
2051
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002053 auto& displayDevice = mDisplays[displayId];
2054 if (!displayDevice->isDisplayOn()) {
2055 continue;
2056 }
2057
David Sodman105b7dc2017-11-04 20:28:14 -07002058 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2060 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002061 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002062}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002063
Mathias Agopiancd60f992012-08-16 16:28:27 -07002064void SurfaceFlinger::doComposition() {
2065 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 ALOGV("doComposition");
2067
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002068 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002069 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002070 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002071 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002072 // transform the dirty region into this screen's coordinate space
2073 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002074
2075 // repaint the framebuffer (if needed)
2076 doDisplayComposition(hw, dirtyRegion);
2077
Mathias Agopiancd60f992012-08-16 16:28:27 -07002078 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002079 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002080 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002081 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002082 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002083}
2084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002085void SurfaceFlinger::postFramebuffer()
2086{
Mathias Agopian841cde52012-03-01 15:44:37 -08002087 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002089
Mathias Agopiana44b0412011-10-16 18:46:35 -07002090 const nsecs_t now = systemTime();
2091 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002092
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2094 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002095 if (!displayDevice->isDisplayOn()) {
2096 continue;
2097 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002098 const auto hwcId = displayDevice->getHwcDisplayId();
2099 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002100 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002101 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002102 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002103 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002105 // The layer buffer from the previous frame (if any) is released
2106 // by HWC only when the release fence from this frame (if any) is
2107 // signaled. Always get the release fence from HWC first.
2108 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002109 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002110
2111 // If the layer was client composited in the previous frame, we
2112 // need to merge with the previous client target acquire fence.
2113 // Since we do not track that, always merge with the current
2114 // client target acquire fence when it is available, even though
2115 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002117 releaseFence = Fence::merge("LayerRelease", releaseFence,
2118 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002119 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002120
David Sodmanb8af7922017-12-21 15:17:55 -08002121 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 }
Chia-I Wu83806892017-11-16 10:50:20 -08002123
2124 // We've got a list of layers needing fences, that are disjoint with
2125 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2126 // supply them with the present fence.
2127 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002128 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002129 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002130 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002131 }
2132 }
2133
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002135 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002136 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002137 }
2138
Mathias Agopiana44b0412011-10-16 18:46:35 -07002139 mLastSwapBufferTime = systemTime() - now;
2140 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002141
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002142 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002143 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2144 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2145 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2146 logFrameStats();
2147 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002148 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149}
2150
Mathias Agopian87baae12012-07-31 12:38:26 -07002151void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002152{
Mathias Agopian841cde52012-03-01 15:44:37 -08002153 ATRACE_CALL();
2154
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002155 // here we keep a copy of the drawing state (that is the state that's
2156 // going to be overwritten by handleTransactionLocked()) outside of
2157 // mStateLock so that the side-effects of the State assignment
2158 // don't happen with mStateLock held (which can cause deadlocks).
2159 State drawingState(mDrawingState);
2160
Mathias Agopianca4d3602011-05-19 15:38:14 -07002161 Mutex::Autolock _l(mStateLock);
2162 const nsecs_t now = systemTime();
2163 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164
Mathias Agopianca4d3602011-05-19 15:38:14 -07002165 // Here we're guaranteed that some transaction flags are set
2166 // so we can call handleTransactionLocked() unconditionally.
2167 // We call getTransactionFlags(), which will also clear the flags,
2168 // with mStateLock held to guarantee that mCurrentState won't change
2169 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002170
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002171 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002172 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002173 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002174
Mathias Agopianca4d3602011-05-19 15:38:14 -07002175 mLastTransactionTime = systemTime() - now;
2176 mDebugInTransaction = 0;
2177 invalidateHwcGeometry();
2178 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002179}
2180
Lloyd Pique715a2c12017-12-14 17:18:08 -08002181DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002182 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002183 // Figure out whether the event is for the primary display or an
2184 // external display by matching the Hwc display id against one for a
2185 // connected display. If we did not find a match, we then check what
2186 // displays are not already connected to determine the type. If we don't
2187 // have a connected primary display, we assume the new display is meant to
2188 // be the primary display, and then if we don't have an external display,
2189 // we assume it is that.
2190 const auto primaryDisplayId =
2191 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2192 const auto externalDisplayId =
2193 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2194 if (primaryDisplayId && primaryDisplayId == display) {
2195 return DisplayDevice::DISPLAY_PRIMARY;
2196 } else if (externalDisplayId && externalDisplayId == display) {
2197 return DisplayDevice::DISPLAY_EXTERNAL;
2198 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2199 return DisplayDevice::DISPLAY_PRIMARY;
2200 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2201 return DisplayDevice::DISPLAY_EXTERNAL;
2202 }
2203
2204 return DisplayDevice::DISPLAY_ID_INVALID;
2205}
2206
Lloyd Piqueba04e622017-12-14 17:11:26 -08002207void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2208 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002209 auto displayType = determineDisplayType(event.display, event.connection);
2210 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2211 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2212 continue;
2213 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002214
2215 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2216 ALOGE("External displays are not supported by the vr hardware composer.");
2217 continue;
2218 }
2219
Lloyd Pique715a2c12017-12-14 17:18:08 -08002220 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002221
2222 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002223 if (!mBuiltinDisplays[displayType].get()) {
2224 ALOGV("Creating built in display %d", displayType);
2225 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002226 DisplayDeviceState info;
2227 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002228 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2229 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002230 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002231 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2232 mInterceptor->saveDisplayCreation(info);
2233 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002235 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002236
Lloyd Piquefcd86612017-12-14 17:15:36 -08002237 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2238 if (idx >= 0) {
2239 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002240 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002241 mCurrentState.displays.removeItemsAt(idx);
2242 }
2243 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002244 }
2245
2246 processDisplayChangesLocked();
2247 }
2248
2249 mPendingHotplugEvents.clear();
2250}
2251
Lloyd Pique99d3da52018-01-22 17:48:03 -08002252sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2253 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2254 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255 bool hasWideColorGamut = false;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002256 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002258 for (ColorMode colorMode : modes) {
2259 switch (colorMode) {
2260 case ColorMode::DISPLAY_P3:
2261 case ColorMode::ADOBE_RGB:
2262 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002265 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique99d3da52018-01-22 17:48:03 -08002266 default:
2267 break;
2268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269
2270 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2271 colorMode);
2272 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2273 for (auto intent : renderIntents) {
2274 if (intent == RenderIntent::ENHANCE) {
2275 mBuiltinDisplaySupportsEnhance = true;
2276 break;
2277 }
2278 }
2279 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280 }
2281 }
2282
Peiyong Lin62665892018-04-16 11:07:44 -07002283 HdrCapabilities hdrCapabilities;
2284 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285
2286 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2287 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2288
2289 /*
2290 * Create our display's surface
2291 */
2292 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2293 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002294 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002295 renderSurface->setNativeWindow(nativeWindow.get());
2296 const int displayWidth = renderSurface->queryWidth();
2297 const int displayHeight = renderSurface->queryHeight();
2298
2299 // Make sure that composition can never be stalled by a virtual display
2300 // consumer that isn't processing buffers fast enough. We have to do this
2301 // in two places:
2302 // * Here, in case the display is composed entirely by HWC.
2303 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2304 // window's swap interval in eglMakeCurrent, so they'll override the
2305 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002306 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002307 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2308 }
2309
2310 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002311 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312
2313 sp<DisplayDevice> hw =
2314 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2315 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002316 hasWideColorGamut, hdrCapabilities,
2317 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2318 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319
2320 if (maxFrameBufferAcquiredBuffers >= 3) {
2321 nativeWindowSurface->preallocateBuffers();
2322 }
2323
2324 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2326 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 hw->setLayerStack(state.layerStack);
2332 hw->setProjection(state.orientation, state.viewport, state.frame);
2333 hw->setDisplayName(state.displayName);
2334
2335 return hw;
2336}
2337
Lloyd Pique347200f2017-12-14 17:00:15 -08002338void SurfaceFlinger::processDisplayChangesLocked() {
2339 // here we take advantage of Vector's copy-on-write semantics to
2340 // improve performance by skipping the transaction entirely when
2341 // know that the lists are identical
2342 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2343 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2344 if (!curr.isIdenticalTo(draw)) {
2345 mVisibleRegionsDirty = true;
2346 const size_t cc = curr.size();
2347 size_t dc = draw.size();
2348
2349 // find the displays that were removed
2350 // (ie: in drawing state but not in current state)
2351 // also handle displays that changed
2352 // (ie: displays that are in both lists)
2353 for (size_t i = 0; i < dc;) {
2354 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2355 if (j < 0) {
2356 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002357 // Call makeCurrent() on the primary display so we can
2358 // be sure that nothing associated with this display
2359 // is current.
2360 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2361 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2362 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2363 if (hw != nullptr) hw->disconnect(getHwComposer());
2364 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2365 mEventThread->onHotplugReceived(draw[i].type, false);
2366 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 } else {
2368 // this display is in both lists. see if something changed.
2369 const DisplayDeviceState& state(curr[j]);
2370 const wp<IBinder>& display(curr.keyAt(j));
2371 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2372 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2373 if (state_binder != draw_binder) {
2374 // changing the surface is like destroying and
2375 // recreating the DisplayDevice, so we just remove it
2376 // from the drawing state, so that it get re-added
2377 // below.
2378 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2379 if (hw != nullptr) hw->disconnect(getHwComposer());
2380 mDisplays.removeItem(display);
2381 mDrawingState.displays.removeItemsAt(i);
2382 dc--;
2383 // at this point we must loop to the next item
2384 continue;
2385 }
2386
2387 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2388 if (disp != nullptr) {
2389 if (state.layerStack != draw[i].layerStack) {
2390 disp->setLayerStack(state.layerStack);
2391 }
2392 if ((state.orientation != draw[i].orientation) ||
2393 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2394 disp->setProjection(state.orientation, state.viewport, state.frame);
2395 }
2396 if (state.width != draw[i].width || state.height != draw[i].height) {
2397 disp->setDisplaySize(state.width, state.height);
2398 }
2399 }
2400 }
2401 ++i;
2402 }
2403
2404 // find displays that were added
2405 // (ie: in current state but not in drawing state)
2406 for (size_t i = 0; i < cc; i++) {
2407 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2408 const DisplayDeviceState& state(curr[i]);
2409
2410 sp<DisplaySurface> dispSurface;
2411 sp<IGraphicBufferProducer> producer;
2412 sp<IGraphicBufferProducer> bqProducer;
2413 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002414 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002415
2416 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002417 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002418 // Virtual displays without a surface are dormant:
2419 // they have external state (layer stack, projection,
2420 // etc.) but no internal state (i.e. a DisplayDevice).
2421 if (state.surface != nullptr) {
2422 // Allow VR composer to use virtual displays.
2423 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2424 int width = 0;
2425 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2426 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2427 int height = 0;
2428 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2429 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2430 int intFormat = 0;
2431 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2432 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002433 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002434
2435 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2436 }
2437
2438 // TODO: Plumb requested format back up to consumer
2439
2440 sp<VirtualDisplaySurface> vds =
2441 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2442 bqProducer, bqConsumer,
2443 state.displayName);
2444
2445 dispSurface = vds;
2446 producer = vds;
2447 }
2448 } else {
2449 ALOGE_IF(state.surface != nullptr,
2450 "adding a supported display, but rendering "
2451 "surface is provided (%p), ignoring it",
2452 state.surface.get());
2453
2454 hwcId = state.type;
2455 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2456 producer = bqProducer;
2457 }
2458
2459 const wp<IBinder>& display(curr.keyAt(i));
2460 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461 mDisplays.add(display,
2462 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2463 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002464 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 mEventThread->onHotplugReceived(state.type, true);
2466 }
2467 }
2468 }
2469 }
2470 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002471
2472 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002473}
2474
Mathias Agopian87baae12012-07-31 12:38:26 -07002475void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002476{
Dan Stoza7dde5992015-05-22 09:51:44 -07002477 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002478 mCurrentState.traverseInZOrder([](Layer* layer) {
2479 layer->notifyAvailableFrames();
2480 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002481
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 /*
2483 * Traversal of the children
2484 * (perform the transaction for each of them if needed)
2485 */
2486
Mathias Agopian3559b072012-08-15 13:46:03 -07002487 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002488 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002490 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491
2492 const uint32_t flags = layer->doTransaction(0);
2493 if (flags & Layer::eVisibleRegion)
2494 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002495 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496 }
2497
2498 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002499 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 */
2501
Mathias Agopiane57f2922012-08-09 16:29:12 -07002502 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002504 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002507 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002508 // The transform hint might have changed for some layers
2509 // (either because a display has changed, or because a layer
2510 // as changed).
2511 //
2512 // Walk through all the layers in currentLayers,
2513 // and update their transform hint.
2514 //
2515 // If a layer is visible only on a single display, then that
2516 // display is used to calculate the hint, otherwise we use the
2517 // default display.
2518 //
2519 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2520 // the hint is set before we acquire a buffer from the surface texture.
2521 //
2522 // NOTE: layer transactions have taken place already, so we use their
2523 // drawing state. However, SurfaceFlinger's own transaction has not
2524 // happened yet, so we must use the current state layer list
2525 // (soon to become the drawing state list).
2526 //
2527 sp<const DisplayDevice> disp;
2528 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002529 bool first = true;
2530 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002531 // NOTE: we rely on the fact that layers are sorted by
2532 // layerStack first (so we don't have to traverse the list
2533 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002534 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002535 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002536 currentlayerStack = layerStack;
2537 // figure out if this layerstack is mirrored
2538 // (more than one display) if so, pick the default display,
2539 // if not, pick the only display it's on.
2540 disp.clear();
2541 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2542 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002543 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002544 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002545 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002546 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002547 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002548 break;
2549 }
2550 }
2551 }
2552 }
Chet Haase91d25932013-04-11 15:24:55 -07002553
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002554 if (disp == nullptr) {
2555 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2556 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002557
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002558 // could be null when this layer is using a layerStack
2559 // that is not visible on any display. Also can occur at
2560 // screen off/on times.
2561 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002562 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002563
2564 // disp can be null if there is no display available at all to get
2565 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002566 if (disp != nullptr) {
2567 layer->updateTransformHint(disp);
2568 }
Robert Carr2047fae2016-11-28 14:09:09 -08002569
2570 first = false;
2571 });
Mathias Agopian84300952012-11-21 16:02:13 -08002572 }
2573
2574
Mathias Agopian3559b072012-08-15 13:46:03 -07002575 /*
2576 * Perform our own transaction if needed
2577 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578
2579 if (mLayersAdded) {
2580 mLayersAdded = false;
2581 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 mVisibleRegionsDirty = true;
2583 }
2584
2585 // some layers might have been removed, so
2586 // we need to update the regions they're exposing.
2587 if (mLayersRemoved) {
2588 mLayersRemoved = false;
2589 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002590 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002592 // this layer is not visible anymore
2593 // TODO: we could traverse the tree from front to back and
2594 // compute the actual visible region
2595 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002596 Region visibleReg;
2597 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002598 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002599 }
Robert Carr2047fae2016-11-28 14:09:09 -08002600 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 }
2602
2603 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002604
2605 updateCursorAsync();
2606}
2607
2608void SurfaceFlinger::updateCursorAsync()
2609{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2611 auto& displayDevice = mDisplays[displayId];
2612 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002613 continue;
2614 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002615
2616 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2617 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002618 }
2619 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002620}
2621
2622void SurfaceFlinger::commitTransaction()
2623{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002624 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002625 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 for (const auto& l : mLayersPendingRemoval) {
2627 recordBufferingStats(l->getName().string(),
2628 l->getOccupancyHistory(true));
2629 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002630 }
2631 mLayersPendingRemoval.clear();
2632 }
2633
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002634 // If this transaction is part of a window animation then the next frame
2635 // we composite should be considered an animation as well.
2636 mAnimCompositionPending = mAnimTransactionPending;
2637
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 mDrawingState.traverseInZOrder([](Layer* layer) {
2640 layer->commitChildList();
2641 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002642 mTransactionPending = false;
2643 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002644 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645}
2646
Chia-I Wuab0c3192017-08-01 11:29:00 -07002647void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002648 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649{
Mathias Agopian841cde52012-03-01 15:44:37 -08002650 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002652
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653 Region aboveOpaqueLayers;
2654 Region aboveCoveredLayers;
2655 Region dirty;
2656
Mathias Agopian87baae12012-07-31 12:38:26 -07002657 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658
Robert Carr2047fae2016-11-28 14:09:09 -08002659 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002661 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Jesse Hall01e29052013-02-19 16:13:35 -08002663 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002664 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002665 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002666
Mathias Agopianab028732010-03-16 16:41:46 -07002667 /*
2668 * opaqueRegion: area of a surface that is fully opaque.
2669 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002671
2672 /*
2673 * visibleRegion: area of a surface that is visible on screen
2674 * and not fully transparent. This is essentially the layer's
2675 * footprint minus the opaque regions above it.
2676 * Areas covered by a translucent surface are considered visible.
2677 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002679
2680 /*
2681 * coveredRegion: area of a surface that is covered by all
2682 * visible regions above it (which includes the translucent areas).
2683 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002685
Jesse Halla8026d22012-09-25 13:25:04 -07002686 /*
2687 * transparentRegion: area of a surface that is hinted to be completely
2688 * transparent. This is only used to tell when the layer has no visible
2689 * non-transparent regions and can be removed from the layer list. It
2690 * does not affect the visibleRegion of this layer or any layers
2691 * beneath it. The hint may not be correct if apps don't respect the
2692 * SurfaceView restrictions (which, sadly, some don't).
2693 */
2694 Region transparentRegion;
2695
Mathias Agopianab028732010-03-16 16:41:46 -07002696
2697 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002698 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002699 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002700 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002702 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002703 if (!visibleRegion.isEmpty()) {
2704 // Remove the transparent area from the visible region
2705 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002706 if (tr.preserveRects()) {
2707 // transform the transparent region
2708 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002710 // transformation too complex, can't do the
2711 // transparent region optimization.
2712 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 }
Mathias Agopianab028732010-03-16 16:41:46 -07002714 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715
Mathias Agopianab028732010-03-16 16:41:46 -07002716 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002718 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002719 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2720 // the opaque region is the layer's footprint
2721 opaqueRegion = visibleRegion;
2722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723 }
2724 }
2725
Robert Carre5f4f692018-01-12 13:12:28 -08002726 if (visibleRegion.isEmpty()) {
2727 layer->clearVisibilityRegions();
2728 return;
2729 }
2730
Mathias Agopianab028732010-03-16 16:41:46 -07002731 // Clip the covered region to the visible region
2732 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2733
2734 // Update aboveCoveredLayers for next (lower) layer
2735 aboveCoveredLayers.orSelf(visibleRegion);
2736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 // subtract the opaque region covered by the layers above us
2738 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739
2740 // compute this layer's dirty region
2741 if (layer->contentDirty) {
2742 // we need to invalidate the whole region
2743 dirty = visibleRegion;
2744 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002745 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746 layer->contentDirty = false;
2747 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002748 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002749 * the exposed region consists of two components:
2750 * 1) what's VISIBLE now and was COVERED before
2751 * 2) what's EXPOSED now less what was EXPOSED before
2752 *
2753 * note that (1) is conservative, we start with the whole
2754 * visible region but only keep what used to be covered by
2755 * something -- which mean it may have been exposed.
2756 *
2757 * (2) handles areas that were not covered by anything but got
2758 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002759 */
Mathias Agopianab028732010-03-16 16:41:46 -07002760 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002761 const Region oldVisibleRegion = layer->visibleRegion;
2762 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002763 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2764 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 }
2766 dirty.subtractSelf(aboveOpaqueLayers);
2767
2768 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002769 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770
Mathias Agopianab028732010-03-16 16:41:46 -07002771 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002773
Jesse Halla8026d22012-09-25 13:25:04 -07002774 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 layer->setVisibleRegion(visibleRegion);
2776 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002777 layer->setVisibleNonTransparentRegion(
2778 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002779 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780
Mathias Agopian87baae12012-07-31 12:38:26 -07002781 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782}
2783
Chia-I Wuab0c3192017-08-01 11:29:00 -07002784void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002785 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002786 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002787 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002788 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002789 }
2790 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002791}
2792
Dan Stoza6b9454d2014-11-07 16:00:59 -08002793bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 ALOGV("handlePageFlip");
2796
Brian Andersond6927fb2016-07-23 23:37:30 -07002797 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002800 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002801 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002802
2803 // Store the set of layers that need updates. This set must not change as
2804 // buffers are being latched, as this could result in a deadlock.
2805 // Example: Two producers share the same command stream and:
2806 // 1.) Layer 0 is latched
2807 // 2.) Layer 0 gets a new frame
2808 // 2.) Layer 1 gets a new frame
2809 // 3.) Layer 1 is latched.
2810 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2811 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002812 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002813 if (layer->hasQueuedFrame()) {
2814 frameQueued = true;
2815 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002816 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002817 } else {
2818 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002819 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002820 } else {
2821 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002822 }
Robert Carr2047fae2016-11-28 14:09:09 -08002823 });
2824
Dan Stoza9e56aa02015-11-02 13:00:03 -08002825 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002826 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002827 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002828 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002829 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002830 newDataLatched = true;
2831 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002832 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002833
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002834 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835
2836 // If we will need to wake up at some time in the future to deal with a
2837 // queued frame that shouldn't be displayed during this vsync period, wake
2838 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002839 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002840 signalLayerUpdate();
2841 }
2842
2843 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002844 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845}
2846
Mathias Agopianad456f92011-01-13 17:53:01 -08002847void SurfaceFlinger::invalidateHwcGeometry()
2848{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002850}
2851
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002852
Fabien Sanglard830b8472016-11-30 16:35:58 -08002853void SurfaceFlinger::doDisplayComposition(
2854 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002855 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856{
Dan Stoza71433162014-02-04 16:22:36 -08002857 // We only need to actually compose the display if:
2858 // 1) It is being handled by hardware composer, which may need this to
2859 // keep its virtual display state machine in sync, or
2860 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002861 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002862 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002863 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002864 return;
2865 }
2866
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002868 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002869
2870 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002871 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Chia-I Wub02087d2017-11-09 10:19:54 -08002874bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002875{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002877
Chia-I Wub02087d2017-11-09 10:19:54 -08002878 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002879 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002881 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2882 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2883 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2884 HWC2::Capability::SkipClientColorTransform);
2885 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002886
2887 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002888 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2889 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002890 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002891 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002892 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002893 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002894 }
2895
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 if (hasClientComposition) {
2897 ALOGV("hasClientComposition");
2898
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002899 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002900 if (displayDevice->hasWideColorGamut()) {
2901 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002902 }
2903 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2904
Chia-I Wu7f402902017-11-09 12:51:10 -08002905 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002906 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002907 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002908 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002909
2910 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002911 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002912 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2913 }
2914 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002915 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002916
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002917 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002919 // when using overlays, we assume a fully transparent framebuffer
2920 // NOTE: we could reduce how much we need to clear, for instance
2921 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002922 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002923 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002924 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002925 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002926 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002927 // we're left with the letterbox region
2928 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002930
2931 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002933
Mathias Agopianb9494d52012-04-18 02:28:45 -07002934 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002935 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002936 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002938 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002939 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002940
Dominik Laskowski281644e2018-04-19 15:47:35 -07002941 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002942 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002943 // scissor on the main display. It should never be needed
2944 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 const Rect& bounds(displayDevice->getBounds());
2946 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002947 if (scissor != bounds) {
2948 // scissor doesn't match the screen's dimensions, so we
2949 // need to clear everything outside of it and enable
2950 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002951
Mathias Agopianf45c5102012-10-24 16:29:17 -07002952 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002954 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002955 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002956 }
2957 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002958 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002959
Mathias Agopian85d751c2012-08-29 16:59:24 -07002960 /*
2961 * and then, render the layers targeted at the framebuffer
2962 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002963
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964 ALOGV("Rendering client layers");
2965 const Transform& displayTransform = displayDevice->getTransform();
2966 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002967 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 bool firstLayer = true;
2969 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002970 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002971 displayTransform.transform(layer->visibleRegion)));
2972 ALOGV("Layer: %s", layer->getName().string());
2973 ALOGV(" Composition type: %s",
2974 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002975 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 switch (layer->getCompositionType(hwcId)) {
2977 case HWC2::Composition::Cursor:
2978 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002979 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002981 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002983 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002984 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002985 // never clear the very first layer since we're
2986 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002987 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002988 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002989 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002990 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002992 // Only apply saturation matrix layer that is legacy SRGB dataspace
2993 // when auto color mode is on.
2994 bool restore = false;
2995 mat4 savedMatrix;
2996 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2997 layer->isLegacySrgbDataSpace()) {
2998 savedMatrix =
2999 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3000 restore = true;
3001 }
chaviwa76b2712017-09-20 12:02:26 -07003002 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003003 if (restore) {
3004 getRenderEngine().setupColorTransform(savedMatrix);
3005 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003006 break;
3007 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003009 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003010 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003011 } else {
3012 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003013 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003015 }
3016 } else {
3017 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003019 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003020 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003021 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003022 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003023 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003024 }
3025 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003026
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003027 if (applyColorMatrix) {
3028 getRenderEngine().setupColorTransform(oldColorMatrix);
3029 }
3030
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003032 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003033 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034}
3035
Fabien Sanglard830b8472016-11-30 16:35:58 -08003036void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3037 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003038 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003039 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040}
3041
Dan Stoza7d89d062015-04-30 13:29:25 -07003042status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003043 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003044 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 const sp<Layer>& lbc,
3046 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003047{
Dan Stoza7d89d062015-04-30 13:29:25 -07003048 // add this layer to the current state list
3049 {
3050 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003051 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003052 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3053 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003054 return NO_MEMORY;
3055 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003056 if (parent == nullptr) {
3057 mCurrentState.layersSortedByZ.add(lbc);
3058 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003059 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003060 ALOGE("addClientLayer called with a removed parent");
3061 return NAME_NOT_FOUND;
3062 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 parent->addChild(lbc);
3064 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003065
Dan Stoza101d8dc2018-02-27 15:42:25 -08003066 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003067 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3068 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3069 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3070 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3071 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003072 mLayersAdded = true;
3073 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003074 }
3075
Mathias Agopian96f08192010-06-02 23:28:45 -07003076 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003077 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003078
Dan Stoza7d89d062015-04-30 13:29:25 -07003079 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003080}
3081
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003082status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003083 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003084 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3085}
Robert Carr7f9b8992017-03-10 11:08:39 -08003086
chaviwca27f252018-02-06 16:46:39 -08003087status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3088 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003089 if (layer->isPendingRemoval()) {
3090 return NO_ERROR;
3091 }
3092
Robert Carr1f0a16a2016-10-24 16:27:39 -07003093 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003094 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003095 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003096 if (topLevelOnly) {
3097 return NO_ERROR;
3098 }
3099
Chia-I Wu98f1c102017-05-30 14:54:08 -07003100 sp<Layer> ancestor = p;
3101 while (ancestor->getParent() != nullptr) {
3102 ancestor = ancestor->getParent();
3103 }
3104 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3105 ALOGE("removeLayer called with a layer whose parent has been removed");
3106 return NAME_NOT_FOUND;
3107 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003108
3109 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003110 } else {
3111 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003112 }
3113
Robert Carr136e2f62017-02-08 17:54:29 -08003114 // As a matter of normal operation, the LayerCleaner will produce a second
3115 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3116 // so we will succeed in promoting it, but it's already been removed
3117 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3118 // otherwise something has gone wrong and we are leaking the layer.
3119 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003120 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3121 layer->getName().string(),
3122 (p != nullptr) ? p->getName().string() : "no-parent");
3123 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003124 } else if (index < 0) {
3125 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003126 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127
Chia-I Wuc6657022017-08-15 11:18:17 -07003128 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003129 mLayersPendingRemoval.add(layer);
3130 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003131 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003132 setTransactionFlags(eTransactionNeeded);
3133 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003136uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003137 return android_atomic_release_load(&mTransactionFlags);
3138}
3139
Mathias Agopian3f844832013-08-07 21:24:32 -07003140uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3142}
3143
Mathias Agopian3f844832013-08-07 21:24:32 -07003144uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003145 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3146}
3147
3148uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3149 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003151 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003153 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 }
3155 return old;
3156}
3157
chaviwca27f252018-02-06 16:46:39 -08003158bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3159 for (const ComposerState& state : states) {
3160 // Here we need to check that the interface we're given is indeed
3161 // one of our own. A malicious client could give us a nullptr
3162 // IInterface, or one of its own or even one of our own but a
3163 // different type. All these situations would cause us to crash.
3164 if (state.client == nullptr) {
3165 return true;
3166 }
3167
3168 sp<IBinder> binder = IInterface::asBinder(state.client);
3169 if (binder == nullptr) {
3170 return true;
3171 }
3172
3173 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3174 return true;
3175 }
3176 }
3177 return false;
3178}
3179
Mathias Agopian8b33f032012-07-24 20:43:54 -07003180void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003181 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003182 const Vector<DisplayState>& displays,
3183 uint32_t flags)
3184{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003185 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003186 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003187 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003188
chaviwca27f252018-02-06 16:46:39 -08003189 if (containsAnyInvalidClientState(states)) {
3190 return;
3191 }
3192
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003193 if (flags & eAnimation) {
3194 // For window updates that are part of an animation we must wait for
3195 // previous animation "frames" to be handled.
3196 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003197 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003198 if (CC_UNLIKELY(err != NO_ERROR)) {
3199 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003200 // caller after a few seconds.
3201 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3202 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003203 mAnimTransactionPending = false;
3204 break;
3205 }
3206 }
3207 }
3208
chaviwca27f252018-02-06 16:46:39 -08003209 for (const DisplayState& display : displays) {
3210 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003211 }
3212
chaviwca27f252018-02-06 16:46:39 -08003213 for (const ComposerState& state : states) {
3214 transactionFlags |= setClientStateLocked(state);
3215 }
3216
3217 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3218 // as destroyed should only occur after setting all other states. This is to allow for a
3219 // child re-parent to happen before marking its original parent as destroyed (which would
3220 // then mark the child as destroyed).
3221 for (const ComposerState& state : states) {
3222 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003223 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003224
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003225 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3226 // anyway. This can be used as a flush mechanism for previous async transactions.
3227 // Empty animation transaction can be used to simulate back-pressure, so also force a
3228 // transaction for empty animation transactions.
3229 if (transactionFlags == 0 &&
3230 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003231 transactionFlags = eTransactionNeeded;
3232 }
3233
Mathias Agopian386aa982011-11-07 21:58:03 -08003234 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003235 if (mInterceptor->isEnabled()) {
3236 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003237 }
Irvel468051e2016-06-13 16:44:44 -07003238
Mathias Agopian386aa982011-11-07 21:58:03 -08003239 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003240 const auto start = (flags & eEarlyWakeup)
3241 ? VSyncModulator::TransactionStart::EARLY
3242 : VSyncModulator::TransactionStart::NORMAL;
3243 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003244
3245 // if this is a synchronous transaction, wait for it to take effect
3246 // before returning.
3247 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003248 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003249 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003250 if (flags & eAnimation) {
3251 mAnimTransactionPending = true;
3252 }
3253 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003254 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3255 if (CC_UNLIKELY(err != NO_ERROR)) {
3256 // just in case something goes wrong in SF, return to the
3257 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003258 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3259 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003260 break;
3261 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003262 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263 }
3264}
3265
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3267{
Jesse Hall9a143922012-10-04 16:29:19 -07003268 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3269 if (dpyIdx < 0)
3270 return 0;
3271
Mathias Agopiane57f2922012-08-09 16:29:12 -07003272 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003273 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003274 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003275 const uint32_t what = s.what;
3276 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003277 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003278 disp.surface = s.surface;
3279 flags |= eDisplayTransactionNeeded;
3280 }
3281 }
3282 if (what & DisplayState::eLayerStackChanged) {
3283 if (disp.layerStack != s.layerStack) {
3284 disp.layerStack = s.layerStack;
3285 flags |= eDisplayTransactionNeeded;
3286 }
3287 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003288 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289 if (disp.orientation != s.orientation) {
3290 disp.orientation = s.orientation;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 if (disp.frame != s.frame) {
3294 disp.frame = s.frame;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 if (disp.viewport != s.viewport) {
3298 disp.viewport = s.viewport;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 }
Michael Lentine47e45402014-07-18 15:34:25 -07003302 if (what & DisplayState::eDisplaySizeChanged) {
3303 if (disp.width != s.width) {
3304 disp.width = s.width;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 if (disp.height != s.height) {
3308 disp.height = s.height;
3309 flags |= eDisplayTransactionNeeded;
3310 }
3311 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003312 }
3313 return flags;
3314}
3315
chaviwca27f252018-02-06 16:46:39 -08003316uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3317 const layer_state_t& s = composerState.state;
3318 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3319
Mathias Agopian13127d82013-03-05 17:47:11 -08003320 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003321 if (layer == nullptr) {
3322 return 0;
3323 }
3324
3325 if (layer->isPendingRemoval()) {
3326 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3327 return 0;
3328 }
3329
3330 uint32_t flags = 0;
3331
3332 const uint32_t what = s.what;
3333 bool geometryAppliesWithResize =
3334 what & layer_state_t::eGeometryAppliesWithResize;
3335 if (what & layer_state_t::ePositionChanged) {
3336 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3337 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003338 }
chaviw8b3871a2017-11-01 17:41:01 -07003339 }
3340 if (what & layer_state_t::eLayerChanged) {
3341 // NOTE: index needs to be calculated before we update the state
3342 const auto& p = layer->getParent();
3343 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003344 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003345 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003346 mCurrentState.layersSortedByZ.removeAt(idx);
3347 mCurrentState.layersSortedByZ.add(layer);
3348 // we need traversal (state changed)
3349 // AND transaction (list changed)
3350 flags |= eTransactionNeeded|eTraversalNeeded;
3351 }
chaviw8b3871a2017-11-01 17:41:01 -07003352 } else {
3353 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003354 flags |= eTransactionNeeded|eTraversalNeeded;
3355 }
3356 }
chaviw8b3871a2017-11-01 17:41:01 -07003357 }
3358 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003359 // NOTE: index needs to be calculated before we update the state
3360 const auto& p = layer->getParent();
3361 if (p == nullptr) {
3362 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3363 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3364 mCurrentState.layersSortedByZ.removeAt(idx);
3365 mCurrentState.layersSortedByZ.add(layer);
3366 // we need traversal (state changed)
3367 // AND transaction (list changed)
3368 flags |= eTransactionNeeded|eTraversalNeeded;
3369 }
3370 } else {
3371 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3372 flags |= eTransactionNeeded|eTraversalNeeded;
3373 }
chaviw8b3871a2017-11-01 17:41:01 -07003374 }
3375 }
3376 if (what & layer_state_t::eSizeChanged) {
3377 if (layer->setSize(s.w, s.h)) {
3378 flags |= eTraversalNeeded;
3379 }
3380 }
3381 if (what & layer_state_t::eAlphaChanged) {
3382 if (layer->setAlpha(s.alpha))
3383 flags |= eTraversalNeeded;
3384 }
3385 if (what & layer_state_t::eColorChanged) {
3386 if (layer->setColor(s.color))
3387 flags |= eTraversalNeeded;
3388 }
3389 if (what & layer_state_t::eMatrixChanged) {
3390 if (layer->setMatrix(s.matrix))
3391 flags |= eTraversalNeeded;
3392 }
3393 if (what & layer_state_t::eTransparentRegionChanged) {
3394 if (layer->setTransparentRegionHint(s.transparentRegion))
3395 flags |= eTraversalNeeded;
3396 }
3397 if (what & layer_state_t::eFlagsChanged) {
3398 if (layer->setFlags(s.flags, s.mask))
3399 flags |= eTraversalNeeded;
3400 }
3401 if (what & layer_state_t::eCropChanged) {
3402 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3403 flags |= eTraversalNeeded;
3404 }
3405 if (what & layer_state_t::eFinalCropChanged) {
3406 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3407 flags |= eTraversalNeeded;
3408 }
3409 if (what & layer_state_t::eLayerStackChanged) {
3410 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3411 // We only allow setting layer stacks for top level layers,
3412 // everything else inherits layer stack from its parent.
3413 if (layer->hasParent()) {
3414 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3415 layer->getName().string());
3416 } else if (idx < 0) {
3417 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3418 "that also does not appear in the top level layer list. Something"
3419 " has gone wrong.", layer->getName().string());
3420 } else if (layer->setLayerStack(s.layerStack)) {
3421 mCurrentState.layersSortedByZ.removeAt(idx);
3422 mCurrentState.layersSortedByZ.add(layer);
3423 // we need traversal (state changed)
3424 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003425 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003426 }
3427 }
3428 if (what & layer_state_t::eDeferTransaction) {
3429 if (s.barrierHandle != nullptr) {
3430 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3431 } else if (s.barrierGbp != nullptr) {
3432 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3433 if (authenticateSurfaceTextureLocked(gbp)) {
3434 const auto& otherLayer =
3435 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3436 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3437 } else {
3438 ALOGE("Attempt to defer transaction to to an"
3439 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003440 }
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 // We don't trigger a traversal here because if no other state is
3443 // changed, we don't want this to cause any more work
3444 }
3445 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003446 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003447 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003448 if (!hadParent) {
3449 mCurrentState.layersSortedByZ.remove(layer);
3450 }
chaviw8b3871a2017-11-01 17:41:01 -07003451 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 }
3454 if (what & layer_state_t::eReparentChildren) {
3455 if (layer->reparentChildren(s.reparentHandle)) {
3456 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003457 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003458 }
chaviw8b3871a2017-11-01 17:41:01 -07003459 if (what & layer_state_t::eDetachChildren) {
3460 layer->detachChildren();
3461 }
3462 if (what & layer_state_t::eOverrideScalingModeChanged) {
3463 layer->setOverrideScalingMode(s.overrideScalingMode);
3464 // We don't trigger a traversal here because if no other state is
3465 // changed, we don't want this to cause any more work
3466 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003467 return flags;
3468}
3469
chaviwca27f252018-02-06 16:46:39 -08003470void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3471 const layer_state_t& state = composerState.state;
3472 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3473
3474 sp<Layer> layer(client->getLayerUser(state.surface));
3475 if (layer == nullptr) {
3476 return;
3477 }
3478
3479 if (layer->isPendingRemoval()) {
3480 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3481 return;
3482 }
3483
3484 if (state.what & layer_state_t::eDestroySurface) {
3485 removeLayerLocked(mStateLock, layer);
3486 }
3487}
3488
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003489status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003490 const String8& name,
3491 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003492 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003493 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003494 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003496 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003497 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003498 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003499 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003500 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003501
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003502 status_t result = NO_ERROR;
3503
3504 sp<Layer> layer;
3505
Cody Northropbc755282017-03-31 12:00:08 -06003506 String8 uniqueName = getUniqueLayerName(name);
3507
Mathias Agopian3165cc22012-08-08 19:42:09 -07003508 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3509 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003510 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003511 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003512 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003513
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 break;
chaviw13fdc492017-06-27 12:40:18 -07003515 case ISurfaceComposerClient::eFXSurfaceColor:
3516 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003517 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003518 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 break;
3520 default:
3521 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 break;
3523 }
3524
Dan Stoza7d89d062015-04-30 13:29:25 -07003525 if (result != NO_ERROR) {
3526 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003528
Chia-I Wuab0c3192017-08-01 11:29:00 -07003529 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3530 // TODO b/64227542
3531 if (windowType == 441731) {
3532 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3533 layer->setPrimaryDisplayOnly();
3534 }
3535
Albert Chaulk479c60c2017-01-27 14:21:34 -05003536 layer->setInfo(windowType, ownerUid);
3537
Robert Carr1f0a16a2016-10-24 16:27:39 -07003538 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003539 if (result != NO_ERROR) {
3540 return result;
3541 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003542 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003543
3544 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546}
3547
Cody Northropbc755282017-03-31 12:00:08 -06003548String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3549{
3550 bool matchFound = true;
3551 uint32_t dupeCounter = 0;
3552
3553 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3554 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3555
3556 // Loop over layers until we're sure there is no matching name
3557 while (matchFound) {
3558 matchFound = false;
3559 mDrawingState.traverseInZOrder([&](Layer* layer) {
3560 if (layer->getName() == uniqueName) {
3561 matchFound = true;
3562 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3563 }
3564 });
3565 }
3566
3567 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3568
3569 return uniqueName;
3570}
3571
David Sodman0c69cad2017-08-21 12:12:51 -07003572status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003573 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3574 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575{
3576 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003577 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578 case PIXEL_FORMAT_TRANSPARENT:
3579 case PIXEL_FORMAT_TRANSLUCENT:
3580 format = PIXEL_FORMAT_RGBA_8888;
3581 break;
3582 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003583 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 break;
3585 }
3586
David Sodman0c69cad2017-08-21 12:12:51 -07003587 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3588 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003590 *handle = layer->getHandle();
3591 *gbp = layer->getProducer();
3592 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594
David Sodman0c69cad2017-08-21 12:12:51 -07003595 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003596 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597}
3598
chaviw13fdc492017-06-27 12:40:18 -07003599status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003600 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003601 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602{
chaviw13fdc492017-06-27 12:40:18 -07003603 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003604 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003606}
3607
Mathias Agopianac9fa422013-02-11 16:40:36 -08003608status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609{
Robert Carr9524cb32017-02-13 11:32:32 -08003610 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003611 status_t err = NO_ERROR;
3612 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003613 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003614 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003615 err = removeLayer(l);
3616 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3617 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003618 }
3619 return err;
3620}
3621
Mathias Agopian13127d82013-03-05 17:47:11 -08003622status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003623{
Mathias Agopian67106042013-03-14 19:18:13 -07003624 // called by ~LayerCleaner() when all references to the IBinder (handle)
3625 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003626 sp<Layer> l = layer.promote();
3627 if (l == nullptr) {
3628 // The layer has already been removed, carry on
3629 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003630 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003631 // If we have a parent, then we can continue to live as long as it does.
3632 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633}
3634
Mathias Agopianb60314a2012-04-10 22:09:54 -07003635// ---------------------------------------------------------------------------
3636
Andy McFadden13a082e2012-08-24 10:16:42 -07003637void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003638 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003639 Vector<ComposerState> state;
3640 Vector<DisplayState> displays;
3641 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003642 d.what = DisplayState::eDisplayProjectionChanged |
3643 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003644 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003645 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003646 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003647 d.frame.makeInvalid();
3648 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003649 d.width = 0;
3650 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003651 displays.add(d);
3652 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003653 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3654 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003655
David Sodman105b7dc2017-11-04 20:28:14 -07003656 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003657 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003658 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003659
Brian Andersond0010582017-03-07 13:20:31 -08003660 // Use phase of 0 since phase is not known.
3661 // Use latency of 0, which will snap to the ideal latency.
3662 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003663}
3664
3665void SurfaceFlinger::initializeDisplays() {
3666 class MessageScreenInitialized : public MessageBase {
3667 SurfaceFlinger* flinger;
3668 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003669 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003670 virtual bool handler() {
3671 flinger->onInitializeDisplays();
3672 return true;
3673 }
3674 };
3675 sp<MessageBase> msg = new MessageScreenInitialized(this);
3676 postMessageAsync(msg); // we may be called from main thread, use async message
3677}
3678
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003679void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003680 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003681 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3682 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003683 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003684
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003685 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003686 return;
3687 }
3688
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003689 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003690 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 ALOGW("Trying to set power mode for virtual display");
3692 return;
3693 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003694
Lloyd Pique4dccc412018-01-22 17:21:36 -08003695 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003696 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003697 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3698 if (idx < 0) {
3699 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3700 return;
3701 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003702 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003703 }
3704
Dominik Laskowski281644e2018-04-19 15:47:35 -07003705 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003707 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003708 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003709 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003710 // FIXME: eventthread only knows about the main display right now
3711 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003712 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003715 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003716 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003717 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003718
3719 struct sched_param param = {0};
3720 param.sched_priority = 1;
3721 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3722 ALOGW("Couldn't set SCHED_FIFO on display on");
3723 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003724 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003725 // Turn off the display
3726 struct sched_param param = {0};
3727 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3728 ALOGW("Couldn't set SCHED_OTHER on display off");
3729 }
3730
Dominik Laskowski281644e2018-04-19 15:47:35 -07003731 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003732 disableHardwareVsync(true); // also cancels any in-progress resync
3733
Mathias Agopiancde87a32012-09-13 14:09:01 -07003734 // FIXME: eventthread only knows about the main display right now
3735 mEventThread->onScreenReleased();
3736 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003737
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003738 getHwComposer().setPowerMode(type, mode);
3739 mVisibleRegionsDirty = true;
3740 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003741 } else if (mode == HWC_POWER_MODE_DOZE ||
3742 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003743 // Update display while dozing
3744 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003745 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003746 // FIXME: eventthread only knows about the main display right now
3747 mEventThread->onScreenAcquired();
3748 resyncToHardwareVsync(true);
3749 }
3750 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3751 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003752 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003753 disableHardwareVsync(true); // also cancels any in-progress resync
3754 // FIXME: eventthread only knows about the main display right now
3755 mEventThread->onScreenReleased();
3756 }
3757 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003759 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003760 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003761 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003762 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003763}
3764
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3766 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003767 SurfaceFlinger& mFlinger;
3768 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003770 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 MessageSetPowerMode(SurfaceFlinger& flinger,
3772 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3773 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003776 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003778 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003779 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 ALOGW("Attempt to set power mode = %d for virtual display",
3781 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003782 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003783 mFlinger.setPowerModeInternal(
3784 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003785 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003786 return true;
3787 }
3788 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003789 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003790 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003791}
3792
3793// ---------------------------------------------------------------------------
3794
Lloyd Pique755e3192018-01-31 16:46:15 -08003795status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3796 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003797 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003798
Mathias Agopianbd115332013-04-18 16:41:04 -07003799 IPCThreadState* ipc = IPCThreadState::self();
3800 const int pid = ipc->getCallingPid();
3801 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003802
Mathias Agopianbd115332013-04-18 16:41:04 -07003803 if ((uid != AID_SHELL) &&
3804 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003805 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003806 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003807 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003808 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003809 // (this would indicate SF is stuck, but we want to be able to
3810 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003811 status_t err = mStateLock.timedLock(s2ns(1));
3812 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003813 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003814 result.appendFormat(
3815 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3816 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003817 }
3818
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003819 bool dumpAll = true;
3820 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003821 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003822
3823 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003824 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003825 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3826 dumpAll = false;
3827 }
3828
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003829 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003830 if ((index < numArgs) &&
3831 (args[index] == String16("--list"))) {
3832 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003833 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003834 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003835 }
3836
3837 if ((index < numArgs) &&
3838 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003841 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003842 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843
3844 if ((index < numArgs) &&
3845 (args[index] == String16("--latency-clear"))) {
3846 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003848 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--dispsync"))) {
3853 index++;
3854 mPrimaryDispSync.dump(result);
3855 dumpAll = false;
3856 }
Dan Stozab90cf072015-03-05 11:05:59 -08003857
3858 if ((index < numArgs) &&
3859 (args[index] == String16("--static-screen"))) {
3860 index++;
3861 dumpStaticScreenStats(result);
3862 dumpAll = false;
3863 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003864
3865 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003866 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003867 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003868 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003869 dumpAll = false;
3870 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003871
3872 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3873 index++;
3874 dumpWideColorInfo(result);
3875 dumpAll = false;
3876 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--enable-layer-stats"))) {
3880 index++;
3881 mLayerStats.enable();
3882 dumpAll = false;
3883 }
3884
3885 if ((index < numArgs) &&
3886 (args[index] == String16("--disable-layer-stats"))) {
3887 index++;
3888 mLayerStats.disable();
3889 dumpAll = false;
3890 }
3891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--clear-layer-stats"))) {
3894 index++;
3895 mLayerStats.clear();
3896 dumpAll = false;
3897 }
3898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--dump-layer-stats"))) {
3901 index++;
3902 mLayerStats.dump(result);
3903 dumpAll = false;
3904 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003906
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003908 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003909 }
3910
Mathias Agopian9795c422009-08-26 16:36:26 -07003911 if (locked) {
3912 mStateLock.unlock();
3913 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914 }
3915 write(fd, result.string(), result.size());
3916 return NO_ERROR;
3917}
3918
Dan Stozac7014012014-02-14 15:03:43 -08003919void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3920 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003921{
Robert Carr2047fae2016-11-28 14:09:09 -08003922 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003924 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925}
3926
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003927void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003928 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929{
3930 String8 name;
3931 if (index < args.size()) {
3932 name = String8(args[index]);
3933 index++;
3934 }
3935
David Sodman105b7dc2017-11-04 20:28:14 -07003936 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003937 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003938 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003939
3940 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003941 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003942 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003943 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003944 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003945 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003946 }
Robert Carr2047fae2016-11-28 14:09:09 -08003947 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003948 }
3949}
3950
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003951void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003952 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953{
3954 String8 name;
3955 if (index < args.size()) {
3956 name = String8(args[index]);
3957 index++;
3958 }
3959
Robert Carr2047fae2016-11-28 14:09:09 -08003960 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003961 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003962 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963 }
Robert Carr2047fae2016-11-28 14:09:09 -08003964 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003965
Svetoslavd85084b2014-03-20 10:28:31 -07003966 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967}
3968
Jamie Gennis6547ff42013-07-16 20:12:42 -07003969// This should only be called from the main thread. Otherwise it would need
3970// the lock and should use mCurrentState rather than mDrawingState.
3971void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003972 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003974 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003975
3976 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3977}
3978
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003979void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003980{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003981 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003982
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003983 if (isLayerTripleBufferingDisabled())
3984 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003985
3986 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003987 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003988 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003989 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003990 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3991 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003992 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003993}
3994
Dan Stozab90cf072015-03-05 11:05:59 -08003995void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3996{
3997 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003998 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3999 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004000 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004001 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004002 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4003 b + 1, bucketTimeSec, percent);
4004 }
David Sodman4a36e932017-11-07 14:29:47 -08004005 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004006 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004007 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004008 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004009 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004010}
4011
Dan Stozae77c7662016-05-13 11:37:28 -07004012void SurfaceFlinger::recordBufferingStats(const char* layerName,
4013 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004014 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4015 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004016 for (const auto& segment : history) {
4017 if (!segment.usedThirdBuffer) {
4018 stats.twoBufferTime += segment.totalTime;
4019 }
4020 if (segment.occupancyAverage < 1.0f) {
4021 stats.doubleBufferedTime += segment.totalTime;
4022 } else if (segment.occupancyAverage < 2.0f) {
4023 stats.tripleBufferedTime += segment.totalTime;
4024 }
4025 ++stats.numSegments;
4026 stats.totalTime += segment.totalTime;
4027 }
4028}
4029
Brian Andersond6927fb2016-07-23 23:37:30 -07004030void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4031 result.appendFormat("Layer frame timestamps:\n");
4032
4033 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4034 const size_t count = currentLayers.size();
4035 for (size_t i=0 ; i<count ; i++) {
4036 currentLayers[i]->dumpFrameEvents(result);
4037 }
4038}
4039
Dan Stozae77c7662016-05-13 11:37:28 -07004040void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4041 result.append("Buffering stats:\n");
4042 result.append(" [Layer name] <Active time> <Two buffer> "
4043 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004044 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004045 typedef std::tuple<std::string, float, float, float> BufferTuple;
4046 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004047 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004048 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004049 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004050 if (stats.numSegments == 0) {
4051 continue;
4052 }
4053 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4054 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4055 stats.totalTime;
4056 float doubleBufferRatio = static_cast<float>(
4057 stats.doubleBufferedTime) / stats.totalTime;
4058 float tripleBufferRatio = static_cast<float>(
4059 stats.tripleBufferedTime) / stats.totalTime;
4060 sorted.insert({activeTime, {name, twoBufferRatio,
4061 doubleBufferRatio, tripleBufferRatio}});
4062 }
4063 for (const auto& sortedPair : sorted) {
4064 float activeTime = sortedPair.first;
4065 const BufferTuple& values = sortedPair.second;
4066 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4067 std::get<0>(values).c_str(), activeTime,
4068 std::get<1>(values), std::get<2>(values),
4069 std::get<3>(values));
4070 }
4071 result.append("\n");
4072}
4073
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004074void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4075 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004076 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004077
4078 // TODO: print out if wide-color mode is active or not
4079
4080 for (size_t d = 0; d < mDisplays.size(); d++) {
4081 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4082 int32_t hwcId = displayDevice->getHwcDisplayId();
4083 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4084 continue;
4085 }
4086
4087 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004088 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004089 for (auto&& mode : modes) {
4090 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4091 }
4092
Peiyong Lina52f0292018-03-14 17:26:31 -07004093 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004094 result.appendFormat(" Current color mode: %s (%d)\n",
4095 decodeColorMode(currentMode).c_str(), currentMode);
4096 }
4097 result.append("\n");
4098}
4099
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004100LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004101 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004102 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4103 const State& state = useDrawing ? mDrawingState : mCurrentState;
4104 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004105 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004106 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004107 });
4108
4109 return layersProto;
4110}
4111
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004112LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4113 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004114 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004115
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004116 SizeProto* resolution = layersProto.mutable_resolution();
4117 resolution->set_w(displayDevice->getWidth());
4118 resolution->set_h(displayDevice->getHeight());
4119
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004120 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4121 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4122 layersProto.set_global_transform(
4123 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4124
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004125 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004126 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004127 LayerProto* layerProto = layersProto.add_layers();
4128 layer->writeToProto(layerProto, hwcId);
4129 }
4130 });
4131
4132 return layersProto;
4133}
4134
Mathias Agopian74d211a2013-04-22 16:55:35 +02004135void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4136 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004137{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004138 bool colorize = false;
4139 if (index < args.size()
4140 && (args[index] == String16("--color"))) {
4141 colorize = true;
4142 index++;
4143 }
4144
4145 Colorizer colorizer(colorize);
4146
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004147 // figure out if we're stuck somewhere
4148 const nsecs_t now = systemTime();
4149 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4150 const nsecs_t inTransaction(mDebugInTransaction);
4151 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4152 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4153
4154 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004155 * Dump library configuration.
4156 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004157
4158 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004159 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004160 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004161 appendSfConfigString(result);
4162 appendUiConfigString(result);
4163 appendGuiConfigString(result);
4164 result.append("\n");
4165
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004166 result.append("\nWide-Color information:\n");
4167 dumpWideColorInfo(result);
4168
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004169 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004170 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004171 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004172 result.append(SyncFeatures::getInstance().toString());
4173 result.append("\n");
4174
David Sodman105b7dc2017-11-04 20:28:14 -07004175 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004176
Andy McFadden41d67d72014-04-25 16:58:34 -07004177 colorizer.bold(result);
4178 result.append("DispSync configuration: ");
4179 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004180 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4181 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4182 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004183 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004184 result.append("\n");
4185
Dan Stozab90cf072015-03-05 11:05:59 -08004186 // Dump static screen stats
4187 result.append("\n");
4188 dumpStaticScreenStats(result);
4189 result.append("\n");
4190
Dan Stozae77c7662016-05-13 11:37:28 -07004191 dumpBufferingStats(result);
4192
Andy McFadden4803b742012-09-24 19:07:20 -07004193 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004194 * Dump the visible layer list
4195 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004196 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004197 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004198 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4199 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004201
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004202 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004203 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004204 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004205 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004206
4207 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004208 * Dump Display state
4209 */
4210
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004212 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004214 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4215 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004216 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004217 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004218 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004219
4220 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004221 * Dump SurfaceFlinger global state
4222 */
4223
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004224 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004225 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227
Mathias Agopian888c8222012-08-04 21:10:38 -07004228 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004229 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004230
David Sodmanbc815282017-11-05 18:57:52 -08004231 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004233 if (hw) {
4234 hw->undefinedRegion.dump(result, "undefinedRegion");
4235 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4236 hw->getOrientation(), hw->isDisplayOn());
4237 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004238 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004239 " last eglSwapBuffers() time: %f us\n"
4240 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004241 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242 " refresh-rate : %f fps\n"
4243 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004244 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004245 " gpu_to_cpu_unsupported : %d\n"
4246 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004247 mLastSwapBufferTime/1000.0,
4248 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004249 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004250 1e9 / activeConfig->getVsyncPeriod(),
4251 activeConfig->getDpiX(),
4252 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004253 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254
Mathias Agopian74d211a2013-04-22 16:55:35 +02004255 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257
Mathias Agopian74d211a2013-04-22 16:55:35 +02004258 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260
4261 /*
4262 * VSYNC state
4263 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004264 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004265 result.append("\n");
4266
4267 /*
4268 * HWC layer minidump
4269 */
4270 for (size_t d = 0; d < mDisplays.size(); d++) {
4271 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4272 int32_t hwcId = displayDevice->getHwcDisplayId();
4273 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4274 continue;
4275 }
4276
4277 result.appendFormat("Display %d HWC layers:\n", hwcId);
4278 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004279 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004280 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004281 });
Dan Stozae22aec72016-08-01 13:20:59 -07004282 result.append("\n");
4283 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
4286 * Dump HWComposer state
4287 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004289 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004291 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004292 result.appendFormat(" h/w composer %s\n",
4293 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004294 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004295
4296 /*
4297 * Dump gralloc state
4298 */
4299 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4300 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004301
4302 /*
4303 * Dump VrFlinger state if in use.
4304 */
4305 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4306 result.append("VrFlinger state:\n");
4307 result.append(mVrFlinger->Dump().c_str());
4308 result.append("\n");
4309 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004310}
4311
Mathias Agopian13127d82013-03-05 17:47:11 -08004312const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004313SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004314 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004315 wp<IBinder> dpy;
4316 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4317 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4318 dpy = mDisplays.keyAt(i);
4319 break;
4320 }
4321 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004322 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004323 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4324 // Just use the primary display so we have something to return
4325 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4326 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004327 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004328}
4329
Keun young Park63f165f2012-08-31 10:53:36 -07004330bool SurfaceFlinger::startDdmConnection()
4331{
4332 void* libddmconnection_dso =
4333 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4334 if (!libddmconnection_dso) {
4335 return false;
4336 }
4337 void (*DdmConnection_start)(const char* name);
4338 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004339 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004340 if (!DdmConnection_start) {
4341 dlclose(libddmconnection_dso);
4342 return false;
4343 }
4344 (*DdmConnection_start)(getServiceName());
4345 return true;
4346}
4347
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004348status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004349 switch (code) {
4350 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004351 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004352 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004353 case CLEAR_ANIMATION_FRAME_STATS:
4354 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004355 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004356 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004357 case ENABLE_VSYNC_INJECTIONS:
4358 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004359 {
4360 // codes that require permission check
4361 IPCThreadState* ipc = IPCThreadState::self();
4362 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004363 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004364 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004365 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004366 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004367 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004369 break;
4370 }
Robert Carr1db73f62016-12-21 12:58:51 -08004371 /*
4372 * Calling setTransactionState is safe, because you need to have been
4373 * granted a reference to Client* and Handle* to do anything with it.
4374 *
4375 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4376 */
4377 case SET_TRANSACTION_STATE:
4378 case CREATE_SCOPED_CONNECTION:
4379 {
4380 return OK;
4381 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004382 case CAPTURE_SCREEN:
4383 {
4384 // codes that require permission check
4385 IPCThreadState* ipc = IPCThreadState::self();
4386 const int pid = ipc->getCallingPid();
4387 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004388 if ((uid != AID_GRAPHICS) &&
4389 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004390 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004391 return PERMISSION_DENIED;
4392 }
4393 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004394 }
chaviwa76b2712017-09-20 12:02:26 -07004395 case CAPTURE_LAYERS: {
4396 IPCThreadState* ipc = IPCThreadState::self();
4397 const int pid = ipc->getCallingPid();
4398 const int uid = ipc->getCallingUid();
4399 if ((uid != AID_GRAPHICS) &&
4400 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4401 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4402 return PERMISSION_DENIED;
4403 }
4404 break;
4405 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004406 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004407 return OK;
4408}
4409
4410status_t SurfaceFlinger::onTransact(
4411 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4412{
4413 status_t credentialCheck = CheckTransactCodeCredentials(code);
4414 if (credentialCheck != OK) {
4415 return credentialCheck;
4416 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004417
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004418 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4419 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004420 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004421 IPCThreadState* ipc = IPCThreadState::self();
4422 const int uid = ipc->getCallingUid();
4423 if (CC_UNLIKELY(uid != AID_SYSTEM
4424 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004425 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004426 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004427 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004428 return PERMISSION_DENIED;
4429 }
4430 int n;
4431 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004432 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004433 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 return NO_ERROR;
4435 case 1002: // SHOW_UPDATES
4436 n = data.readInt32();
4437 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004438 invalidateHwcGeometry();
4439 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004440 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004442 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004443 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004444 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004445 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004446 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004447 setTransactionFlags(
4448 eTransactionNeeded|
4449 eDisplayTransactionNeeded|
4450 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004451 return NO_ERROR;
4452 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004453 case 1006:{ // send empty update
4454 signalRefresh();
4455 return NO_ERROR;
4456 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004457 case 1008: // toggle use of hw composer
4458 n = data.readInt32();
4459 mDebugDisableHWC = n ? 1 : 0;
4460 invalidateHwcGeometry();
4461 repaintEverything();
4462 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004463 case 1009: // toggle use of transform hint
4464 n = data.readInt32();
4465 mDebugDisableTransformHint = n ? 1 : 0;
4466 invalidateHwcGeometry();
4467 repaintEverything();
4468 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004469 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004470 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 reply->writeInt32(0);
4472 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004473 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004474 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 return NO_ERROR;
4476 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004477 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004478 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004479 return NO_ERROR;
4480 }
4481 case 1014: {
4482 // daltonize
4483 n = data.readInt32();
4484 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004485 case 1:
4486 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4487 break;
4488 case 2:
4489 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4490 break;
4491 case 3:
4492 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4493 break;
4494 default:
4495 mDaltonizer.setType(ColorBlindnessType::None);
4496 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004497 }
4498 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004499 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004500 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004501 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004502 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004503 invalidateHwcGeometry();
4504 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004505 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004507 case 1015: {
4508 // apply a color matrix
4509 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004510 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004511 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004512 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004513 for (size_t j = 0; j < 4; j++) {
4514 mColorMatrix[i][j] = data.readFloat();
4515 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004516 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004517 } else {
4518 mColorMatrix = mat4();
4519 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004520
4521 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4522 // the division by w in the fragment shader
4523 float4 lastRow(transpose(mColorMatrix)[3]);
4524 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4525 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4526 }
4527
Alan Viverette9c5a3332013-09-12 20:04:35 -07004528 invalidateHwcGeometry();
4529 repaintEverything();
4530 return NO_ERROR;
4531 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004532 // This is an experimental interface
4533 // Needs to be shifted to proper binder interface when we productize
4534 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004535 n = data.readInt32();
4536 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004537 return NO_ERROR;
4538 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004539 case 1017: {
4540 n = data.readInt32();
4541 mForceFullDamage = static_cast<bool>(n);
4542 return NO_ERROR;
4543 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004544 case 1018: { // Modify Choreographer's phase offset
4545 n = data.readInt32();
4546 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4547 return NO_ERROR;
4548 }
4549 case 1019: { // Modify SurfaceFlinger's phase offset
4550 n = data.readInt32();
4551 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4552 return NO_ERROR;
4553 }
Irvel468051e2016-06-13 16:44:44 -07004554 case 1020: { // Layer updates interceptor
4555 n = data.readInt32();
4556 if (n) {
4557 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004558 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004559 }
4560 else{
4561 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004562 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004563 }
4564 return NO_ERROR;
4565 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004566 case 1021: { // Disable HWC virtual displays
4567 n = data.readInt32();
4568 mUseHwcVirtualDisplays = !n;
4569 return NO_ERROR;
4570 }
Romain Guy0147a172017-06-01 13:53:56 -07004571 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004572 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004573
4574 invalidateHwcGeometry();
4575 repaintEverything();
4576 return NO_ERROR;
4577 }
Romain Guy54f154a2017-10-24 21:40:32 +01004578 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004579 int32_t value = data.readInt32();
4580 if (value > 2) {
4581 return BAD_VALUE;
4582 }
4583 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4584 return BAD_VALUE;
4585 }
Romain Guy54f154a2017-10-24 21:40:32 +01004586
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004587 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004588 invalidateHwcGeometry();
4589 repaintEverything();
4590 return NO_ERROR;
4591 }
4592 case 1024: { // Is wide color gamut rendering/color management supported?
4593 reply->writeBool(hasWideColorDisplay);
4594 return NO_ERROR;
4595 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004596 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004597 n = data.readInt32();
4598 if (n) {
4599 ALOGV("LayerTracing enabled");
4600 mTracing.enable();
4601 doTracing("tracing.enable");
4602 reply->writeInt32(NO_ERROR);
4603 } else {
4604 ALOGV("LayerTracing disabled");
4605 status_t err = mTracing.disable();
4606 reply->writeInt32(err);
4607 }
4608 return NO_ERROR;
4609 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004610 case 1026: { // Get layer tracing status
4611 reply->writeBool(mTracing.isEnabled());
4612 return NO_ERROR;
4613 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004614 // Is a DisplayColorSetting supported?
4615 case 1027: {
4616 int32_t value = data.readInt32();
4617 switch (value) {
4618 case 0:
4619 reply->writeBool(hasWideColorDisplay);
4620 return NO_ERROR;
4621 case 1:
4622 reply->writeBool(true);
4623 return NO_ERROR;
4624 case 2:
4625 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4626 return NO_ERROR;
4627 default:
4628 return BAD_VALUE;
4629 }
4630 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004631 }
4632 }
4633 return err;
4634}
4635
Steven Thomas6d8110b2017-08-31 18:24:21 -07004636void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004637 android_atomic_or(1, &mRepaintEverything);
4638 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004639}
4640
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004641// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4642class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004643public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004644 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4645 ~WindowDisconnector() {
4646 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004647 }
4648
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004649private:
4650 ANativeWindow* mWindow;
4651 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004652};
4653
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004654status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4655 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4656 int32_t minLayerZ, int32_t maxLayerZ,
4657 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004658 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004659 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004660
chaviwa76b2712017-09-20 12:02:26 -07004661 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4662
4663 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004664 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4665
chaviwa76b2712017-09-20 12:02:26 -07004666 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4667
4668 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4669 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004670 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004671}
4672
4673status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004674 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004675 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004676 ATRACE_CALL();
4677
4678 class LayerRenderArea : public RenderArea {
4679 public:
Robert Carr578038f2018-03-09 12:25:24 -08004680 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4681 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004682 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004683 mLayer(layer),
4684 mCrop(crop),
4685 mFlinger(flinger),
4686 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004687 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004688 Rect getBounds() const override {
4689 const Layer::State& layerState(mLayer->getDrawingState());
4690 return Rect(layerState.active.w, layerState.active.h);
4691 }
4692 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4693 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4694 bool isSecure() const override { return false; }
4695 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004696 Rect getSourceCrop() const override {
4697 if (mCrop.isEmpty()) {
4698 return getBounds();
4699 } else {
4700 return mCrop;
4701 }
4702 }
4703 bool getWideColorSupport() const override { return false; }
4704 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004705
4706 class ReparentForDrawing {
4707 public:
4708 const sp<Layer>& oldParent;
4709 const sp<Layer>& newParent;
4710
4711 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4712 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004713 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004714 }
Robert Carr15eae092018-03-23 13:43:53 -07004715 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004716 };
4717
4718 void render(std::function<void()> drawLayers) override {
4719 if (!mChildrenOnly) {
4720 mTransform = mLayer->getTransform().inverse();
4721 drawLayers();
4722 } else {
4723 Rect bounds = getBounds();
4724 screenshotParentLayer =
4725 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4726 bounds.getWidth(), bounds.getHeight(), 0);
4727
4728 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4729 drawLayers();
4730 }
4731 }
chaviwa76b2712017-09-20 12:02:26 -07004732
chaviwa76b2712017-09-20 12:02:26 -07004733 private:
chaviw7206d492017-11-10 16:16:12 -08004734 const sp<Layer> mLayer;
4735 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004736
4737 // In the "childrenOnly" case we reparent the children to a screenshot
4738 // layer which has no properties set and which does not draw.
4739 sp<ContainerLayer> screenshotParentLayer;
4740 Transform mTransform;
4741
4742 SurfaceFlinger* mFlinger;
4743 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004744 };
4745
4746 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4747 auto parent = layerHandle->owner.promote();
4748
chaviw7206d492017-11-10 16:16:12 -08004749 if (parent == nullptr || parent->isPendingRemoval()) {
4750 ALOGE("captureLayers called with a removed parent");
4751 return NAME_NOT_FOUND;
4752 }
4753
Robert Carr578038f2018-03-09 12:25:24 -08004754 const int uid = IPCThreadState::self()->getCallingUid();
4755 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4756 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4757 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4758 return PERMISSION_DENIED;
4759 }
4760
chaviw7206d492017-11-10 16:16:12 -08004761 Rect crop(sourceCrop);
4762 if (sourceCrop.width() <= 0) {
4763 crop.left = 0;
4764 crop.right = parent->getCurrentState().active.w;
4765 }
4766
4767 if (sourceCrop.height() <= 0) {
4768 crop.top = 0;
4769 crop.bottom = parent->getCurrentState().active.h;
4770 }
4771
4772 int32_t reqWidth = crop.width() * frameScale;
4773 int32_t reqHeight = crop.height() * frameScale;
4774
Robert Carr578038f2018-03-09 12:25:24 -08004775 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004776
Robert Carr578038f2018-03-09 12:25:24 -08004777 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004778 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4779 if (!layer->isVisible()) {
4780 return;
Robert Carr578038f2018-03-09 12:25:24 -08004781 } else if (childrenOnly && layer == parent.get()) {
4782 return;
chaviwa76b2712017-09-20 12:02:26 -07004783 }
4784 visitor(layer);
4785 });
4786 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004787 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004788}
4789
4790status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4791 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004792 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004793 bool useIdentityTransform) {
4794 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004795
chaviwa76b2712017-09-20 12:02:26 -07004796 renderArea.updateDimensions();
4797
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004798 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4799 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4800 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4801 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004802
4803 // This mutex protects syncFd and captureResult for communication of the return values from the
4804 // main thread back to this Binder thread
4805 std::mutex captureMutex;
4806 std::condition_variable captureCondition;
4807 std::unique_lock<std::mutex> captureLock(captureMutex);
4808 int syncFd = -1;
4809 std::optional<status_t> captureResult;
4810
Robert Carr03480e22018-01-04 16:02:06 -08004811 const int uid = IPCThreadState::self()->getCallingUid();
4812 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4813
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004814 sp<LambdaMessage> message = new LambdaMessage([&]() {
4815 // If there is a refresh pending, bug out early and tell the binder thread to try again
4816 // after the refresh.
4817 if (mRefreshPending) {
4818 ATRACE_NAME("Skipping screenshot for now");
4819 std::unique_lock<std::mutex> captureLock(captureMutex);
4820 captureResult = std::make_optional<status_t>(EAGAIN);
4821 captureCondition.notify_one();
4822 return;
4823 }
4824
4825 status_t result = NO_ERROR;
4826 int fd = -1;
4827 {
4828 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004829 renderArea.render([&]() {
4830 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4831 useIdentityTransform, forSystem, &fd);
4832 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004833 }
4834
4835 {
4836 std::unique_lock<std::mutex> captureLock(captureMutex);
4837 syncFd = fd;
4838 captureResult = std::make_optional<status_t>(result);
4839 captureCondition.notify_one();
4840 }
4841 });
4842
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004843 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004844 if (result == NO_ERROR) {
4845 captureCondition.wait(captureLock, [&]() { return captureResult; });
4846 while (*captureResult == EAGAIN) {
4847 captureResult.reset();
4848 result = postMessageAsync(message);
4849 if (result != NO_ERROR) {
4850 return result;
4851 }
4852 captureCondition.wait(captureLock, [&]() { return captureResult; });
4853 }
4854 result = *captureResult;
4855 }
4856
4857 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004858 sync_wait(syncFd, -1);
4859 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004860 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004861
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004862 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004863}
4864
chaviwa76b2712017-09-20 12:02:26 -07004865void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4866 TraverseLayersFunction traverseLayers, bool yswap,
4867 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004868 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004869
Lloyd Pique144e1162017-12-20 16:44:52 -08004870 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004871
4872 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004873 const auto raWidth = renderArea.getWidth();
4874 const auto raHeight = renderArea.getHeight();
4875
4876 const auto reqWidth = renderArea.getReqWidth();
4877 const auto reqHeight = renderArea.getReqHeight();
4878 Rect sourceCrop = renderArea.getSourceCrop();
4879
4880 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4881 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004882
Dan Stozac1879002014-05-22 15:59:05 -07004883 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004884 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004885 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004886 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004887 }
4888
4889 // ensure that sourceCrop is inside screen
4890 if (sourceCrop.left < 0) {
4891 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4892 }
chaviwa76b2712017-09-20 12:02:26 -07004893 if (sourceCrop.right > raWidth) {
4894 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004895 }
4896 if (sourceCrop.top < 0) {
4897 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4898 }
chaviwa76b2712017-09-20 12:02:26 -07004899 if (sourceCrop.bottom > raHeight) {
4900 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004901 }
4902
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004903 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004904 if (renderArea.getWideColorSupport()) {
4905 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004906 }
4907 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004908
Mathias Agopian180f10d2013-04-10 22:55:41 -07004909 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004910 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004911
4912 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004913 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4914 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004915 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004916
chaviw50da5042018-04-09 13:49:37 -07004917 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004918 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004919 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004920
chaviwa76b2712017-09-20 12:02:26 -07004921 traverseLayers([&](Layer* layer) {
4922 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004923 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004924 if (filtering) layer->setFiltering(false);
4925 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004926}
4927
chaviwa76b2712017-09-20 12:02:26 -07004928status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4929 TraverseLayersFunction traverseLayers,
4930 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004931 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004932 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004933 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004934 ATRACE_CALL();
4935
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004936 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004937
4938 traverseLayers([&](Layer* layer) {
4939 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4940 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004941
Robert Carr03480e22018-01-04 16:02:06 -08004942 // We allow the system server to take screenshots of secure layers for
4943 // use in situations like the Screen-rotation animation and place
4944 // the impetus on WindowManager to not persist them.
4945 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004946 ALOGW("FB is protected: PERMISSION_DENIED");
4947 return PERMISSION_DENIED;
4948 }
4949
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004950 // this binds the given EGLImage as a framebuffer for the
4951 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004952 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004953 if (bufferBond.getStatus() != NO_ERROR) {
4954 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004955 return INVALID_OPERATION;
4956 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004957
Dan Stozaabcda352017-06-01 14:37:39 -07004958 // this will in fact render into our dequeued buffer
4959 // via an FBO, which means we didn't have to create
4960 // an EGLSurface and therefore we're not
4961 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004962 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004963
Dan Stozaabcda352017-06-01 14:37:39 -07004964 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004965 getRenderEngine().finish();
4966 *outSyncFd = -1;
4967
chaviwa76b2712017-09-20 12:02:26 -07004968 const auto reqWidth = renderArea.getReqWidth();
4969 const auto reqHeight = renderArea.getReqHeight();
4970
Dan Stozaabcda352017-06-01 14:37:39 -07004971 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4972 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004973 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004974 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004975 } else {
4976 base::unique_fd syncFd = getRenderEngine().flush();
4977 if (syncFd < 0) {
4978 getRenderEngine().finish();
4979 }
4980 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004981 }
4982
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004983 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004984}
4985
Mathias Agopiand5556842013-09-19 17:08:37 -07004986void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004987 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004988 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004989 for (size_t y = 0; y < h; y++) {
4990 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4991 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004992 if (p[x] != 0xFF000000) return;
4993 }
4994 }
chaviwa76b2712017-09-20 12:02:26 -07004995 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004996
Robert Carr2047fae2016-11-28 14:09:09 -08004997 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004998 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004999 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005000 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5001 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5002 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5003 static_cast<float>(state.color.a));
5004 i++;
5005 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005006 }
5007}
5008
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005009// ---------------------------------------------------------------------------
5010
Dan Stoza412903f2017-04-27 13:42:17 -07005011void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5012 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005013}
5014
Dan Stoza412903f2017-04-27 13:42:17 -07005015void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5016 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005017}
5018
chaviwa76b2712017-09-20 12:02:26 -07005019void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5020 int32_t maxLayerZ,
5021 const LayerVector::Visitor& visitor) {
5022 // We loop through the first level of layers without traversing,
5023 // as we need to interpret min/max layer Z in the top level Z space.
5024 for (const auto& layer : mDrawingState.layersSortedByZ) {
5025 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5026 continue;
5027 }
5028 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005029 // relative layers are traversed in Layer::traverseInZOrder
5030 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005031 continue;
5032 }
5033 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005034 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5035 return;
5036 }
chaviwa76b2712017-09-20 12:02:26 -07005037 if (!layer->isVisible()) {
5038 return;
5039 }
5040 visitor(layer);
5041 });
5042 }
5043}
5044
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005045}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005046
Chia-I Wu30505fb2018-03-26 16:20:31 -07005047
Mathias Agopian3f844832013-08-07 21:24:32 -07005048#if defined(__gl_h_)
5049#error "don't include gl/gl.h in this file"
5050#endif
5051
5052#if defined(__gl2_h_)
5053#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005054#endif