blob: 82b8bc099ace4bbded4981d25a347d9b9fea4c87 [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;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108
Steven Thomasb02664d2017-07-26 18:48:28 -0700109namespace {
110class ConditionalLock {
111public:
112 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
113 if (lock) {
114 mMutex.lock();
115 }
116 }
117 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
118private:
119 Mutex& mMutex;
120 bool mLocked;
121};
122} // namespace anonymous
123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124// ---------------------------------------------------------------------------
125
Mathias Agopian99b49842011-06-27 16:05:52 -0700126const String16 sHardwareTest("android.permission.HARDWARE_TEST");
127const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
128const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
129const String16 sDump("android.permission.DUMP");
130
131// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800132int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
133int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800140// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600141bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700142
Kalle Raitaa099a242017-01-11 11:17:29 -0800143
144std::string getHwcServiceName() {
145 char value[PROPERTY_VALUE_MAX] = {};
146 property_get("debug.sf.hwc_service_name", value, "default");
147 ALOGI("Using HWComposer service: '%s'", value);
148 return std::string(value);
149}
150
151bool useTrebleTestingOverride() {
152 char value[PROPERTY_VALUE_MAX] = {};
153 property_get("debug.sf.treble_testing_override", value, "false");
154 ALOGI("Treble testing override: '%s'", value);
155 return std::string(value) == "true";
156}
157
Lloyd Pique99d3da52018-01-22 17:48:03 -0800158NativeWindowSurface::~NativeWindowSurface() = default;
159
160namespace impl {
161
162class NativeWindowSurface final : public android::NativeWindowSurface {
163public:
164 static std::unique_ptr<android::NativeWindowSurface> create(
165 const sp<IGraphicBufferProducer>& producer) {
166 return std::make_unique<NativeWindowSurface>(producer);
167 }
168
169 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
170 : surface(new Surface(producer, false)) {}
171
172 ~NativeWindowSurface() override = default;
173
174private:
175 sp<ANativeWindow> getNativeWindow() const override { return surface; }
176
177 void preallocateBuffers() override { surface->allocateBuffers(); }
178
179 sp<Surface> surface;
180};
181
182} // namespace impl
183
David Sodmanbc815282017-11-05 18:57:52 -0800184SurfaceFlingerBE::SurfaceFlingerBE()
185 : mHwcServiceName(getHwcServiceName()),
186 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800187 mFrameBuckets(),
188 mTotalTime(0),
189 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800190 mComposerSequenceId(0) {
191}
192
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800193SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800194 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700196 mTransactionPending(false),
197 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700198 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700199 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700200 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800202 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800204 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800205 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700208 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700209 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700210 mDebugInSwapBuffers(0),
211 mLastSwapBufferTime(0),
212 mDebugInTransaction(0),
213 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700214 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700215 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000216 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700217 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700218 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700219 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800220 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700222 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800223 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800224 mCreateBufferQueue(&BufferQueue::createBufferQueue),
225 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800226
227SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800228 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800229
230 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
231 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
232
233 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
234 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
235
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800236 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
237 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700239 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
240 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
241
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700242 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
243 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
244
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800245 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
246 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
247
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 // Vr flinger is only enabled on Daydream ready devices.
249 useVrFlinger = getBool< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::useVrFlinger>(false);
251
Fabien Sanglard1971b632017-03-10 14:50:03 -0800252 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
254
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600255 hasWideColorDisplay =
256 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
257
David Sodman99974d22017-11-28 12:04:33 -0800258 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 // debugging stuff...
261 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262
Mathias Agopianb4b17302013-03-20 18:36:41 -0700263 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700264 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 property_get("debug.sf.showupdates", value, "0");
267 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700268
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700269 property_get("debug.sf.ddms", value, "0");
270 mDebugDDMS = atoi(value);
271 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700272 if (!startDdmConnection()) {
273 // start failed, and DDMS debugging not enabled
274 mDebugDDMS = 0;
275 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700276 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700277 ALOGI_IF(mDebugRegion, "showupdates enabled");
278 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700279
280 property_get("debug.sf.disable_backpressure", value, "0");
281 mPropagateBackpressure = !atoi(value);
282 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700283
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800284 property_get("debug.sf.enable_hwc_vds", value, "0");
285 mUseHwcVirtualDisplays = atoi(value);
286 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800287
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800288 property_get("ro.sf.disable_triple_buffer", value, "1");
289 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800290 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700291
Dan Stoza0a0158c2018-03-16 13:38:54 -0700292 // TODO (b/74616334): Reduce the default value once we isolate the leak
293 const size_t defaultListSize = 4 * MAX_LAYERS;
294 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
295 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
296
Romain Guy11d63f42017-07-20 12:47:14 -0700297 // We should be reading 'persist.sys.sf.color_saturation' here
298 // but since /data may be encrypted, we need to wait until after vold
299 // comes online to attempt to read the property. The property is
300 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800301
302 if (useTrebleTestingOverride()) {
303 // Without the override SurfaceFlinger cannot connect to HIDL
304 // services that are not listed in the manifests. Considered
305 // deriving the setting from the set service name, but it
306 // would be brittle if the name that's not 'default' is used
307 // for production purposes later on.
308 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
309 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310}
311
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800312void SurfaceFlinger::onFirstRef()
313{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800314 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800315}
316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317SurfaceFlinger::~SurfaceFlinger()
318{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319}
320
Dan Stozac7014012014-02-14 15:03:43 -0800321void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800322{
323 // the window manager died on us. prepare its eulogy.
324
Andy McFadden13a082e2012-08-24 10:16:42 -0700325 // restore initial conditions (default device unblank, etc)
326 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800327
328 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700329 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800330}
331
Robert Carr1db73f62016-12-21 12:58:51 -0800332static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700333 status_t err = client->initCheck();
334 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800335 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 }
Robert Carr1db73f62016-12-21 12:58:51 -0800337 return nullptr;
338}
339
340sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
341 return initClient(new Client(this));
342}
343
344sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
345 const sp<IGraphicBufferProducer>& gbp) {
346 if (authenticateSurfaceTexture(gbp) == false) {
347 return nullptr;
348 }
349 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
350 if (layer == nullptr) {
351 return nullptr;
352 }
353
354 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355}
356
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700357sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
358 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700359{
360 class DisplayToken : public BBinder {
361 sp<SurfaceFlinger> flinger;
362 virtual ~DisplayToken() {
363 // no more references, this display must be terminated
364 Mutex::Autolock _l(flinger->mStateLock);
365 flinger->mCurrentState.displays.removeItem(this);
366 flinger->setTransactionFlags(eDisplayTransactionNeeded);
367 }
368 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700369 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700370 : flinger(flinger) {
371 }
372 };
373
374 sp<BBinder> token = new DisplayToken(this);
375
376 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700377 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700378 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700379 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800380 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381 return token;
382}
383
Jesse Hall6c913be2013-08-08 12:15:49 -0700384void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
385 Mutex::Autolock _l(mStateLock);
386
387 ssize_t idx = mCurrentState.displays.indexOfKey(display);
388 if (idx < 0) {
389 ALOGW("destroyDisplay: invalid display token");
390 return;
391 }
392
393 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
394 if (!info.isVirtualDisplay()) {
395 ALOGE("destroyDisplay called for non-virtual display");
396 return;
397 }
Lloyd Pique4dccc412018-01-22 17:21:36 -0800398 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700399 mCurrentState.displays.removeItemsAt(idx);
400 setTransactionFlags(eDisplayTransactionNeeded);
401}
402
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700404 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700405 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800406 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700407 }
Jesse Hall692c7232012-11-08 15:41:56 -0800408 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409}
410
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411void SurfaceFlinger::bootFinished()
412{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700413 if (mStartPropertySetThread->join() != NO_ERROR) {
414 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800415 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416 const nsecs_t now = systemTime();
417 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000418 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700419
420 // wait patiently for the window manager death
421 const String16 name("window");
422 sp<IBinder> window(defaultServiceManager()->getService(name));
423 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700425 }
426
Steven Thomas050b2c82017-03-06 11:45:16 -0800427 if (mVrFlinger) {
428 mVrFlinger->OnBootFinished();
429 }
430
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700431 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 // formerly we would just kill the process, but we now ask it to exit so it
433 // can choose where to stop the animation.
434 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700435
436 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
437 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
438 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700439
Thierry Strudel2924d012017-08-14 15:19:37 -0700440 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700441 readPersistentProperties();
442 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700443 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444}
445
Mathias Agopian3f844832013-08-07 21:24:32 -0700446void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700447 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800448 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700449 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700450 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800451 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
452 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700453 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700454 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700455 return true;
456 }
457 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700458 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700459}
460
Lloyd Piquee83f9312018-02-01 12:53:17 -0800461class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700463 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000464 const char* name) :
465 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700467 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
469 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700470 mDispSync(dispSync),
471 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 mVsyncMutex(),
473 mPhaseOffset(phaseOffset),
474 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700475
Lloyd Piquee83f9312018-02-01 12:53:17 -0800476 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700477
Lloyd Piquee83f9312018-02-01 12:53:17 -0800478 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000481 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 static_cast<DispSync::Callback*>(this));
483 if (err != NO_ERROR) {
484 ALOGE("error registering vsync callback: %s (%d)",
485 strerror(-err), err);
486 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700487 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 } else {
489 status_t err = mDispSync->removeEventListener(
490 static_cast<DispSync::Callback*>(this));
491 if (err != NO_ERROR) {
492 ALOGE("error unregistering vsync callback: %s (%d)",
493 strerror(-err), err);
494 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700497 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 }
499
Lloyd Piquee83f9312018-02-01 12:53:17 -0800500 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700501 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 mCallback = callback;
503 }
504
Lloyd Piquee83f9312018-02-01 12:53:17 -0800505 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 Mutex::Autolock lock(mVsyncMutex);
507
508 // Normalize phaseOffset to [0, period)
509 auto period = mDispSync->getPeriod();
510 phaseOffset %= period;
511 if (phaseOffset < 0) {
512 // If we're here, then phaseOffset is in (-period, 0). After this
513 // operation, it will be in (0, period)
514 phaseOffset += period;
515 }
516 mPhaseOffset = phaseOffset;
517
518 // If we're not enabled, we don't need to mess with the listeners
519 if (!mEnabled) {
520 return;
521 }
522
523 // Remove the listener with the old offset
524 status_t err = mDispSync->removeEventListener(
525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error unregistering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
530
531 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000532 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 static_cast<DispSync::Callback*>(this));
534 if (err != NO_ERROR) {
535 ALOGE("error registering vsync callback: %s (%d)",
536 strerror(-err), err);
537 }
538 }
539
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540private:
541 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 callback = mCallback;
546
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547 if (mTraceVsync) {
548 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700549 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700550 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 }
552
Peiyong Lin566a3b42018-01-09 18:22:43 -0800553 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 callback->onVSyncEvent(when);
555 }
556 }
557
Tim Murray4a4e4a22016-04-19 16:29:23 +0000558 const char* const mName;
559
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560 int mValue;
561
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700562 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 const String8 mVsyncOnLabel;
564 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700565
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567
568 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570
571 Mutex mVsyncMutex; // Protects the following
572 nsecs_t mPhaseOffset;
573 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574};
575
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700577public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 InjectVSyncSource() = default;
579 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700580
Lloyd Piquee83f9312018-02-01 12:53:17 -0800581 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700582 std::lock_guard<std::mutex> lock(mCallbackMutex);
583 mCallback = callback;
584 }
585
Lloyd Piquee83f9312018-02-01 12:53:17 -0800586 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700587 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700588 if (mCallback) {
589 mCallback->onVSyncEvent(when);
590 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700591 }
592
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 void setVSyncEnabled(bool) override {}
594 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700595
596private:
597 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800598 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700599};
600
Wei Wangf9b05ee2017-07-19 20:59:39 -0700601// Do not call property_set on main thread which will be blocked by init
602// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700604 ALOGI( "SurfaceFlinger's main thread ready to run. "
605 "Initializing graphics H/W...");
606
Thierry Strudel2924d012017-08-14 15:19:37 -0700607 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800612 mEventThreadSource =
613 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
614 true, "app");
615 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
616 "appEventThread");
617 mSfEventThreadSource =
618 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
619 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800620
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800621 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
622 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800623 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800626 getBE().mRenderEngine =
627 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
628 hasWideColorDisplay
629 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
630 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800631 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700632
633 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
634 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800635 getBE().mHwc.reset(
636 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700637 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800638 // Process any initial hotplug and resulting display changes.
639 processDisplayHotplugEventsLocked();
640 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
641 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800642
Lloyd Piquefcd86612017-12-14 17:15:36 -0800643 // make the default display GLContext current so that we can create textures
644 // when creating Layers (which may happens before we render something)
645 getDefaultDisplayDeviceLocked()->makeCurrent();
646
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (useVrFlinger) {
648 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 // This callback is called from the vr flinger dispatch thread. We
650 // need to call signalTransaction(), which requires holding
651 // mStateLock when we're not on the main thread. Acquiring
652 // mStateLock from the vr flinger dispatch thread might trigger a
653 // deadlock in surface flinger (see b/66916578), so post a message
654 // to be handled on the main thread instead.
655 sp<LambdaMessage> message = new LambdaMessage([=]() {
656 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
657 mVrFlingerRequestsDisplay = requestDisplay;
658 signalTransaction();
659 });
660 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 };
David Sodman105b7dc2017-11-04 20:28:14 -0700662 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
663 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800664 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 if (!mVrFlinger) {
666 ALOGE("Failed to start vrflinger");
667 }
668 }
669
Lloyd Pique379adc12018-01-22 17:31:47 -0800670 mEventControlThread = std::make_unique<impl::EventControlThread>(
671 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700672
Mathias Agopian92a979a2012-08-02 18:32:23 -0700673 // initialize our drawing state
674 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700675
Andy McFadden13a082e2012-08-24 10:16:42 -0700676 // set initial conditions (e.g. unblank default device)
677 initializeDisplays();
678
David Sodmanbc815282017-11-05 18:57:52 -0800679 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700680
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 // Inform native graphics APIs whether the present timestamp is supported:
682 if (getHwComposer().hasCapability(
683 HWC2::Capability::PresentFenceIsNotReliable)) {
684 mStartPropertySetThread = new StartPropertySetThread(false);
685 } else {
686 mStartPropertySetThread = new StartPropertySetThread(true);
687 }
688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
700 mSaturation = atof(value);
701 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
704 mForceNativeColorMode = atoi(value) == 1;
705 if (mForceNativeColorMode) {
706 ALOGV("Forcing native color mode");
707 }
Romain Guy11d63f42017-07-20 12:47:14 -0700708}
709
Mathias Agopiana67e4182012-06-19 17:26:12 -0700710void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Start boot animation service by setting a property mailbox
712 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800714 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 if (mStartPropertySetThread->join() != NO_ERROR) {
716 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800721 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800725 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800729
Jamie Gennis582270d2011-08-17 18:19:00 -0700730bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800732 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800733 return authenticateSurfaceTextureLocked(bufferProducer);
734}
735
736bool SurfaceFlinger::authenticateSurfaceTextureLocked(
737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800738 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800739 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800740}
741
Brian Anderson6b376712017-04-04 10:51:39 -0700742status_t SurfaceFlinger::getSupportedFrameTimestamps(
743 std::vector<FrameEvent>* outSupported) const {
744 *outSupported = {
745 FrameEvent::REQUESTED_PRESENT,
746 FrameEvent::ACQUIRE,
747 FrameEvent::LATCH,
748 FrameEvent::FIRST_REFRESH_START,
749 FrameEvent::LAST_REFRESH_START,
750 FrameEvent::GPU_COMPOSITION_DONE,
751 FrameEvent::DEQUEUE_READY,
752 FrameEvent::RELEASE,
753 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700756 if (!getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
759 }
760 return NO_ERROR;
761}
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
764 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800765 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 return BAD_VALUE;
767 }
768
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500769 if (!display.get())
770 return NAME_NOT_FOUND;
771
Jesse Hall692c7232012-11-08 15:41:56 -0800772 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700773 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800774 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700775 type = i;
776 break;
777 }
778 }
779
780 if (type < 0) {
781 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700782 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 // TODO: Not sure if display density should handled by SF any longer
785 class Density {
786 static int getDensityFromProperty(char const* propName) {
787 char property[PROPERTY_VALUE_MAX];
788 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800789 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700790 density = atoi(property);
791 }
792 return density;
793 }
794 public:
795 static int getEmuDensity() {
796 return getDensityFromProperty("qemu.sf.lcd_density"); }
797 static int getBuildDensity() {
798 return getDensityFromProperty("ro.sf.lcd_density"); }
799 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700800
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700802
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 DisplayInfo info = DisplayInfo();
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 float xdpi = hwConfig->getDpiX();
809 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810
811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
812 // The density of the device is provided by a build property
813 float density = Density::getBuildDensity() / 160.0f;
814 if (density == 0) {
815 // the build doesn't provide a density -- this is wrong!
816 // use xdpi instead
817 ALOGE("ro.sf.lcd_density must be defined as a build property");
818 density = xdpi / 160.0f;
819 }
820 if (Density::getEmuDensity()) {
821 // if "qemu.sf.lcd_density" is specified, it overrides everything
822 xdpi = ydpi = density = Density::getEmuDensity();
823 density /= 160.0f;
824 }
825 info.density = density;
826
827 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800829 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 } else {
831 // TODO: where should this value come from?
832 static const int TV_DENSITY = 213;
833 info.density = TV_DENSITY / 160.0f;
834 info.orientation = 0;
835 }
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 info.xdpi = xdpi;
840 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900842 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843
Andy McFadden91b2ca82014-06-13 14:04:23 -0700844 // This is how far in advance a buffer must be queued for
845 // presentation at a given time. If you want a buffer to appear
846 // on the screen at time N, you must submit the buffer before
847 // (N - presentationDeadline).
848 //
849 // Normally it's one full refresh period (to give SF a chance to
850 // latch the buffer), but this can be reduced by configuring a
851 // DispSync offset. Any additional delays introduced by the hardware
852 // composer or panel must be accounted for here.
853 //
854 // We add an additional 1ms to allow for processing time and
855 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800857 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
859 // All non-virtual displays are currently considered secure.
860 info.secure = true;
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800870 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
876 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
878 return NO_ERROR;
879}
880
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700881int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800882 if (display == nullptr) {
883 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
887 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800888 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700889 return device->getActiveConfig();
890 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700891
Dan Stoza24a42e92015-03-09 10:04:11 -0700892 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
896 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
897 this);
898 int32_t type = hw->getDisplayType();
899 int currentMode = hw->getActiveConfig();
900
901 if (mode == currentMode) {
902 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
903 return;
904 }
905
906 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
907 ALOGW("Trying to set config for virtual display");
908 return;
909 }
910
911 hw->setActiveConfig(mode);
912 getHwComposer().setActiveConfig(type, mode);
913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
916 class MessageSetActiveConfig: public MessageBase {
917 SurfaceFlinger& mFlinger;
918 sp<IBinder> mDisplay;
919 int mMode;
920 public:
921 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
922 int mode) :
923 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
924 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700925 Vector<DisplayInfo> configs;
926 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700927 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700928 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700929 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700931 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700935 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
937 ALOGW("Attempt to set active config = %d for virtual display",
938 mMode);
939 } else {
940 mFlinger.setActiveConfigInternal(hw, mMode);
941 }
942 return true;
943 }
944 };
945 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
946 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700947 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700948}
Michael Wright28f24d02016-07-12 13:30:53 -0700949status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700950 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
952 return BAD_VALUE;
953 }
954
955 if (!display.get()) {
956 return NAME_NOT_FOUND;
957 }
958
959 int32_t type = NAME_NOT_FOUND;
960 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
961 if (display == mBuiltinDisplays[i]) {
962 type = i;
963 break;
964 }
965 }
966
967 if (type < 0) {
968 return type;
969 }
970
Peiyong Lina52f0292018-03-14 17:26:31 -0700971 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700972 {
973 ConditionalLock _l(mStateLock,
974 std::this_thread::get_id() != mMainThreadId);
975 modes = getHwComposer().getColorModes(type);
976 }
Michael Wright28f24d02016-07-12 13:30:53 -0700977 outColorModes->clear();
978 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
979
980 return NO_ERROR;
981}
982
Peiyong Lina52f0292018-03-14 17:26:31 -0700983ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700984 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700985 if (device != nullptr) {
986 return device->getActiveColorMode();
987 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700989}
990
991void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700993 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700995
996 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return;
998 }
999
1000 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1001 ALOGW("Trying to set config for virtual display");
1002 return;
1003 }
1004
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1006 hw->getDisplayType());
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 hw->setActiveColorMode(mode);
1009 getHwComposer().setActiveColorMode(type, mode);
1010}
1011
1012
1013status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 class MessageSetActiveColorMode: public MessageBase {
1016 SurfaceFlinger& mFlinger;
1017 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001019 public:
1020 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001022 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1023 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 mFlinger.getDisplayColorModes(mDisplay, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001028 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1029 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001030 return true;
1031 }
1032 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1033 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001034 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1035 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001036 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001037 ALOGW("Attempt to set active color mode %s %d for virtual display",
1038 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001039 } else {
1040 mFlinger.setActiveColorModeInternal(hw, mMode);
1041 }
1042 return true;
1043 }
1044 };
1045 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1046 postMessageSync(msg);
1047 return NO_ERROR;
1048}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049
Svetoslavd85084b2014-03-20 10:28:31 -07001050status_t SurfaceFlinger::clearAnimationFrameStats() {
1051 Mutex::Autolock _l(mStateLock);
1052 mAnimFrameTracker.clearStats();
1053 return NO_ERROR;
1054}
1055
1056status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1057 Mutex::Autolock _l(mStateLock);
1058 mAnimFrameTracker.getStats(outStats);
1059 return NO_ERROR;
1060}
1061
Dan Stozac4f471e2016-03-24 09:31:08 -07001062status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1063 HdrCapabilities* outCapabilities) const {
1064 Mutex::Autolock _l(mStateLock);
1065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001066 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 if (displayDevice == nullptr) {
1068 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1069 return BAD_VALUE;
1070 }
1071
1072 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001073 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001075 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1076 // insert HDR10 as we will force client composition for HDR10
1077 // layers
1078 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1079 types.push_back(HAL_HDR_HDR10);
1080
1081 *outCapabilities = HdrCapabilities(types,
1082 capabilities->getDesiredMaxLuminance(),
1083 capabilities->getDesiredMaxAverageLuminance(),
1084 capabilities->getDesiredMinLuminance());
1085 } else {
1086 *outCapabilities = std::move(*capabilities);
1087 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 } else {
1089 return BAD_VALUE;
1090 }
1091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
1103 if (enable) {
1104 ALOGV("VSync Injections enabled");
1105 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001106 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001107 mInjectorEventThread =
1108 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 });
1119 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 IPCThreadState* ipc = IPCThreadState::self();
1140 const int pid = ipc->getCallingPid();
1141 const int uid = ipc->getCallingUid();
1142 if ((uid != AID_SHELL) &&
1143 !PermissionCache::checkPermission(sDump, pid, uid)) {
1144 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1145 return PERMISSION_DENIED;
1146 }
1147
1148 // Try to acquire a lock for 1s, fail gracefully
1149 const status_t err = mStateLock.timedLock(s2ns(1));
1150 const bool locked = (err == NO_ERROR);
1151 if (!locked) {
1152 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1153 return TIMED_OUT;
1154 }
1155
1156 outLayers->clear();
1157 mCurrentState.traverseInZOrder([&](Layer* layer) {
1158 outLayers->push_back(layer->getLayerDebugInfo());
1159 });
1160
1161 mStateLock.unlock();
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
1169 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1170 return mSFEventThread->createEventConnection();
1171 } else {
1172 return mEventThread->createEventConnection();
1173 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001174}
1175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177
1178void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001179 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180}
1181
1182void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001183 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184}
1185
1186void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001191 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001196 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001201 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203 if (res == NO_ERROR) {
1204 msg->wait();
1205 }
1206 return res;
1207}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001210 do {
1211 waitForEvent();
1212 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213}
1214
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215void SurfaceFlinger::enableHardwareVsync() {
1216 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1220 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 Mutex::Autolock _l(mHWVsyncLock);
1227
Jesse Hall948fe0c2013-10-14 12:56:09 -07001228 if (makeAvailable) {
1229 mHWVsyncAvailable = true;
1230 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 // Hardware vsync is not currently available, so abort the resync
1232 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 return;
1234 }
1235
David Sodman105b7dc2017-11-04 20:28:14 -07001236 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238
1239 mPrimaryDispSync.reset();
1240 mPrimaryDispSync.setPeriod(period);
1241
1242 if (!mPrimaryHWVsyncEnabled) {
1243 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1245 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryHWVsyncEnabled = true;
1247 }
1248}
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 Mutex::Autolock _l(mHWVsyncLock);
1252 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1254 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.endResync();
1256 mPrimaryHWVsyncEnabled = false;
1257 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeUnavailable) {
1259 mHWVsyncAvailable = false;
1260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Tim Murray4a4e4a22016-04-19 16:29:23 +00001263void SurfaceFlinger::resyncWithRateLimit() {
1264 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001265
1266 // No explicit locking is needed here since EventThread holds a lock while calling this method
1267 static nsecs_t sLastResyncAttempted = 0;
1268 const nsecs_t now = systemTime();
1269 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271 }
Dan Stoza57164302017-05-08 14:03:54 -07001272 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001273}
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1276 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001277 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001278 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001279 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 return;
1281 }
1282
1283 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001284 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001285 return;
1286 }
1287
Jamie Gennisd1700752013-10-14 12:22:52 -07001288 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 { // Scope for the lock
1291 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001295 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001296
1297 if (needsHwVsync) {
1298 enableHardwareVsync();
1299 } else {
1300 disableHardwareVsync(false);
1301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302}
1303
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001304void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001305 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1306 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001307}
1308
Lloyd Pique715a2c12017-12-14 17:18:08 -08001309void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1310 HWC2::Connection connection) {
1311 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1312 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313
Lloyd Piqueba04e622017-12-14 17:11:26 -08001314 // Ignore events that do not have the right sequenceId.
1315 if (sequenceId != getBE().mComposerSequenceId) {
1316 return;
1317 }
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Only lock if we're not on the main thread. This function is normally
1320 // called on a hwbinder thread, but for the primary display it's called on
1321 // the main thread with the state lock already held, so don't attempt to
1322 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001323 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001324
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001326
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001327 if (std::this_thread::get_id() == mMainThreadId) {
1328 // Process all pending hot plug events immediately if we are on the main thread.
1329 processDisplayHotplugEventsLocked();
1330 }
1331
Lloyd Piqueba04e622017-12-14 17:11:26 -08001332 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001333}
1334
Steven Thomasb02664d2017-07-26 18:48:28 -07001335void SurfaceFlinger::onRefreshReceived(int sequenceId,
1336 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001340 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001341 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001342}
1343
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001347 getHwComposer().setVsyncEnabled(disp,
1348 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001349}
1350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001352void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354 // Clear the drawing state so that the logic inside of
1355 // handleTransactionLocked will fire. It will determine the delta between
1356 // mCurrentState and mDrawingState and re-apply all changes when we make the
1357 // transition.
1358 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001359 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 mDisplays.clear();
1361}
1362
Steven Thomas050b2c82017-03-06 11:45:16 -08001363void SurfaceFlinger::updateVrFlinger() {
1364 if (!mVrFlinger)
1365 return;
1366 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001368 return;
1369 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 ALOGE("Vr flinger is only supported for remote hardware composer"
1373 " service connections. Ignoring request to transition to vr"
1374 " flinger.");
1375 mVrFlingerRequestsDisplay = false;
1376 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 int currentDisplayPowerMode = getDisplayDeviceLocked(
1382 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001389 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001390 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1391 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001392 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
David Sodman105b7dc2017-11-04 20:28:14 -07001394 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1395 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001396
1397 if (vrFlingerRequestsDisplay) {
1398 mVrFlinger->GrantDisplayOwnership();
1399 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
1403 mVisibleRegionsDirty = true;
1404 invalidateHwcGeometry();
1405
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001406 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1408 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1409 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001412 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 const nsecs_t period = activeConfig->getVsyncPeriod();
1414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Use phase of 0 since phase is not known.
1417 // Use latency of 0, which will snap to the ideal latency.
1418 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 android_atomic_or(1, &mRepaintEverything);
1421 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422}
1423
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001425 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001428 bool frameMissed = !mHadClientComposition &&
1429 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 (mPreviousPresentFence->getSignalTime() ==
1431 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001432 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001433 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001434 signalLayerUpdate();
1435 break;
1436 }
1437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001447 // Signal a refresh if a transaction modified the window state,
1448 // a new buffer was latched, or if HWC has requested a full
1449 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 signalRefresh();
1451 }
1452 break;
1453 }
1454 case MessageQueue::REFRESH: {
1455 handleMessageRefresh();
1456 break;
1457 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 }
1459}
1460
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001462 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001464 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468}
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473}
1474
1475void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001477
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001478 mRefreshPending = false;
1479
Chia-I Wu30505fb2018-03-26 16:20:31 -07001480 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001481
Chia-I Wu30505fb2018-03-26 16:20:31 -07001482 preComposition(refreshStartTime);
1483 rebuildLayerStacks();
1484 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001485 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001486 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001487 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001488 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001489 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492
1493 mHadClientComposition = false;
1494 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1495 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1496 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001497 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001499
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503void SurfaceFlinger::doDebugFlashRegions()
1504{
1505 // is debugging enabled
1506 if (CC_LIKELY(!mDebugRegion))
1507 return;
1508
1509 const bool repaintEverything = mRepaintEverything;
1510 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1511 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001512 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 // transform the dirty region into this screen's coordinate space
1514 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1515 if (!dirtyRegion.isEmpty()) {
1516 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001517 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518
1519 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001521 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001522 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1523
Mathias Agopianda27af92012-09-13 18:17:13 -07001524 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 }
1526 }
1527 }
1528
1529 postFramebuffer();
1530
1531 if (mDebugRegion > 1) {
1532 usleep(mDebugRegion * 1000);
1533 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001534
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001536 auto& displayDevice = mDisplays[displayId];
1537 if (!displayDevice->isDisplayOn()) {
1538 continue;
1539 }
1540
David Sodman105b7dc2017-11-04 20:28:14 -07001541 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1542 ALOGE_IF(result != NO_ERROR,
1543 "prepareFrame for display %zd failed:"
1544 " %d (%s)",
1545 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001546 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
1548
Adrian Roos1e1a1282017-11-01 19:05:31 +01001549void SurfaceFlinger::doTracing(const char* where) {
1550 ATRACE_CALL();
1551 ATRACE_NAME(where);
1552 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001553 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001554 }
1555}
1556
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001557void SurfaceFlinger::logLayerStats() {
1558 ATRACE_CALL();
1559 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1560 int32_t hwcId = -1;
1561 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1562 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1563 if (displayDevice->isPrimary()) {
1564 hwcId = displayDevice->getHwcDisplayId();
1565 break;
1566 }
1567 }
1568 if (hwcId < 0) {
1569 ALOGE("LayerStats: Hmmm, no primary display?");
1570 return;
1571 }
1572 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1573 }
1574}
1575
Chia-I Wu30505fb2018-03-26 16:20:31 -07001576void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001578 ATRACE_CALL();
1579 ALOGV("preComposition");
1580
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001583 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 needExtraInvalidate = true;
1585 }
Robert Carr2047fae2016-11-28 14:09:09 -08001586 });
1587
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 if (needExtraInvalidate) {
1589 signalLayerUpdate();
1590 }
1591}
1592
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593void SurfaceFlinger::updateCompositorTiming(
1594 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1595 std::shared_ptr<FenceTime>& presentFenceTime) {
1596 // Update queue of past composite+present times and determine the
1597 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001598 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001600 while (!getBE().mCompositePresentTimes.empty()) {
1601 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 // Cached values should have been updated before calling this method,
1603 // which helps avoid duplicate syscalls.
1604 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1605 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1606 break;
1607 }
1608 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001609 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610 }
1611
1612 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001613 while (getBE().mCompositePresentTimes.size() > 16) {
1614 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 }
1616
Brian Andersond0010582017-03-07 13:20:31 -08001617 setCompositorTimingSnapped(
1618 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1619}
1620
1621void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1622 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 // Integer division and modulo round toward 0 not -inf, so we need to
1624 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001625 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1627 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1628
Brian Andersond0010582017-03-07 13:20:31 -08001629 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1630 if (idealLatency <= 0) {
1631 idealLatency = vsyncInterval;
1632 }
1633
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Snap the latency to a value that removes scheduling jitter from the
1635 // composition and present times, which often have >1ms of jitter.
1636 // Reducing jitter is important if an app attempts to extrapolate
1637 // something (such as user input) to an accurate diasplay time.
1638 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1639 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001640 nsecs_t bias = vsyncInterval / 2;
1641 int64_t extraVsyncs =
1642 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1643 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1644 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645
David Sodman99974d22017-11-28 12:04:33 -08001646 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1647 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1648 getBE().mCompositorTiming.interval = vsyncInterval;
1649 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650}
1651
Chia-I Wu30505fb2018-03-26 16:20:31 -07001652void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 ATRACE_CALL();
1655 ALOGV("postComposition");
1656
Brian Anderson3546a3f2016-07-14 11:51:14 -07001657 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001658 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001659 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001660 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001661 }
1662
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001663 // |mStateLock| not needed as we are on the main thread
1664 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001665
David Sodman73beded2017-11-15 11:56:06 -08001666 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001667 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001668 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669 glCompositionDoneFenceTime =
1670 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001671 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001672 } else {
1673 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1674 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675
David Sodman73beded2017-11-15 11:56:06 -08001676 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001677 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001678 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001679 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001680
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1682 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1683
Chia-I Wu30505fb2018-03-26 16:20:31 -07001684 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 // when we started doing work for this frame, but that should be okay
1686 // since updateCompositorTiming has snapping logic.
1687 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001688 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001689 CompositorTiming compositorTiming;
1690 {
David Sodman99974d22017-11-28 12:04:33 -08001691 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1692 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001693 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694
Robert Carr2047fae2016-11-28 14:09:09 -08001695 mDrawingState.traverseInZOrder([&](Layer* layer) {
1696 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001697 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001698 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001699 recordBufferingStats(layer->getName().string(),
1700 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001701 }
Robert Carr2047fae2016-11-28 14:09:09 -08001702 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001703
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001704 if (presentFenceTime->isValid()) {
1705 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001706 enableHardwareVsync();
1707 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001708 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001709 }
1710 }
1711
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001712 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001713 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001714 enableHardwareVsync();
1715 }
1716 }
1717
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718 if (mAnimCompositionPending) {
1719 mAnimCompositionPending = false;
1720
Brian Anderson4e606e32017-03-16 15:34:57 -07001721 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001723 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001724 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001725 // The HWC doesn't support present fences, so use the refresh
1726 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001727 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001728 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 mAnimFrameTracker.setActualPresentTime(presentTime);
1730 }
1731 mAnimFrameTracker.advanceFrame();
1732 }
Dan Stozab90cf072015-03-05 11:05:59 -08001733
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001734 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1735 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001736 return;
1737 }
1738
1739 nsecs_t currentTime = systemTime();
1740 if (mHasPoweredOff) {
1741 mHasPoweredOff = false;
1742 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001743 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001745 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1746 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001747 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001748 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001749 }
David Sodman4a36e932017-11-07 14:29:47 -08001750 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001751 }
David Sodman4a36e932017-11-07 14:29:47 -08001752 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753}
1754
1755void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 ATRACE_CALL();
1757 ALOGV("rebuildLayerStacks");
1758
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001761 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 mVisibleRegionsDirty = false;
1763 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001764
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1766 Region opaqueRegion;
1767 Region dirtyRegion;
1768 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001769 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1771 const Transform& tr(displayDevice->getTransform());
1772 const Rect bounds(displayDevice->getBounds());
1773 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001774 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001775
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001777 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001778 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1779 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 Region drawRegion(tr.transform(
1781 layer->visibleNonTransparentRegion));
1782 drawRegion.andSelf(bounds);
1783 if (!drawRegion.isEmpty()) {
1784 layersSortedByZ.add(layer);
1785 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001786 // Clear out the HWC layer if this layer was
1787 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001788 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001789 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001790 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001791 } else {
1792 // WM changes displayDevice->layerStack upon sleep/awake.
1793 // Here we make sure we delete the HWC layers even if
1794 // WM changed their layer stack.
1795 hwcLayerDestroyed = layer->destroyHwcLayer(
1796 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001797 }
1798
1799 // If a layer is not going to get a release fence because
1800 // it is invisible, but it is also going to release its
1801 // old buffer, add it to the list of layers needing
1802 // fences.
1803 if (hwcLayerDestroyed) {
1804 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1805 mLayersWithQueuedFrames.cend(), layer);
1806 if (found != mLayersWithQueuedFrames.cend()) {
1807 layersNeedingFences.add(layer);
1808 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001809 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 });
1811 }
1812 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001813 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 displayDevice->undefinedRegion.set(bounds);
1815 displayDevice->undefinedRegion.subtractSelf(
1816 tr.transform(opaqueRegion));
1817 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001821
Romain Guy0147a172017-06-01 13:53:56 -07001822mat4 SurfaceFlinger::computeSaturationMatrix() const {
1823 if (mSaturation == 1.0f) {
1824 return mat4();
1825 }
1826
1827 // Rec.709 luma coefficients
1828 float3 luminance{0.213f, 0.715f, 0.072f};
1829 luminance *= 1.0f - mSaturation;
1830 return mat4(
1831 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1832 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1833 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1834 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1835 );
1836}
1837
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001838// pickColorMode translates a given dataspace into the best available color mode.
1839// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001840ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001841 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001842 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001843 }
1844
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001845 switch (dataSpace) {
1846 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1847 // system expects.
1848 case HAL_DATASPACE_UNKNOWN:
1849 case HAL_DATASPACE_SRGB:
1850 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001851 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001852 break;
1853
1854 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001855 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001856 break;
1857
1858 default:
1859 // TODO (courtneygo): Do we want to assert an error here?
1860 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1861 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001862 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001863 break;
1864 }
1865}
1866
Romain Guy0147a172017-06-01 13:53:56 -07001867android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001868 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869 // Only support sRGB and Display-P3 right now.
1870 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1871 return HAL_DATASPACE_DISPLAY_P3;
1872 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001873 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1874 return HAL_DATASPACE_DISPLAY_P3;
1875 }
1876 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1877 return HAL_DATASPACE_DISPLAY_P3;
1878 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001879 if (!hasHdr) {
1880 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1881 return HAL_DATASPACE_DISPLAY_P3;
1882 }
1883 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1884 return HAL_DATASPACE_DISPLAY_P3;
1885 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001886 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001887
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001888 return HAL_DATASPACE_V0_SRGB;
1889}
1890
Chia-I Wu30505fb2018-03-26 16:20:31 -07001891void SurfaceFlinger::setUpHWComposer() {
1892 ATRACE_CALL();
1893 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894
Jesse Hall028dc8f2013-08-20 16:35:32 -07001895 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001896 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1897 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1898 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1899
1900 // If nothing has changed (!dirty), don't recompose.
1901 // If something changed, but we don't currently have any visible layers,
1902 // and didn't when we last did a composition, then skip it this time.
1903 // The second rule does two things:
1904 // - When all layers are removed from a display, we'll emit one black
1905 // frame, then nothing more until we get new layers.
1906 // - When a display is created with a private layer stack, we won't
1907 // emit any black frames until a layer is added to the layer stack.
1908 bool mustRecompose = dirty && !(empty && wasEmpty);
1909
1910 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1911 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1912 mustRecompose ? "doing" : "skipping",
1913 dirty ? "+" : "-",
1914 empty ? "+" : "-",
1915 wasEmpty ? "+" : "-");
1916
Dan Stoza71433162014-02-04 16:22:36 -08001917 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001918
1919 if (mustRecompose) {
1920 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1921 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001922 }
1923
Chia-I Wu30505fb2018-03-26 16:20:31 -07001924 // build the h/w work list
1925 if (CC_UNLIKELY(mGeometryInvalid)) {
1926 mGeometryInvalid = false;
1927 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1928 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1929 const auto hwcId = displayDevice->getHwcDisplayId();
1930 if (hwcId >= 0) {
1931 const Vector<sp<Layer>>& currentLayers(
1932 displayDevice->getVisibleLayersSortedByZ());
1933 for (size_t i = 0; i < currentLayers.size(); i++) {
1934 const auto& layer = currentLayers[i];
1935 if (!layer->hasHwcLayer(hwcId)) {
1936 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1937 layer->forceClientComposition(hwcId);
1938 continue;
1939 }
1940 }
1941
1942 layer->setGeometry(displayDevice, i);
1943 if (mDebugDisableHWC || mDebugRegion) {
1944 layer->forceClientComposition(hwcId);
1945 }
1946 }
1947 }
1948 }
1949 }
1950
1951
1952 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
1953
1954 // Set the per-frame data
1955 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1956 auto& displayDevice = mDisplays[displayId];
1957 const auto hwcId = displayDevice->getHwcDisplayId();
1958
1959 if (hwcId < 0) {
1960 continue;
1961 }
1962 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08001963 displayDevice->setColorTransform(colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001964 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
1965 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1966 "display %zd: %d", displayId, result);
1967 }
1968 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1969 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1970 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
1971 !displayDevice->getHdrSupport()) {
1972 layer->forceClientComposition(hwcId);
1973 }
1974
1975 if (layer->getForceClientComposition(hwcId)) {
1976 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1977 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1978 continue;
1979 }
1980
1981 layer->setPerFrameData(displayDevice);
1982 }
1983
1984 if (hasWideColorDisplay) {
1985 ColorMode newColorMode;
1986 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1987
1988 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1989 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1990 displayDevice->getHdrSupport());
1991 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1992 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1993 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1994 }
1995 newColorMode = pickColorMode(newDataSpace);
1996
1997 setActiveColorModeInternal(displayDevice, newColorMode);
1998 }
1999 }
2000
2001 mPreviousColorMatrix = colorMatrix;
2002
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002004 auto& displayDevice = mDisplays[displayId];
2005 if (!displayDevice->isDisplayOn()) {
2006 continue;
2007 }
2008
David Sodman105b7dc2017-11-04 20:28:14 -07002009 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2011 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015void SurfaceFlinger::doComposition() {
2016 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ALOGV("doComposition");
2018
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002019 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002020 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002021 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002022 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 // transform the dirty region into this screen's coordinate space
2024 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002025
2026 // repaint the framebuffer (if needed)
2027 doDisplayComposition(hw, dirtyRegion);
2028
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002030 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002031 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002032 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002033 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002034}
2035
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036void SurfaceFlinger::postFramebuffer()
2037{
Mathias Agopian841cde52012-03-01 15:44:37 -08002038 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002040
Mathias Agopiana44b0412011-10-16 18:46:35 -07002041 const nsecs_t now = systemTime();
2042 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002043
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2045 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002046 if (!displayDevice->isDisplayOn()) {
2047 continue;
2048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 const auto hwcId = displayDevice->getHwcDisplayId();
2050 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002051 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002052 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002053 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002054 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002056 // The layer buffer from the previous frame (if any) is released
2057 // by HWC only when the release fence from this frame (if any) is
2058 // signaled. Always get the release fence from HWC first.
2059 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002060 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002061
2062 // If the layer was client composited in the previous frame, we
2063 // need to merge with the previous client target acquire fence.
2064 // Since we do not track that, always merge with the current
2065 // client target acquire fence when it is available, even though
2066 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002068 releaseFence = Fence::merge("LayerRelease", releaseFence,
2069 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002070 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002071
David Sodmanb8af7922017-12-21 15:17:55 -08002072 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 }
Chia-I Wu83806892017-11-16 10:50:20 -08002074
2075 // We've got a list of layers needing fences, that are disjoint with
2076 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2077 // supply them with the present fence.
2078 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002079 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002080 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002081 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002082 }
2083 }
2084
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002086 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002087 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002088 }
2089
Mathias Agopiana44b0412011-10-16 18:46:35 -07002090 mLastSwapBufferTime = systemTime() - now;
2091 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002092
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002093 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002094 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2095 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2096 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2097 logFrameStats();
2098 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002099 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002100}
2101
Mathias Agopian87baae12012-07-31 12:38:26 -07002102void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103{
Mathias Agopian841cde52012-03-01 15:44:37 -08002104 ATRACE_CALL();
2105
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002106 // here we keep a copy of the drawing state (that is the state that's
2107 // going to be overwritten by handleTransactionLocked()) outside of
2108 // mStateLock so that the side-effects of the State assignment
2109 // don't happen with mStateLock held (which can cause deadlocks).
2110 State drawingState(mDrawingState);
2111
Mathias Agopianca4d3602011-05-19 15:38:14 -07002112 Mutex::Autolock _l(mStateLock);
2113 const nsecs_t now = systemTime();
2114 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115
Mathias Agopianca4d3602011-05-19 15:38:14 -07002116 // Here we're guaranteed that some transaction flags are set
2117 // so we can call handleTransactionLocked() unconditionally.
2118 // We call getTransactionFlags(), which will also clear the flags,
2119 // with mStateLock held to guarantee that mCurrentState won't change
2120 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002121
Mathias Agopiane57f2922012-08-09 16:29:12 -07002122 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002123 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002124
Mathias Agopianca4d3602011-05-19 15:38:14 -07002125 mLastTransactionTime = systemTime() - now;
2126 mDebugInTransaction = 0;
2127 invalidateHwcGeometry();
2128 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002129}
2130
Lloyd Pique715a2c12017-12-14 17:18:08 -08002131DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002132 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002133 // Figure out whether the event is for the primary display or an
2134 // external display by matching the Hwc display id against one for a
2135 // connected display. If we did not find a match, we then check what
2136 // displays are not already connected to determine the type. If we don't
2137 // have a connected primary display, we assume the new display is meant to
2138 // be the primary display, and then if we don't have an external display,
2139 // we assume it is that.
2140 const auto primaryDisplayId =
2141 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2142 const auto externalDisplayId =
2143 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2144 if (primaryDisplayId && primaryDisplayId == display) {
2145 return DisplayDevice::DISPLAY_PRIMARY;
2146 } else if (externalDisplayId && externalDisplayId == display) {
2147 return DisplayDevice::DISPLAY_EXTERNAL;
2148 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2149 return DisplayDevice::DISPLAY_PRIMARY;
2150 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2151 return DisplayDevice::DISPLAY_EXTERNAL;
2152 }
2153
2154 return DisplayDevice::DISPLAY_ID_INVALID;
2155}
2156
Lloyd Piqueba04e622017-12-14 17:11:26 -08002157void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2158 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002159 auto displayType = determineDisplayType(event.display, event.connection);
2160 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2161 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2162 continue;
2163 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002164
2165 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2166 ALOGE("External displays are not supported by the vr hardware composer.");
2167 continue;
2168 }
2169
Lloyd Pique715a2c12017-12-14 17:18:08 -08002170 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002171
2172 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002173 if (!mBuiltinDisplays[displayType].get()) {
2174 ALOGV("Creating built in display %d", displayType);
2175 mBuiltinDisplays[displayType] = new BBinder();
2176 // All non-virtual displays are currently considered secure.
2177 DisplayDeviceState info(displayType, true);
2178 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2179 "Built-in Screen" : "External Screen";
2180 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2181 mInterceptor->saveDisplayCreation(info);
2182 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002183 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002184 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002185
Lloyd Piquefcd86612017-12-14 17:15:36 -08002186 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2187 if (idx >= 0) {
2188 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4dccc412018-01-22 17:21:36 -08002189 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002190 mCurrentState.displays.removeItemsAt(idx);
2191 }
2192 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193 }
2194
2195 processDisplayChangesLocked();
2196 }
2197
2198 mPendingHotplugEvents.clear();
2199}
2200
Lloyd Pique99d3da52018-01-22 17:48:03 -08002201sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2202 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2203 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2204 bool hasWideColorSupport = false;
2205 if (hasWideColorDisplay) {
2206 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2207 for (ColorMode colorMode : modes) {
2208 switch (colorMode) {
2209 case ColorMode::DISPLAY_P3:
2210 case ColorMode::ADOBE_RGB:
2211 case ColorMode::DCI_P3:
2212 hasWideColorSupport = true;
2213 break;
2214 default:
2215 break;
2216 }
2217 }
2218 }
2219
2220 bool hasHdrSupport = false;
2221 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2222 getHwComposer().getHdrCapabilities(state.type);
2223 if (hdrCapabilities) {
2224 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2225 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2226 hasHdrSupport = iter != types.cend();
2227 }
2228
2229 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2230 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2231
2232 /*
2233 * Create our display's surface
2234 */
2235 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2236 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2237 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2238 renderSurface->setNativeWindow(nativeWindow.get());
2239 const int displayWidth = renderSurface->queryWidth();
2240 const int displayHeight = renderSurface->queryHeight();
2241
2242 // Make sure that composition can never be stalled by a virtual display
2243 // consumer that isn't processing buffers fast enough. We have to do this
2244 // in two places:
2245 // * Here, in case the display is composed entirely by HWC.
2246 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2247 // window's swap interval in eglMakeCurrent, so they'll override the
2248 // interval we set here.
2249 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2250 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2251 }
2252
2253 // virtual displays are always considered enabled
2254 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2255 : HWC_POWER_MODE_OFF;
2256
2257 sp<DisplayDevice> hw =
2258 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2259 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2260 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2261
2262 if (maxFrameBufferAcquiredBuffers >= 3) {
2263 nativeWindowSurface->preallocateBuffers();
2264 }
2265
2266 ColorMode defaultColorMode = ColorMode::NATIVE;
2267 if (hasWideColorSupport) {
2268 defaultColorMode = ColorMode::SRGB;
2269 }
2270 setActiveColorModeInternal(hw, defaultColorMode);
2271 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2272 hw->setLayerStack(state.layerStack);
2273 hw->setProjection(state.orientation, state.viewport, state.frame);
2274 hw->setDisplayName(state.displayName);
2275
2276 return hw;
2277}
2278
Lloyd Pique347200f2017-12-14 17:00:15 -08002279void SurfaceFlinger::processDisplayChangesLocked() {
2280 // here we take advantage of Vector's copy-on-write semantics to
2281 // improve performance by skipping the transaction entirely when
2282 // know that the lists are identical
2283 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2284 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2285 if (!curr.isIdenticalTo(draw)) {
2286 mVisibleRegionsDirty = true;
2287 const size_t cc = curr.size();
2288 size_t dc = draw.size();
2289
2290 // find the displays that were removed
2291 // (ie: in drawing state but not in current state)
2292 // also handle displays that changed
2293 // (ie: displays that are in both lists)
2294 for (size_t i = 0; i < dc;) {
2295 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2296 if (j < 0) {
2297 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002298 // Call makeCurrent() on the primary display so we can
2299 // be sure that nothing associated with this display
2300 // is current.
2301 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2302 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2303 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2304 if (hw != nullptr) hw->disconnect(getHwComposer());
2305 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2306 mEventThread->onHotplugReceived(draw[i].type, false);
2307 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002308 } else {
2309 // this display is in both lists. see if something changed.
2310 const DisplayDeviceState& state(curr[j]);
2311 const wp<IBinder>& display(curr.keyAt(j));
2312 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2313 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2314 if (state_binder != draw_binder) {
2315 // changing the surface is like destroying and
2316 // recreating the DisplayDevice, so we just remove it
2317 // from the drawing state, so that it get re-added
2318 // below.
2319 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2320 if (hw != nullptr) hw->disconnect(getHwComposer());
2321 mDisplays.removeItem(display);
2322 mDrawingState.displays.removeItemsAt(i);
2323 dc--;
2324 // at this point we must loop to the next item
2325 continue;
2326 }
2327
2328 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2329 if (disp != nullptr) {
2330 if (state.layerStack != draw[i].layerStack) {
2331 disp->setLayerStack(state.layerStack);
2332 }
2333 if ((state.orientation != draw[i].orientation) ||
2334 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2335 disp->setProjection(state.orientation, state.viewport, state.frame);
2336 }
2337 if (state.width != draw[i].width || state.height != draw[i].height) {
2338 disp->setDisplaySize(state.width, state.height);
2339 }
2340 }
2341 }
2342 ++i;
2343 }
2344
2345 // find displays that were added
2346 // (ie: in current state but not in drawing state)
2347 for (size_t i = 0; i < cc; i++) {
2348 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2349 const DisplayDeviceState& state(curr[i]);
2350
2351 sp<DisplaySurface> dispSurface;
2352 sp<IGraphicBufferProducer> producer;
2353 sp<IGraphicBufferProducer> bqProducer;
2354 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002355 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002356
2357 int32_t hwcId = -1;
2358 if (state.isVirtualDisplay()) {
2359 // Virtual displays without a surface are dormant:
2360 // they have external state (layer stack, projection,
2361 // etc.) but no internal state (i.e. a DisplayDevice).
2362 if (state.surface != nullptr) {
2363 // Allow VR composer to use virtual displays.
2364 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2365 int width = 0;
2366 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2367 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2368 int height = 0;
2369 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2370 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2371 int intFormat = 0;
2372 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2373 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2374 auto format = static_cast<android_pixel_format_t>(intFormat);
2375
2376 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2377 }
2378
2379 // TODO: Plumb requested format back up to consumer
2380
2381 sp<VirtualDisplaySurface> vds =
2382 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2383 bqProducer, bqConsumer,
2384 state.displayName);
2385
2386 dispSurface = vds;
2387 producer = vds;
2388 }
2389 } else {
2390 ALOGE_IF(state.surface != nullptr,
2391 "adding a supported display, but rendering "
2392 "surface is provided (%p), ignoring it",
2393 state.surface.get());
2394
2395 hwcId = state.type;
2396 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2397 producer = bqProducer;
2398 }
2399
2400 const wp<IBinder>& display(curr.keyAt(i));
2401 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 mDisplays.add(display,
2403 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2404 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002405 if (!state.isVirtualDisplay()) {
2406 mEventThread->onHotplugReceived(state.type, true);
2407 }
2408 }
2409 }
2410 }
2411 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412
2413 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002414}
2415
Mathias Agopian87baae12012-07-31 12:38:26 -07002416void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002417{
Dan Stoza7dde5992015-05-22 09:51:44 -07002418 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002419 mCurrentState.traverseInZOrder([](Layer* layer) {
2420 layer->notifyAvailableFrames();
2421 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002422
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 /*
2424 * Traversal of the children
2425 * (perform the transaction for each of them if needed)
2426 */
2427
Mathias Agopian3559b072012-08-15 13:46:03 -07002428 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002429 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002431 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432
2433 const uint32_t flags = layer->doTransaction(0);
2434 if (flags & Layer::eVisibleRegion)
2435 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002436 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437 }
2438
2439 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002440 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441 */
2442
Mathias Agopiane57f2922012-08-09 16:29:12 -07002443 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002445 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002446 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447
Mathias Agopian84300952012-11-21 16:02:13 -08002448 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2449 // The transform hint might have changed for some layers
2450 // (either because a display has changed, or because a layer
2451 // as changed).
2452 //
2453 // Walk through all the layers in currentLayers,
2454 // and update their transform hint.
2455 //
2456 // If a layer is visible only on a single display, then that
2457 // display is used to calculate the hint, otherwise we use the
2458 // default display.
2459 //
2460 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2461 // the hint is set before we acquire a buffer from the surface texture.
2462 //
2463 // NOTE: layer transactions have taken place already, so we use their
2464 // drawing state. However, SurfaceFlinger's own transaction has not
2465 // happened yet, so we must use the current state layer list
2466 // (soon to become the drawing state list).
2467 //
2468 sp<const DisplayDevice> disp;
2469 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002470 bool first = true;
2471 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002472 // NOTE: we rely on the fact that layers are sorted by
2473 // layerStack first (so we don't have to traverse the list
2474 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002475 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002476 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002477 currentlayerStack = layerStack;
2478 // figure out if this layerstack is mirrored
2479 // (more than one display) if so, pick the default display,
2480 // if not, pick the only display it's on.
2481 disp.clear();
2482 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2483 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002484 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002485 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002486 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002487 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002488 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002489 break;
2490 }
2491 }
2492 }
2493 }
Chet Haase91d25932013-04-11 15:24:55 -07002494
Robert Carr56a0b9a2017-12-04 16:06:13 -08002495 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002496 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002497 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2498 // redraw after transform hint changes. See bug 8508397.
2499
2500 // could be null when this layer is using a layerStack
2501 // that is not visible on any display. Also can occur at
2502 // screen off/on times.
2503 disp = getDefaultDisplayDeviceLocked();
2504 }
2505 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002506 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002507 if (disp != nullptr) {
2508 layer->updateTransformHint(disp);
2509 }
Robert Carr2047fae2016-11-28 14:09:09 -08002510
2511 first = false;
2512 });
Mathias Agopian84300952012-11-21 16:02:13 -08002513 }
2514
2515
Mathias Agopian3559b072012-08-15 13:46:03 -07002516 /*
2517 * Perform our own transaction if needed
2518 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002519
2520 if (mLayersAdded) {
2521 mLayersAdded = false;
2522 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002523 mVisibleRegionsDirty = true;
2524 }
2525
2526 // some layers might have been removed, so
2527 // we need to update the regions they're exposing.
2528 if (mLayersRemoved) {
2529 mLayersRemoved = false;
2530 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002531 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002533 // this layer is not visible anymore
2534 // TODO: we could traverse the tree from front to back and
2535 // compute the actual visible region
2536 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537 Region visibleReg;
2538 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002539 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002540 }
Robert Carr2047fae2016-11-28 14:09:09 -08002541 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542 }
2543
2544 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002545
2546 updateCursorAsync();
2547}
2548
2549void SurfaceFlinger::updateCursorAsync()
2550{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2552 auto& displayDevice = mDisplays[displayId];
2553 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002554 continue;
2555 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556
2557 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2558 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002559 }
2560 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002561}
2562
2563void SurfaceFlinger::commitTransaction()
2564{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002565 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002566 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567 for (const auto& l : mLayersPendingRemoval) {
2568 recordBufferingStats(l->getName().string(),
2569 l->getOccupancyHistory(true));
2570 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002571 }
2572 mLayersPendingRemoval.clear();
2573 }
2574
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002575 // If this transaction is part of a window animation then the next frame
2576 // we composite should be considered an animation as well.
2577 mAnimCompositionPending = mAnimTransactionPending;
2578
Mathias Agopian4fec8732012-06-29 14:12:52 -07002579 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002580 mDrawingState.traverseInZOrder([](Layer* layer) {
2581 layer->commitChildList();
2582 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002583 mTransactionPending = false;
2584 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586}
2587
Chia-I Wuab0c3192017-08-01 11:29:00 -07002588void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002589 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590{
Mathias Agopian841cde52012-03-01 15:44:37 -08002591 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002593
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 Region aboveOpaqueLayers;
2595 Region aboveCoveredLayers;
2596 Region dirty;
2597
Mathias Agopian87baae12012-07-31 12:38:26 -07002598 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599
Robert Carr2047fae2016-11-28 14:09:09 -08002600 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002602 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603
Jesse Hall01e29052013-02-19 16:13:35 -08002604 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002605 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002606 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002607
Mathias Agopianab028732010-03-16 16:41:46 -07002608 /*
2609 * opaqueRegion: area of a surface that is fully opaque.
2610 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002612
2613 /*
2614 * visibleRegion: area of a surface that is visible on screen
2615 * and not fully transparent. This is essentially the layer's
2616 * footprint minus the opaque regions above it.
2617 * Areas covered by a translucent surface are considered visible.
2618 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002620
2621 /*
2622 * coveredRegion: area of a surface that is covered by all
2623 * visible regions above it (which includes the translucent areas).
2624 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002626
Jesse Halla8026d22012-09-25 13:25:04 -07002627 /*
2628 * transparentRegion: area of a surface that is hinted to be completely
2629 * transparent. This is only used to tell when the layer has no visible
2630 * non-transparent regions and can be removed from the layer list. It
2631 * does not affect the visibleRegion of this layer or any layers
2632 * beneath it. The hint may not be correct if apps don't respect the
2633 * SurfaceView restrictions (which, sadly, some don't).
2634 */
2635 Region transparentRegion;
2636
Mathias Agopianab028732010-03-16 16:41:46 -07002637
2638 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002639 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002640 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002644 if (!visibleRegion.isEmpty()) {
2645 // Remove the transparent area from the visible region
2646 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002647 if (tr.preserveRects()) {
2648 // transform the transparent region
2649 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002651 // transformation too complex, can't do the
2652 // transparent region optimization.
2653 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002654 }
Mathias Agopianab028732010-03-16 16:41:46 -07002655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Mathias Agopianab028732010-03-16 16:41:46 -07002657 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002658 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002659 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002660 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2661 // the opaque region is the layer's footprint
2662 opaqueRegion = visibleRegion;
2663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 }
2665 }
2666
Robert Carre5f4f692018-01-12 13:12:28 -08002667 if (visibleRegion.isEmpty()) {
2668 layer->clearVisibilityRegions();
2669 return;
2670 }
2671
Mathias Agopianab028732010-03-16 16:41:46 -07002672 // Clip the covered region to the visible region
2673 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2674
2675 // Update aboveCoveredLayers for next (lower) layer
2676 aboveCoveredLayers.orSelf(visibleRegion);
2677
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 // subtract the opaque region covered by the layers above us
2679 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680
2681 // compute this layer's dirty region
2682 if (layer->contentDirty) {
2683 // we need to invalidate the whole region
2684 dirty = visibleRegion;
2685 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002686 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 layer->contentDirty = false;
2688 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002689 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002690 * the exposed region consists of two components:
2691 * 1) what's VISIBLE now and was COVERED before
2692 * 2) what's EXPOSED now less what was EXPOSED before
2693 *
2694 * note that (1) is conservative, we start with the whole
2695 * visible region but only keep what used to be covered by
2696 * something -- which mean it may have been exposed.
2697 *
2698 * (2) handles areas that were not covered by anything but got
2699 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002700 */
Mathias Agopianab028732010-03-16 16:41:46 -07002701 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 const Region oldVisibleRegion = layer->visibleRegion;
2703 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002704 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2705 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706 }
2707 dirty.subtractSelf(aboveOpaqueLayers);
2708
2709 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002710 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711
Mathias Agopianab028732010-03-16 16:41:46 -07002712 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002714
Jesse Halla8026d22012-09-25 13:25:04 -07002715 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 layer->setVisibleRegion(visibleRegion);
2717 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002718 layer->setVisibleNonTransparentRegion(
2719 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002720 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721
Mathias Agopian87baae12012-07-31 12:38:26 -07002722 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723}
2724
Chia-I Wuab0c3192017-08-01 11:29:00 -07002725void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002726 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002727 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002728 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002729 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002730 }
2731 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002732}
2733
Dan Stoza6b9454d2014-11-07 16:00:59 -08002734bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 ALOGV("handlePageFlip");
2737
Brian Andersond6927fb2016-07-23 23:37:30 -07002738 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739
Mathias Agopian4fec8732012-06-29 14:12:52 -07002740 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002741 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002742 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002743
2744 // Store the set of layers that need updates. This set must not change as
2745 // buffers are being latched, as this could result in a deadlock.
2746 // Example: Two producers share the same command stream and:
2747 // 1.) Layer 0 is latched
2748 // 2.) Layer 0 gets a new frame
2749 // 2.) Layer 1 gets a new frame
2750 // 3.) Layer 1 is latched.
2751 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2752 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002753 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002754 if (layer->hasQueuedFrame()) {
2755 frameQueued = true;
2756 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002757 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002758 } else {
2759 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002760 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002761 } else {
2762 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002763 }
Robert Carr2047fae2016-11-28 14:09:09 -08002764 });
2765
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002767 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002768 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002769 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002770 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002771 newDataLatched = true;
2772 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002773 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002774
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002775 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002776
2777 // If we will need to wake up at some time in the future to deal with a
2778 // queued frame that shouldn't be displayed during this vsync period, wake
2779 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002780 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002781 signalLayerUpdate();
2782 }
2783
2784 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002785 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786}
2787
Mathias Agopianad456f92011-01-13 17:53:01 -08002788void SurfaceFlinger::invalidateHwcGeometry()
2789{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002791}
2792
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002793
Fabien Sanglard830b8472016-11-30 16:35:58 -08002794void SurfaceFlinger::doDisplayComposition(
2795 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002796 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797{
Dan Stoza71433162014-02-04 16:22:36 -08002798 // We only need to actually compose the display if:
2799 // 1) It is being handled by hardware composer, which may need this to
2800 // keep its virtual display state machine in sync, or
2801 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002802 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002803 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002805 return;
2806 }
2807
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002809 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002810
2811 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002812 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813}
2814
Chia-I Wub02087d2017-11-09 10:19:54 -08002815bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002816{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002818
Chia-I Wub02087d2017-11-09 10:19:54 -08002819 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002820 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002822
2823 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002824 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2825 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002826 if (applyColorMatrix) {
2827 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2828 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2829 }
2830
David Sodman105b7dc2017-11-04 20:28:14 -07002831 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 if (hasClientComposition) {
2833 ALOGV("hasClientComposition");
2834
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002835 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002836 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002837 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002838 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2839 }
2840 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2841
Chia-I Wu7f402902017-11-09 12:51:10 -08002842 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002843 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002845 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002846
2847 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002848 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002849 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2850 }
2851 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002852 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002853
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002854 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002855 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002857 // when using overlays, we assume a fully transparent framebuffer
2858 // NOTE: we could reduce how much we need to clear, for instance
2859 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002860 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002861 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002862 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002863 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002864 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002865 // we're left with the letterbox region
2866 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002868
2869 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002871
Mathias Agopianb9494d52012-04-18 02:28:45 -07002872 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002873 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002874 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002876 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002877 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002878
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002880 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002881 // scissor on the main display. It should never be needed
2882 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 const Rect& bounds(displayDevice->getBounds());
2884 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002885 if (scissor != bounds) {
2886 // scissor doesn't match the screen's dimensions, so we
2887 // need to clear everything outside of it and enable
2888 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002889
Mathias Agopianf45c5102012-10-24 16:29:17 -07002890 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002891 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002892 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002893 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002894 }
2895 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002896 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002897
Mathias Agopian85d751c2012-08-29 16:59:24 -07002898 /*
2899 * and then, render the layers targeted at the framebuffer
2900 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002901
Dan Stoza9e56aa02015-11-02 13:00:03 -08002902 ALOGV("Rendering client layers");
2903 const Transform& displayTransform = displayDevice->getTransform();
2904 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002905 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002906 bool firstLayer = true;
2907 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002908 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 displayTransform.transform(layer->visibleRegion)));
2910 ALOGV("Layer: %s", layer->getName().string());
2911 ALOGV(" Composition type: %s",
2912 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002913 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 switch (layer->getCompositionType(hwcId)) {
2915 case HWC2::Composition::Cursor:
2916 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002917 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002919 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002921 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002923 // never clear the very first layer since we're
2924 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002925 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002926 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002927 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002928 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002930 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002931 break;
2932 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002934 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002935 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 } else {
2937 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002940 }
2941 } else {
2942 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002944 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002946 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002947 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002948 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002949 }
2950 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002952 if (applyColorMatrix) {
2953 getRenderEngine().setupColorTransform(oldColorMatrix);
2954 }
2955
Mathias Agopianf45c5102012-10-24 16:29:17 -07002956 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002957 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002958 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959}
2960
Fabien Sanglard830b8472016-11-30 16:35:58 -08002961void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2962 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002963 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002964 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965}
2966
Dan Stoza7d89d062015-04-30 13:29:25 -07002967status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002968 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002969 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002970 const sp<Layer>& lbc,
2971 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002972{
Dan Stoza7d89d062015-04-30 13:29:25 -07002973 // add this layer to the current state list
2974 {
2975 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002977 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2978 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002979 return NO_MEMORY;
2980 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002981 if (parent == nullptr) {
2982 mCurrentState.layersSortedByZ.add(lbc);
2983 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002984 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002985 ALOGE("addClientLayer called with a removed parent");
2986 return NAME_NOT_FOUND;
2987 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 parent->addChild(lbc);
2989 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002990
Dan Stoza101d8dc2018-02-27 15:42:25 -08002991 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002992 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2993 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2994 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2995 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2996 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002997 mLayersAdded = true;
2998 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002999 }
3000
Mathias Agopian96f08192010-06-02 23:28:45 -07003001 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003002 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003003
Dan Stoza7d89d062015-04-30 13:29:25 -07003004 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003005}
3006
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003007status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003008 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003009 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3010}
Robert Carr7f9b8992017-03-10 11:08:39 -08003011
chaviwca27f252018-02-06 16:46:39 -08003012status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3013 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003014 if (layer->isPendingRemoval()) {
3015 return NO_ERROR;
3016 }
3017
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003019 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003021 if (topLevelOnly) {
3022 return NO_ERROR;
3023 }
3024
Chia-I Wu98f1c102017-05-30 14:54:08 -07003025 sp<Layer> ancestor = p;
3026 while (ancestor->getParent() != nullptr) {
3027 ancestor = ancestor->getParent();
3028 }
3029 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3030 ALOGE("removeLayer called with a layer whose parent has been removed");
3031 return NAME_NOT_FOUND;
3032 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003033
3034 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003035 } else {
3036 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003037 }
3038
Robert Carr136e2f62017-02-08 17:54:29 -08003039 // As a matter of normal operation, the LayerCleaner will produce a second
3040 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3041 // so we will succeed in promoting it, but it's already been removed
3042 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3043 // otherwise something has gone wrong and we are leaking the layer.
3044 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3046 layer->getName().string(),
3047 (p != nullptr) ? p->getName().string() : "no-parent");
3048 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003049 } else if (index < 0) {
3050 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003051 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052
Chia-I Wuc6657022017-08-15 11:18:17 -07003053 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003054 mLayersPendingRemoval.add(layer);
3055 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003056 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 setTransactionFlags(eTransactionNeeded);
3058 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059}
3060
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003061uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003062 return android_atomic_release_load(&mTransactionFlags);
3063}
3064
Mathias Agopian3f844832013-08-07 21:24:32 -07003065uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3067}
3068
Mathias Agopian3f844832013-08-07 21:24:32 -07003069uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3071 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003072 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 }
3074 return old;
3075}
3076
chaviwca27f252018-02-06 16:46:39 -08003077bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3078 for (const ComposerState& state : states) {
3079 // Here we need to check that the interface we're given is indeed
3080 // one of our own. A malicious client could give us a nullptr
3081 // IInterface, or one of its own or even one of our own but a
3082 // different type. All these situations would cause us to crash.
3083 if (state.client == nullptr) {
3084 return true;
3085 }
3086
3087 sp<IBinder> binder = IInterface::asBinder(state.client);
3088 if (binder == nullptr) {
3089 return true;
3090 }
3091
3092 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3093 return true;
3094 }
3095 }
3096 return false;
3097}
3098
Mathias Agopian8b33f032012-07-24 20:43:54 -07003099void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003100 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003101 const Vector<DisplayState>& displays,
3102 uint32_t flags)
3103{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003104 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003105 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003106 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003107
chaviwca27f252018-02-06 16:46:39 -08003108 if (containsAnyInvalidClientState(states)) {
3109 return;
3110 }
3111
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003112 if (flags & eAnimation) {
3113 // For window updates that are part of an animation we must wait for
3114 // previous animation "frames" to be handled.
3115 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003116 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003117 if (CC_UNLIKELY(err != NO_ERROR)) {
3118 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003119 // caller after a few seconds.
3120 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3121 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003122 mAnimTransactionPending = false;
3123 break;
3124 }
3125 }
3126 }
3127
chaviwca27f252018-02-06 16:46:39 -08003128 for (const DisplayState& display : displays) {
3129 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003130 }
3131
chaviwca27f252018-02-06 16:46:39 -08003132 for (const ComposerState& state : states) {
3133 transactionFlags |= setClientStateLocked(state);
3134 }
3135
3136 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3137 // as destroyed should only occur after setting all other states. This is to allow for a
3138 // child re-parent to happen before marking its original parent as destroyed (which would
3139 // then mark the child as destroyed).
3140 for (const ComposerState& state : states) {
3141 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003142 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003143
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003144 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3145 // anyway. This can be used as a flush mechanism for previous async transactions.
3146 // Empty animation transaction can be used to simulate back-pressure, so also force a
3147 // transaction for empty animation transactions.
3148 if (transactionFlags == 0 &&
3149 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003150 transactionFlags = eTransactionNeeded;
3151 }
3152
Mathias Agopian386aa982011-11-07 21:58:03 -08003153 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003154 if (mInterceptor->isEnabled()) {
3155 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003156 }
Irvel468051e2016-06-13 16:44:44 -07003157
Mathias Agopian386aa982011-11-07 21:58:03 -08003158 // this triggers the transaction
3159 setTransactionFlags(transactionFlags);
3160
3161 // if this is a synchronous transaction, wait for it to take effect
3162 // before returning.
3163 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003164 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003165 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003166 if (flags & eAnimation) {
3167 mAnimTransactionPending = true;
3168 }
3169 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003170 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3171 if (CC_UNLIKELY(err != NO_ERROR)) {
3172 // just in case something goes wrong in SF, return to the
3173 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003174 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3175 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003176 break;
3177 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
3180}
3181
Mathias Agopiane57f2922012-08-09 16:29:12 -07003182uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3183{
Jesse Hall9a143922012-10-04 16:29:19 -07003184 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3185 if (dpyIdx < 0)
3186 return 0;
3187
Mathias Agopiane57f2922012-08-09 16:29:12 -07003188 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003189 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003190 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003191 const uint32_t what = s.what;
3192 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003193 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003194 disp.surface = s.surface;
3195 flags |= eDisplayTransactionNeeded;
3196 }
3197 }
3198 if (what & DisplayState::eLayerStackChanged) {
3199 if (disp.layerStack != s.layerStack) {
3200 disp.layerStack = s.layerStack;
3201 flags |= eDisplayTransactionNeeded;
3202 }
3203 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003204 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003205 if (disp.orientation != s.orientation) {
3206 disp.orientation = s.orientation;
3207 flags |= eDisplayTransactionNeeded;
3208 }
3209 if (disp.frame != s.frame) {
3210 disp.frame = s.frame;
3211 flags |= eDisplayTransactionNeeded;
3212 }
3213 if (disp.viewport != s.viewport) {
3214 disp.viewport = s.viewport;
3215 flags |= eDisplayTransactionNeeded;
3216 }
3217 }
Michael Lentine47e45402014-07-18 15:34:25 -07003218 if (what & DisplayState::eDisplaySizeChanged) {
3219 if (disp.width != s.width) {
3220 disp.width = s.width;
3221 flags |= eDisplayTransactionNeeded;
3222 }
3223 if (disp.height != s.height) {
3224 disp.height = s.height;
3225 flags |= eDisplayTransactionNeeded;
3226 }
3227 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003228 }
3229 return flags;
3230}
3231
chaviwca27f252018-02-06 16:46:39 -08003232uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3233 const layer_state_t& s = composerState.state;
3234 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3235
Mathias Agopian13127d82013-03-05 17:47:11 -08003236 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003237 if (layer == nullptr) {
3238 return 0;
3239 }
3240
3241 if (layer->isPendingRemoval()) {
3242 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3243 return 0;
3244 }
3245
3246 uint32_t flags = 0;
3247
3248 const uint32_t what = s.what;
3249 bool geometryAppliesWithResize =
3250 what & layer_state_t::eGeometryAppliesWithResize;
3251 if (what & layer_state_t::ePositionChanged) {
3252 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3253 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003254 }
chaviw8b3871a2017-11-01 17:41:01 -07003255 }
3256 if (what & layer_state_t::eLayerChanged) {
3257 // NOTE: index needs to be calculated before we update the state
3258 const auto& p = layer->getParent();
3259 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003260 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003261 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003262 mCurrentState.layersSortedByZ.removeAt(idx);
3263 mCurrentState.layersSortedByZ.add(layer);
3264 // we need traversal (state changed)
3265 // AND transaction (list changed)
3266 flags |= eTransactionNeeded|eTraversalNeeded;
3267 }
chaviw8b3871a2017-11-01 17:41:01 -07003268 } else {
3269 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003270 flags |= eTransactionNeeded|eTraversalNeeded;
3271 }
3272 }
chaviw8b3871a2017-11-01 17:41:01 -07003273 }
3274 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003275 // NOTE: index needs to be calculated before we update the state
3276 const auto& p = layer->getParent();
3277 if (p == nullptr) {
3278 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3279 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3280 mCurrentState.layersSortedByZ.removeAt(idx);
3281 mCurrentState.layersSortedByZ.add(layer);
3282 // we need traversal (state changed)
3283 // AND transaction (list changed)
3284 flags |= eTransactionNeeded|eTraversalNeeded;
3285 }
3286 } else {
3287 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3288 flags |= eTransactionNeeded|eTraversalNeeded;
3289 }
chaviw8b3871a2017-11-01 17:41:01 -07003290 }
3291 }
3292 if (what & layer_state_t::eSizeChanged) {
3293 if (layer->setSize(s.w, s.h)) {
3294 flags |= eTraversalNeeded;
3295 }
3296 }
3297 if (what & layer_state_t::eAlphaChanged) {
3298 if (layer->setAlpha(s.alpha))
3299 flags |= eTraversalNeeded;
3300 }
3301 if (what & layer_state_t::eColorChanged) {
3302 if (layer->setColor(s.color))
3303 flags |= eTraversalNeeded;
3304 }
3305 if (what & layer_state_t::eMatrixChanged) {
3306 if (layer->setMatrix(s.matrix))
3307 flags |= eTraversalNeeded;
3308 }
3309 if (what & layer_state_t::eTransparentRegionChanged) {
3310 if (layer->setTransparentRegionHint(s.transparentRegion))
3311 flags |= eTraversalNeeded;
3312 }
3313 if (what & layer_state_t::eFlagsChanged) {
3314 if (layer->setFlags(s.flags, s.mask))
3315 flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eCropChanged) {
3318 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3319 flags |= eTraversalNeeded;
3320 }
3321 if (what & layer_state_t::eFinalCropChanged) {
3322 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3323 flags |= eTraversalNeeded;
3324 }
3325 if (what & layer_state_t::eLayerStackChanged) {
3326 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3327 // We only allow setting layer stacks for top level layers,
3328 // everything else inherits layer stack from its parent.
3329 if (layer->hasParent()) {
3330 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3331 layer->getName().string());
3332 } else if (idx < 0) {
3333 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3334 "that also does not appear in the top level layer list. Something"
3335 " has gone wrong.", layer->getName().string());
3336 } else if (layer->setLayerStack(s.layerStack)) {
3337 mCurrentState.layersSortedByZ.removeAt(idx);
3338 mCurrentState.layersSortedByZ.add(layer);
3339 // we need traversal (state changed)
3340 // AND transaction (list changed)
3341 flags |= eTransactionNeeded|eTraversalNeeded;
3342 }
3343 }
3344 if (what & layer_state_t::eDeferTransaction) {
3345 if (s.barrierHandle != nullptr) {
3346 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3347 } else if (s.barrierGbp != nullptr) {
3348 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3349 if (authenticateSurfaceTextureLocked(gbp)) {
3350 const auto& otherLayer =
3351 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3352 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3353 } else {
3354 ALOGE("Attempt to defer transaction to to an"
3355 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003356 }
3357 }
chaviw8b3871a2017-11-01 17:41:01 -07003358 // We don't trigger a traversal here because if no other state is
3359 // changed, we don't want this to cause any more work
3360 }
3361 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003362 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003363 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003364 if (!hadParent) {
3365 mCurrentState.layersSortedByZ.remove(layer);
3366 }
chaviw8b3871a2017-11-01 17:41:01 -07003367 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003368 }
chaviw8b3871a2017-11-01 17:41:01 -07003369 }
3370 if (what & layer_state_t::eReparentChildren) {
3371 if (layer->reparentChildren(s.reparentHandle)) {
3372 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003373 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003374 }
chaviw8b3871a2017-11-01 17:41:01 -07003375 if (what & layer_state_t::eDetachChildren) {
3376 layer->detachChildren();
3377 }
3378 if (what & layer_state_t::eOverrideScalingModeChanged) {
3379 layer->setOverrideScalingMode(s.overrideScalingMode);
3380 // We don't trigger a traversal here because if no other state is
3381 // changed, we don't want this to cause any more work
3382 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003383 return flags;
3384}
3385
chaviwca27f252018-02-06 16:46:39 -08003386void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3387 const layer_state_t& state = composerState.state;
3388 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3389
3390 sp<Layer> layer(client->getLayerUser(state.surface));
3391 if (layer == nullptr) {
3392 return;
3393 }
3394
3395 if (layer->isPendingRemoval()) {
3396 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3397 return;
3398 }
3399
3400 if (state.what & layer_state_t::eDestroySurface) {
3401 removeLayerLocked(mStateLock, layer);
3402 }
3403}
3404
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003405status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003406 const String8& name,
3407 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003408 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003409 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003410 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003411{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003412 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003413 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003414 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003415 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003416 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003417
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003418 status_t result = NO_ERROR;
3419
3420 sp<Layer> layer;
3421
Cody Northropbc755282017-03-31 12:00:08 -06003422 String8 uniqueName = getUniqueLayerName(name);
3423
Mathias Agopian3165cc22012-08-08 19:42:09 -07003424 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3425 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003426 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003427 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003428 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003430 break;
chaviw13fdc492017-06-27 12:40:18 -07003431 case ISurfaceComposerClient::eFXSurfaceColor:
3432 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003433 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003434 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003435 break;
3436 default:
3437 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438 break;
3439 }
3440
Dan Stoza7d89d062015-04-30 13:29:25 -07003441 if (result != NO_ERROR) {
3442 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003443 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003444
Chia-I Wuab0c3192017-08-01 11:29:00 -07003445 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3446 // TODO b/64227542
3447 if (windowType == 441731) {
3448 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3449 layer->setPrimaryDisplayOnly();
3450 }
3451
Albert Chaulk479c60c2017-01-27 14:21:34 -05003452 layer->setInfo(windowType, ownerUid);
3453
Robert Carr1f0a16a2016-10-24 16:27:39 -07003454 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003455 if (result != NO_ERROR) {
3456 return result;
3457 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003458 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003459
3460 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003461 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003462}
3463
Cody Northropbc755282017-03-31 12:00:08 -06003464String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3465{
3466 bool matchFound = true;
3467 uint32_t dupeCounter = 0;
3468
3469 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3470 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3471
3472 // Loop over layers until we're sure there is no matching name
3473 while (matchFound) {
3474 matchFound = false;
3475 mDrawingState.traverseInZOrder([&](Layer* layer) {
3476 if (layer->getName() == uniqueName) {
3477 matchFound = true;
3478 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3479 }
3480 });
3481 }
3482
3483 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3484
3485 return uniqueName;
3486}
3487
David Sodman0c69cad2017-08-21 12:12:51 -07003488status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003489 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3490 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491{
3492 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003493 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494 case PIXEL_FORMAT_TRANSPARENT:
3495 case PIXEL_FORMAT_TRANSLUCENT:
3496 format = PIXEL_FORMAT_RGBA_8888;
3497 break;
3498 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003499 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500 break;
3501 }
3502
David Sodman0c69cad2017-08-21 12:12:51 -07003503 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3504 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003505 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003506 *handle = layer->getHandle();
3507 *gbp = layer->getProducer();
3508 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003510
David Sodman0c69cad2017-08-21 12:12:51 -07003511 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003512 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513}
3514
chaviw13fdc492017-06-27 12:40:18 -07003515status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003517 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518{
chaviw13fdc492017-06-27 12:40:18 -07003519 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003522}
3523
Mathias Agopianac9fa422013-02-11 16:40:36 -08003524status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525{
Robert Carr9524cb32017-02-13 11:32:32 -08003526 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003527 status_t err = NO_ERROR;
3528 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003529 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003530 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003531 err = removeLayer(l);
3532 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3533 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003534 }
3535 return err;
3536}
3537
Mathias Agopian13127d82013-03-05 17:47:11 -08003538status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003539{
Mathias Agopian67106042013-03-14 19:18:13 -07003540 // called by ~LayerCleaner() when all references to the IBinder (handle)
3541 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003542 sp<Layer> l = layer.promote();
3543 if (l == nullptr) {
3544 // The layer has already been removed, carry on
3545 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003546 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003547 // If we have a parent, then we can continue to live as long as it does.
3548 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003549}
3550
Mathias Agopianb60314a2012-04-10 22:09:54 -07003551// ---------------------------------------------------------------------------
3552
Andy McFadden13a082e2012-08-24 10:16:42 -07003553void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003554 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003555 Vector<ComposerState> state;
3556 Vector<DisplayState> displays;
3557 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003558 d.what = DisplayState::eDisplayProjectionChanged |
3559 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003560 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003561 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003562 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003563 d.frame.makeInvalid();
3564 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003565 d.width = 0;
3566 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003567 displays.add(d);
3568 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003569 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3570 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003571
David Sodman105b7dc2017-11-04 20:28:14 -07003572 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003573 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003574 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003575
Brian Andersond0010582017-03-07 13:20:31 -08003576 // Use phase of 0 since phase is not known.
3577 // Use latency of 0, which will snap to the ideal latency.
3578 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003579}
3580
3581void SurfaceFlinger::initializeDisplays() {
3582 class MessageScreenInitialized : public MessageBase {
3583 SurfaceFlinger* flinger;
3584 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003585 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003586 virtual bool handler() {
3587 flinger->onInitializeDisplays();
3588 return true;
3589 }
3590 };
3591 sp<MessageBase> msg = new MessageScreenInitialized(this);
3592 postMessageAsync(msg); // we may be called from main thread, use async message
3593}
3594
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003595void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003596 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003597 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3598 this);
3599 int32_t type = hw->getDisplayType();
3600 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003601
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003602 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003603 return;
3604 }
3605
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003606 hw->setPowerMode(mode);
3607 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3608 ALOGW("Trying to set power mode for virtual display");
3609 return;
3610 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003611
Lloyd Pique4dccc412018-01-22 17:21:36 -08003612 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003613 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003614 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3615 if (idx < 0) {
3616 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3617 return;
3618 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003619 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003620 }
3621
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003622 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003623 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003624 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003625 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3626 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003627 // FIXME: eventthread only knows about the main display right now
3628 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003629 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003630 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003632 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003633 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003634 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003635
3636 struct sched_param param = {0};
3637 param.sched_priority = 1;
3638 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3639 ALOGW("Couldn't set SCHED_FIFO on display on");
3640 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003641 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003642 // Turn off the display
3643 struct sched_param param = {0};
3644 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3645 ALOGW("Couldn't set SCHED_OTHER on display off");
3646 }
3647
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003648 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3649 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003650 disableHardwareVsync(true); // also cancels any in-progress resync
3651
Mathias Agopiancde87a32012-09-13 14:09:01 -07003652 // FIXME: eventthread only knows about the main display right now
3653 mEventThread->onScreenReleased();
3654 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003655
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003656 getHwComposer().setPowerMode(type, mode);
3657 mVisibleRegionsDirty = true;
3658 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003659 } else if (mode == HWC_POWER_MODE_DOZE ||
3660 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003661 // Update display while dozing
3662 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003663 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3664 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003665 // FIXME: eventthread only knows about the main display right now
3666 mEventThread->onScreenAcquired();
3667 resyncToHardwareVsync(true);
3668 }
3669 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3670 // Leave display going to doze
3671 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3672 disableHardwareVsync(true); // also cancels any in-progress resync
3673 // FIXME: eventthread only knows about the main display right now
3674 mEventThread->onScreenReleased();
3675 }
3676 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003677 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003678 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003679 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003680 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003681 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003682}
3683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3685 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003686 SurfaceFlinger& mFlinger;
3687 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003688 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003689 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003690 MessageSetPowerMode(SurfaceFlinger& flinger,
3691 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3692 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003693 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003694 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003695 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003697 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003698 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 ALOGW("Attempt to set power mode = %d for virtual display",
3700 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003701 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003702 mFlinger.setPowerModeInternal(
3703 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003704 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705 return true;
3706 }
3707 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003708 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003709 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003710}
3711
3712// ---------------------------------------------------------------------------
3713
Lloyd Pique755e3192018-01-31 16:46:15 -08003714status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3715 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003717
Mathias Agopianbd115332013-04-18 16:41:04 -07003718 IPCThreadState* ipc = IPCThreadState::self();
3719 const int pid = ipc->getCallingPid();
3720 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003721
Mathias Agopianbd115332013-04-18 16:41:04 -07003722 if ((uid != AID_SHELL) &&
3723 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003724 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003725 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003726 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003727 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003728 // (this would indicate SF is stuck, but we want to be able to
3729 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003730 status_t err = mStateLock.timedLock(s2ns(1));
3731 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003732 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003733 result.appendFormat(
3734 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3735 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003736 }
3737
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003738 bool dumpAll = true;
3739 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003740 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003741
3742 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003743 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003744 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3745 dumpAll = false;
3746 }
3747
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003748 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003749 if ((index < numArgs) &&
3750 (args[index] == String16("--list"))) {
3751 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003752 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003753 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003754 }
3755
3756 if ((index < numArgs) &&
3757 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003759 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003760 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003761 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003762
3763 if ((index < numArgs) &&
3764 (args[index] == String16("--latency-clear"))) {
3765 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003766 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003767 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003768 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003769
3770 if ((index < numArgs) &&
3771 (args[index] == String16("--dispsync"))) {
3772 index++;
3773 mPrimaryDispSync.dump(result);
3774 dumpAll = false;
3775 }
Dan Stozab90cf072015-03-05 11:05:59 -08003776
3777 if ((index < numArgs) &&
3778 (args[index] == String16("--static-screen"))) {
3779 index++;
3780 dumpStaticScreenStats(result);
3781 dumpAll = false;
3782 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003783
3784 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003785 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003786 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003787 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003788 dumpAll = false;
3789 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003790
3791 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3792 index++;
3793 dumpWideColorInfo(result);
3794 dumpAll = false;
3795 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003796
3797 if ((index < numArgs) &&
3798 (args[index] == String16("--enable-layer-stats"))) {
3799 index++;
3800 mLayerStats.enable();
3801 dumpAll = false;
3802 }
3803
3804 if ((index < numArgs) &&
3805 (args[index] == String16("--disable-layer-stats"))) {
3806 index++;
3807 mLayerStats.disable();
3808 dumpAll = false;
3809 }
3810
3811 if ((index < numArgs) &&
3812 (args[index] == String16("--clear-layer-stats"))) {
3813 index++;
3814 mLayerStats.clear();
3815 dumpAll = false;
3816 }
3817
3818 if ((index < numArgs) &&
3819 (args[index] == String16("--dump-layer-stats"))) {
3820 index++;
3821 mLayerStats.dump(result);
3822 dumpAll = false;
3823 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003825
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003826 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003827 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003828 }
3829
Mathias Agopian9795c422009-08-26 16:36:26 -07003830 if (locked) {
3831 mStateLock.unlock();
3832 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 }
3834 write(fd, result.string(), result.size());
3835 return NO_ERROR;
3836}
3837
Dan Stozac7014012014-02-14 15:03:43 -08003838void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3839 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840{
Robert Carr2047fae2016-11-28 14:09:09 -08003841 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003842 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003843 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844}
3845
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003848{
3849 String8 name;
3850 if (index < args.size()) {
3851 name = String8(args[index]);
3852 index++;
3853 }
3854
David Sodman105b7dc2017-11-04 20:28:14 -07003855 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003856 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003857 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003858
3859 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003860 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003861 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003862 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003863 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003864 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003865 }
Robert Carr2047fae2016-11-28 14:09:09 -08003866 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003867 }
3868}
3869
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003870void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003871 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872{
3873 String8 name;
3874 if (index < args.size()) {
3875 name = String8(args[index]);
3876 index++;
3877 }
3878
Robert Carr2047fae2016-11-28 14:09:09 -08003879 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003880 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003881 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003882 }
Robert Carr2047fae2016-11-28 14:09:09 -08003883 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003884
Svetoslavd85084b2014-03-20 10:28:31 -07003885 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003886}
3887
Jamie Gennis6547ff42013-07-16 20:12:42 -07003888// This should only be called from the main thread. Otherwise it would need
3889// the lock and should use mCurrentState rather than mDrawingState.
3890void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003891 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003892 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003893 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003894
3895 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3896}
3897
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003898void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003899{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003900 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003901
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003902 if (isLayerTripleBufferingDisabled())
3903 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003904
3905 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003906 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003907 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003908 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003909 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3910 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003911 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003912}
3913
Dan Stozab90cf072015-03-05 11:05:59 -08003914void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3915{
3916 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003917 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3918 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003919 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003920 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003921 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3922 b + 1, bucketTimeSec, percent);
3923 }
David Sodman4a36e932017-11-07 14:29:47 -08003924 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003925 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003926 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003927 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003928 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003929}
3930
Dan Stozae77c7662016-05-13 11:37:28 -07003931void SurfaceFlinger::recordBufferingStats(const char* layerName,
3932 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003933 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3934 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003935 for (const auto& segment : history) {
3936 if (!segment.usedThirdBuffer) {
3937 stats.twoBufferTime += segment.totalTime;
3938 }
3939 if (segment.occupancyAverage < 1.0f) {
3940 stats.doubleBufferedTime += segment.totalTime;
3941 } else if (segment.occupancyAverage < 2.0f) {
3942 stats.tripleBufferedTime += segment.totalTime;
3943 }
3944 ++stats.numSegments;
3945 stats.totalTime += segment.totalTime;
3946 }
3947}
3948
Brian Andersond6927fb2016-07-23 23:37:30 -07003949void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3950 result.appendFormat("Layer frame timestamps:\n");
3951
3952 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3953 const size_t count = currentLayers.size();
3954 for (size_t i=0 ; i<count ; i++) {
3955 currentLayers[i]->dumpFrameEvents(result);
3956 }
3957}
3958
Dan Stozae77c7662016-05-13 11:37:28 -07003959void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3960 result.append("Buffering stats:\n");
3961 result.append(" [Layer name] <Active time> <Two buffer> "
3962 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003963 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003964 typedef std::tuple<std::string, float, float, float> BufferTuple;
3965 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003966 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003967 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003968 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003969 if (stats.numSegments == 0) {
3970 continue;
3971 }
3972 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3973 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3974 stats.totalTime;
3975 float doubleBufferRatio = static_cast<float>(
3976 stats.doubleBufferedTime) / stats.totalTime;
3977 float tripleBufferRatio = static_cast<float>(
3978 stats.tripleBufferedTime) / stats.totalTime;
3979 sorted.insert({activeTime, {name, twoBufferRatio,
3980 doubleBufferRatio, tripleBufferRatio}});
3981 }
3982 for (const auto& sortedPair : sorted) {
3983 float activeTime = sortedPair.first;
3984 const BufferTuple& values = sortedPair.second;
3985 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3986 std::get<0>(values).c_str(), activeTime,
3987 std::get<1>(values), std::get<2>(values),
3988 std::get<3>(values));
3989 }
3990 result.append("\n");
3991}
3992
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003993void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3994 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003995 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003996
3997 // TODO: print out if wide-color mode is active or not
3998
3999 for (size_t d = 0; d < mDisplays.size(); d++) {
4000 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4001 int32_t hwcId = displayDevice->getHwcDisplayId();
4002 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4003 continue;
4004 }
4005
4006 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004007 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004008 for (auto&& mode : modes) {
4009 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4010 }
4011
Peiyong Lina52f0292018-03-14 17:26:31 -07004012 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004013 result.appendFormat(" Current color mode: %s (%d)\n",
4014 decodeColorMode(currentMode).c_str(), currentMode);
4015 }
4016 result.append("\n");
4017}
4018
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004019LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004020 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004021 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4022 const State& state = useDrawing ? mDrawingState : mCurrentState;
4023 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004024 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004025 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004026 });
4027
4028 return layersProto;
4029}
4030
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004031LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4032 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004033 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004034
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004035 SizeProto* resolution = layersProto.mutable_resolution();
4036 resolution->set_w(displayDevice->getWidth());
4037 resolution->set_h(displayDevice->getHeight());
4038
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004039 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4040 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4041 layersProto.set_global_transform(
4042 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4043
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004044 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004045 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004046 LayerProto* layerProto = layersProto.add_layers();
4047 layer->writeToProto(layerProto, hwcId);
4048 }
4049 });
4050
4051 return layersProto;
4052}
4053
Mathias Agopian74d211a2013-04-22 16:55:35 +02004054void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4055 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004056{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004057 bool colorize = false;
4058 if (index < args.size()
4059 && (args[index] == String16("--color"))) {
4060 colorize = true;
4061 index++;
4062 }
4063
4064 Colorizer colorizer(colorize);
4065
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004066 // figure out if we're stuck somewhere
4067 const nsecs_t now = systemTime();
4068 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4069 const nsecs_t inTransaction(mDebugInTransaction);
4070 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4071 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4072
4073 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004074 * Dump library configuration.
4075 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004076
4077 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004078 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004079 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004080 appendSfConfigString(result);
4081 appendUiConfigString(result);
4082 appendGuiConfigString(result);
4083 result.append("\n");
4084
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004085 result.append("\nWide-Color information:\n");
4086 dumpWideColorInfo(result);
4087
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004088 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004089 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004090 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004091 result.append(SyncFeatures::getInstance().toString());
4092 result.append("\n");
4093
David Sodman105b7dc2017-11-04 20:28:14 -07004094 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004095
Andy McFadden41d67d72014-04-25 16:58:34 -07004096 colorizer.bold(result);
4097 result.append("DispSync configuration: ");
4098 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004099 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004100 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004101 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004102 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004103 result.append("\n");
4104
Dan Stozab90cf072015-03-05 11:05:59 -08004105 // Dump static screen stats
4106 result.append("\n");
4107 dumpStaticScreenStats(result);
4108 result.append("\n");
4109
Dan Stozae77c7662016-05-13 11:37:28 -07004110 dumpBufferingStats(result);
4111
Andy McFadden4803b742012-09-24 19:07:20 -07004112 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004113 * Dump the visible layer list
4114 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004115 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004116 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004117 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4118 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004119 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004120
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004121 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004122 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004123 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004124
4125 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004126 * Dump Display state
4127 */
4128
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004129 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004130 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004131 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004132 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4133 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004134 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004135 }
4136
4137 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004138 * Dump SurfaceFlinger global state
4139 */
4140
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004141 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004142 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004143 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004144
Mathias Agopian888c8222012-08-04 21:10:38 -07004145 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004146 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004147
David Sodmanbc815282017-11-05 18:57:52 -08004148 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004150 if (hw) {
4151 hw->undefinedRegion.dump(result, "undefinedRegion");
4152 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4153 hw->getOrientation(), hw->isDisplayOn());
4154 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004155 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156 " last eglSwapBuffers() time: %f us\n"
4157 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004158 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004159 " refresh-rate : %f fps\n"
4160 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004161 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004162 " gpu_to_cpu_unsupported : %d\n"
4163 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004164 mLastSwapBufferTime/1000.0,
4165 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004166 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004167 1e9 / activeConfig->getVsyncPeriod(),
4168 activeConfig->getDpiX(),
4169 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004170 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004171
Mathias Agopian74d211a2013-04-22 16:55:35 +02004172 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004173 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004174
Mathias Agopian74d211a2013-04-22 16:55:35 +02004175 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004176 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004177
4178 /*
4179 * VSYNC state
4180 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004181 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004182 result.append("\n");
4183
4184 /*
4185 * HWC layer minidump
4186 */
4187 for (size_t d = 0; d < mDisplays.size(); d++) {
4188 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4189 int32_t hwcId = displayDevice->getHwcDisplayId();
4190 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4191 continue;
4192 }
4193
4194 result.appendFormat("Display %d HWC layers:\n", hwcId);
4195 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004196 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004197 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004198 });
Dan Stozae22aec72016-08-01 13:20:59 -07004199 result.append("\n");
4200 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201
4202 /*
4203 * Dump HWComposer state
4204 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004205 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004206 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004207 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004208 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004209 result.appendFormat(" h/w composer %s\n",
4210 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004211 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004212
4213 /*
4214 * Dump gralloc state
4215 */
4216 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4217 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004218
4219 /*
4220 * Dump VrFlinger state if in use.
4221 */
4222 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4223 result.append("VrFlinger state:\n");
4224 result.append(mVrFlinger->Dump().c_str());
4225 result.append("\n");
4226 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227}
4228
Mathias Agopian13127d82013-03-05 17:47:11 -08004229const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004230SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004231 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004232 wp<IBinder> dpy;
4233 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4234 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4235 dpy = mDisplays.keyAt(i);
4236 break;
4237 }
4238 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004239 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004240 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4241 // Just use the primary display so we have something to return
4242 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4243 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004244 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004245}
4246
Keun young Park63f165f2012-08-31 10:53:36 -07004247bool SurfaceFlinger::startDdmConnection()
4248{
4249 void* libddmconnection_dso =
4250 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4251 if (!libddmconnection_dso) {
4252 return false;
4253 }
4254 void (*DdmConnection_start)(const char* name);
4255 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004256 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004257 if (!DdmConnection_start) {
4258 dlclose(libddmconnection_dso);
4259 return false;
4260 }
4261 (*DdmConnection_start)(getServiceName());
4262 return true;
4263}
4264
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004265status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004266 switch (code) {
4267 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004268 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004269 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004270 case CLEAR_ANIMATION_FRAME_STATS:
4271 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004272 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004273 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004274 case ENABLE_VSYNC_INJECTIONS:
4275 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004276 {
4277 // codes that require permission check
4278 IPCThreadState* ipc = IPCThreadState::self();
4279 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004280 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004281 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004282 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004283 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004284 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004286 break;
4287 }
Robert Carr1db73f62016-12-21 12:58:51 -08004288 /*
4289 * Calling setTransactionState is safe, because you need to have been
4290 * granted a reference to Client* and Handle* to do anything with it.
4291 *
4292 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4293 */
4294 case SET_TRANSACTION_STATE:
4295 case CREATE_SCOPED_CONNECTION:
4296 {
4297 return OK;
4298 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004299 case CAPTURE_SCREEN:
4300 {
4301 // codes that require permission check
4302 IPCThreadState* ipc = IPCThreadState::self();
4303 const int pid = ipc->getCallingPid();
4304 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004305 if ((uid != AID_GRAPHICS) &&
4306 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004307 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004308 return PERMISSION_DENIED;
4309 }
4310 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004311 }
chaviwa76b2712017-09-20 12:02:26 -07004312 case CAPTURE_LAYERS: {
4313 IPCThreadState* ipc = IPCThreadState::self();
4314 const int pid = ipc->getCallingPid();
4315 const int uid = ipc->getCallingUid();
4316 if ((uid != AID_GRAPHICS) &&
4317 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4318 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4319 return PERMISSION_DENIED;
4320 }
4321 break;
4322 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004323 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004324 return OK;
4325}
4326
4327status_t SurfaceFlinger::onTransact(
4328 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4329{
4330 status_t credentialCheck = CheckTransactCodeCredentials(code);
4331 if (credentialCheck != OK) {
4332 return credentialCheck;
4333 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004335 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4336 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004337 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004338 IPCThreadState* ipc = IPCThreadState::self();
4339 const int uid = ipc->getCallingUid();
4340 if (CC_UNLIKELY(uid != AID_SYSTEM
4341 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004342 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004343 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004344 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004345 return PERMISSION_DENIED;
4346 }
4347 int n;
4348 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004349 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004350 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004351 return NO_ERROR;
4352 case 1002: // SHOW_UPDATES
4353 n = data.readInt32();
4354 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004355 invalidateHwcGeometry();
4356 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004357 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004358 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004359 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004360 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004361 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004362 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004363 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004364 setTransactionFlags(
4365 eTransactionNeeded|
4366 eDisplayTransactionNeeded|
4367 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004368 return NO_ERROR;
4369 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004370 case 1006:{ // send empty update
4371 signalRefresh();
4372 return NO_ERROR;
4373 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004374 case 1008: // toggle use of hw composer
4375 n = data.readInt32();
4376 mDebugDisableHWC = n ? 1 : 0;
4377 invalidateHwcGeometry();
4378 repaintEverything();
4379 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004380 case 1009: // toggle use of transform hint
4381 n = data.readInt32();
4382 mDebugDisableTransformHint = n ? 1 : 0;
4383 invalidateHwcGeometry();
4384 repaintEverything();
4385 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004386 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004387 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004388 reply->writeInt32(0);
4389 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004390 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004391 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 return NO_ERROR;
4393 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004394 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004395 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004396 return NO_ERROR;
4397 }
4398 case 1014: {
4399 // daltonize
4400 n = data.readInt32();
4401 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004402 case 1:
4403 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4404 break;
4405 case 2:
4406 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4407 break;
4408 case 3:
4409 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4410 break;
4411 default:
4412 mDaltonizer.setType(ColorBlindnessType::None);
4413 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004414 }
4415 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004416 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004417 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004418 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004419 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004420 invalidateHwcGeometry();
4421 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004422 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004423 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004424 case 1015: {
4425 // apply a color matrix
4426 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004427 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004428 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004429 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004430 for (size_t j = 0; j < 4; j++) {
4431 mColorMatrix[i][j] = data.readFloat();
4432 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004433 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004434 } else {
4435 mColorMatrix = mat4();
4436 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004437
4438 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4439 // the division by w in the fragment shader
4440 float4 lastRow(transpose(mColorMatrix)[3]);
4441 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4442 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4443 }
4444
Alan Viverette9c5a3332013-09-12 20:04:35 -07004445 invalidateHwcGeometry();
4446 repaintEverything();
4447 return NO_ERROR;
4448 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004449 // This is an experimental interface
4450 // Needs to be shifted to proper binder interface when we productize
4451 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004452 n = data.readInt32();
4453 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004454 return NO_ERROR;
4455 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004456 case 1017: {
4457 n = data.readInt32();
4458 mForceFullDamage = static_cast<bool>(n);
4459 return NO_ERROR;
4460 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004461 case 1018: { // Modify Choreographer's phase offset
4462 n = data.readInt32();
4463 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4464 return NO_ERROR;
4465 }
4466 case 1019: { // Modify SurfaceFlinger's phase offset
4467 n = data.readInt32();
4468 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4469 return NO_ERROR;
4470 }
Irvel468051e2016-06-13 16:44:44 -07004471 case 1020: { // Layer updates interceptor
4472 n = data.readInt32();
4473 if (n) {
4474 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004475 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004476 }
4477 else{
4478 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004479 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004480 }
4481 return NO_ERROR;
4482 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004483 case 1021: { // Disable HWC virtual displays
4484 n = data.readInt32();
4485 mUseHwcVirtualDisplays = !n;
4486 return NO_ERROR;
4487 }
Romain Guy0147a172017-06-01 13:53:56 -07004488 case 1022: { // Set saturation boost
4489 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4490
4491 invalidateHwcGeometry();
4492 repaintEverything();
4493 return NO_ERROR;
4494 }
Romain Guy54f154a2017-10-24 21:40:32 +01004495 case 1023: { // Set native mode
4496 mForceNativeColorMode = data.readInt32() == 1;
4497
4498 invalidateHwcGeometry();
4499 repaintEverything();
4500 return NO_ERROR;
4501 }
4502 case 1024: { // Is wide color gamut rendering/color management supported?
4503 reply->writeBool(hasWideColorDisplay);
4504 return NO_ERROR;
4505 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004506 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004507 n = data.readInt32();
4508 if (n) {
4509 ALOGV("LayerTracing enabled");
4510 mTracing.enable();
4511 doTracing("tracing.enable");
4512 reply->writeInt32(NO_ERROR);
4513 } else {
4514 ALOGV("LayerTracing disabled");
4515 status_t err = mTracing.disable();
4516 reply->writeInt32(err);
4517 }
4518 return NO_ERROR;
4519 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004520 case 1026: { // Get layer tracing status
4521 reply->writeBool(mTracing.isEnabled());
4522 return NO_ERROR;
4523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524 }
4525 }
4526 return err;
4527}
4528
Steven Thomas6d8110b2017-08-31 18:24:21 -07004529void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004530 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004531 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004532}
4533
Steven Thomas6d8110b2017-08-31 18:24:21 -07004534void SurfaceFlinger::repaintEverything() {
4535 ConditionalLock _l(mStateLock,
4536 std::this_thread::get_id() != mMainThreadId);
4537 repaintEverythingLocked();
4538}
4539
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004540// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4541class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004542public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004543 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4544 ~WindowDisconnector() {
4545 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004546 }
4547
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004548private:
4549 ANativeWindow* mWindow;
4550 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004551};
4552
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004553status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4554 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4555 int32_t minLayerZ, int32_t maxLayerZ,
4556 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004557 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004558 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004559
chaviwa76b2712017-09-20 12:02:26 -07004560 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4561
4562 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004563 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4564
chaviwa76b2712017-09-20 12:02:26 -07004565 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4566
4567 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4568 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004569 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004570}
4571
4572status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004573 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004574 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004575 ATRACE_CALL();
4576
4577 class LayerRenderArea : public RenderArea {
4578 public:
Robert Carr578038f2018-03-09 12:25:24 -08004579 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4580 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4581 : RenderArea(reqHeight, reqWidth),
4582 mLayer(layer),
4583 mCrop(crop),
4584 mFlinger(flinger),
4585 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004586 Rect getBounds() const override {
4587 const Layer::State& layerState(mLayer->getDrawingState());
4588 return Rect(layerState.active.w, layerState.active.h);
4589 }
4590 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4591 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4592 bool isSecure() const override { return false; }
4593 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004594 const Transform& getTransform() const { return mTransform; }
4595
4596 class ReparentForDrawing {
4597 public:
4598 const sp<Layer>& oldParent;
4599 const sp<Layer>& newParent;
4600
4601 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4602 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004603 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004604 }
Robert Carr15eae092018-03-23 13:43:53 -07004605 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004606 };
4607
4608 void render(std::function<void()> drawLayers) override {
4609 if (!mChildrenOnly) {
4610 mTransform = mLayer->getTransform().inverse();
4611 drawLayers();
4612 } else {
4613 Rect bounds = getBounds();
4614 screenshotParentLayer =
4615 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4616 bounds.getWidth(), bounds.getHeight(), 0);
4617
4618 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4619 drawLayers();
4620 }
4621 }
chaviwa76b2712017-09-20 12:02:26 -07004622
chaviw7206d492017-11-10 16:16:12 -08004623 Rect getSourceCrop() const override {
4624 if (mCrop.isEmpty()) {
4625 return getBounds();
4626 } else {
4627 return mCrop;
4628 }
4629 }
chaviwa76b2712017-09-20 12:02:26 -07004630 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004631 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004632
4633 private:
chaviw7206d492017-11-10 16:16:12 -08004634 const sp<Layer> mLayer;
4635 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004636
4637 // In the "childrenOnly" case we reparent the children to a screenshot
4638 // layer which has no properties set and which does not draw.
4639 sp<ContainerLayer> screenshotParentLayer;
4640 Transform mTransform;
4641
4642 SurfaceFlinger* mFlinger;
4643 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004644 };
4645
4646 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4647 auto parent = layerHandle->owner.promote();
4648
chaviw7206d492017-11-10 16:16:12 -08004649 if (parent == nullptr || parent->isPendingRemoval()) {
4650 ALOGE("captureLayers called with a removed parent");
4651 return NAME_NOT_FOUND;
4652 }
4653
Robert Carr578038f2018-03-09 12:25:24 -08004654 const int uid = IPCThreadState::self()->getCallingUid();
4655 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4656 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4657 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4658 return PERMISSION_DENIED;
4659 }
4660
chaviw7206d492017-11-10 16:16:12 -08004661 Rect crop(sourceCrop);
4662 if (sourceCrop.width() <= 0) {
4663 crop.left = 0;
4664 crop.right = parent->getCurrentState().active.w;
4665 }
4666
4667 if (sourceCrop.height() <= 0) {
4668 crop.top = 0;
4669 crop.bottom = parent->getCurrentState().active.h;
4670 }
4671
4672 int32_t reqWidth = crop.width() * frameScale;
4673 int32_t reqHeight = crop.height() * frameScale;
4674
Robert Carr578038f2018-03-09 12:25:24 -08004675 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004676
Robert Carr578038f2018-03-09 12:25:24 -08004677 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004678 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4679 if (!layer->isVisible()) {
4680 return;
Robert Carr578038f2018-03-09 12:25:24 -08004681 } else if (childrenOnly && layer == parent.get()) {
4682 return;
chaviwa76b2712017-09-20 12:02:26 -07004683 }
4684 visitor(layer);
4685 });
4686 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004687 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004688}
4689
4690status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4691 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004692 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004693 bool useIdentityTransform) {
4694 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004695
chaviwa76b2712017-09-20 12:02:26 -07004696 renderArea.updateDimensions();
4697
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004698 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4699 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4700 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4701 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004702
4703 // This mutex protects syncFd and captureResult for communication of the return values from the
4704 // main thread back to this Binder thread
4705 std::mutex captureMutex;
4706 std::condition_variable captureCondition;
4707 std::unique_lock<std::mutex> captureLock(captureMutex);
4708 int syncFd = -1;
4709 std::optional<status_t> captureResult;
4710
Robert Carr03480e22018-01-04 16:02:06 -08004711 const int uid = IPCThreadState::self()->getCallingUid();
4712 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4713
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004714 sp<LambdaMessage> message = new LambdaMessage([&]() {
4715 // If there is a refresh pending, bug out early and tell the binder thread to try again
4716 // after the refresh.
4717 if (mRefreshPending) {
4718 ATRACE_NAME("Skipping screenshot for now");
4719 std::unique_lock<std::mutex> captureLock(captureMutex);
4720 captureResult = std::make_optional<status_t>(EAGAIN);
4721 captureCondition.notify_one();
4722 return;
4723 }
4724
4725 status_t result = NO_ERROR;
4726 int fd = -1;
4727 {
4728 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004729 renderArea.render([&]() {
4730 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4731 useIdentityTransform, forSystem, &fd);
4732 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004733 }
4734
4735 {
4736 std::unique_lock<std::mutex> captureLock(captureMutex);
4737 syncFd = fd;
4738 captureResult = std::make_optional<status_t>(result);
4739 captureCondition.notify_one();
4740 }
4741 });
4742
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004743 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004744 if (result == NO_ERROR) {
4745 captureCondition.wait(captureLock, [&]() { return captureResult; });
4746 while (*captureResult == EAGAIN) {
4747 captureResult.reset();
4748 result = postMessageAsync(message);
4749 if (result != NO_ERROR) {
4750 return result;
4751 }
4752 captureCondition.wait(captureLock, [&]() { return captureResult; });
4753 }
4754 result = *captureResult;
4755 }
4756
4757 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004758 sync_wait(syncFd, -1);
4759 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004760 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004761
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004762 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004763}
4764
chaviwa76b2712017-09-20 12:02:26 -07004765void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4766 TraverseLayersFunction traverseLayers, bool yswap,
4767 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004768 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004769
Lloyd Pique144e1162017-12-20 16:44:52 -08004770 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004771
4772 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004773 const auto raWidth = renderArea.getWidth();
4774 const auto raHeight = renderArea.getHeight();
4775
4776 const auto reqWidth = renderArea.getReqWidth();
4777 const auto reqHeight = renderArea.getReqHeight();
4778 Rect sourceCrop = renderArea.getSourceCrop();
4779
4780 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4781 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004782
Dan Stozac1879002014-05-22 15:59:05 -07004783 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004784 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004785 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004786 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004787 }
4788
4789 // ensure that sourceCrop is inside screen
4790 if (sourceCrop.left < 0) {
4791 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4792 }
chaviwa76b2712017-09-20 12:02:26 -07004793 if (sourceCrop.right > raWidth) {
4794 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004795 }
4796 if (sourceCrop.top < 0) {
4797 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4798 }
chaviwa76b2712017-09-20 12:02:26 -07004799 if (sourceCrop.bottom > raHeight) {
4800 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004801 }
4802
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004803 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004804 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004805 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004806 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4807 }
4808 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004809
Mathias Agopian180f10d2013-04-10 22:55:41 -07004810 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004811 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004812
4813 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004814 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4815 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004816 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004817
4818 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004819 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004820
chaviwa76b2712017-09-20 12:02:26 -07004821 traverseLayers([&](Layer* layer) {
4822 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004823 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004824 if (filtering) layer->setFiltering(false);
4825 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004826}
4827
chaviwa76b2712017-09-20 12:02:26 -07004828status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4829 TraverseLayersFunction traverseLayers,
4830 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004831 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004832 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004833 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004834 ATRACE_CALL();
4835
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004836 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004837
4838 traverseLayers([&](Layer* layer) {
4839 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4840 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004841
Robert Carr03480e22018-01-04 16:02:06 -08004842 // We allow the system server to take screenshots of secure layers for
4843 // use in situations like the Screen-rotation animation and place
4844 // the impetus on WindowManager to not persist them.
4845 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004846 ALOGW("FB is protected: PERMISSION_DENIED");
4847 return PERMISSION_DENIED;
4848 }
4849
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004850 // this binds the given EGLImage as a framebuffer for the
4851 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004852 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004853 if (bufferBond.getStatus() != NO_ERROR) {
4854 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004855 return INVALID_OPERATION;
4856 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004857
Dan Stozaabcda352017-06-01 14:37:39 -07004858 // this will in fact render into our dequeued buffer
4859 // via an FBO, which means we didn't have to create
4860 // an EGLSurface and therefore we're not
4861 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004862 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004863
Dan Stozaabcda352017-06-01 14:37:39 -07004864 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004865 getRenderEngine().finish();
4866 *outSyncFd = -1;
4867
chaviwa76b2712017-09-20 12:02:26 -07004868 const auto reqWidth = renderArea.getReqWidth();
4869 const auto reqHeight = renderArea.getReqHeight();
4870
Dan Stozaabcda352017-06-01 14:37:39 -07004871 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4872 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004873 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004874 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004875 } else {
4876 base::unique_fd syncFd = getRenderEngine().flush();
4877 if (syncFd < 0) {
4878 getRenderEngine().finish();
4879 }
4880 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004881 }
4882
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004883 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004884}
4885
Mathias Agopiand5556842013-09-19 17:08:37 -07004886void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004887 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004888 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004889 for (size_t y = 0; y < h; y++) {
4890 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4891 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004892 if (p[x] != 0xFF000000) return;
4893 }
4894 }
chaviwa76b2712017-09-20 12:02:26 -07004895 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004896
Robert Carr2047fae2016-11-28 14:09:09 -08004897 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004898 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004899 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004900 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4901 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4902 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4903 static_cast<float>(state.color.a));
4904 i++;
4905 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004906 }
4907}
4908
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004909// ---------------------------------------------------------------------------
4910
Dan Stoza412903f2017-04-27 13:42:17 -07004911void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4912 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004913}
4914
Dan Stoza412903f2017-04-27 13:42:17 -07004915void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4916 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004917}
4918
chaviwa76b2712017-09-20 12:02:26 -07004919void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4920 int32_t maxLayerZ,
4921 const LayerVector::Visitor& visitor) {
4922 // We loop through the first level of layers without traversing,
4923 // as we need to interpret min/max layer Z in the top level Z space.
4924 for (const auto& layer : mDrawingState.layersSortedByZ) {
4925 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4926 continue;
4927 }
4928 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004929 // relative layers are traversed in Layer::traverseInZOrder
4930 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004931 continue;
4932 }
4933 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004934 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4935 return;
4936 }
chaviwa76b2712017-09-20 12:02:26 -07004937 if (!layer->isVisible()) {
4938 return;
4939 }
4940 visitor(layer);
4941 });
4942 }
4943}
4944
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004945}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004946
Chia-I Wu30505fb2018-03-26 16:20:31 -07004947
Mathias Agopian3f844832013-08-07 21:24:32 -07004948#if defined(__gl_h_)
4949#error "don't include gl/gl.h in this file"
4950#endif
4951
4952#if defined(__gl2_h_)
4953#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004954#endif