blob: c5bd0eb20e8fd357f2255b6be8c517cab08a657c [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109
Steven Thomasb02664d2017-07-26 18:48:28 -0700110namespace {
111class ConditionalLock {
112public:
113 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
114 if (lock) {
115 mMutex.lock();
116 }
117 }
118 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
119private:
120 Mutex& mMutex;
121 bool mLocked;
122};
123} // namespace anonymous
124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125// ---------------------------------------------------------------------------
126
Mathias Agopian99b49842011-06-27 16:05:52 -0700127const String16 sHardwareTest("android.permission.HARDWARE_TEST");
128const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
129const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
130const String16 sDump("android.permission.DUMP");
131
132// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800133int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
134int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700135int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700136bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800137uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800138bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800139bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800140int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800141// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600142bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700143
Kalle Raitaa099a242017-01-11 11:17:29 -0800144
145std::string getHwcServiceName() {
146 char value[PROPERTY_VALUE_MAX] = {};
147 property_get("debug.sf.hwc_service_name", value, "default");
148 ALOGI("Using HWComposer service: '%s'", value);
149 return std::string(value);
150}
151
152bool useTrebleTestingOverride() {
153 char value[PROPERTY_VALUE_MAX] = {};
154 property_get("debug.sf.treble_testing_override", value, "false");
155 ALOGI("Treble testing override: '%s'", value);
156 return std::string(value) == "true";
157}
158
Lloyd Pique09594832018-01-22 17:48:03 -0800159NativeWindowSurface::~NativeWindowSurface() = default;
160
161namespace impl {
162
163class NativeWindowSurface final : public android::NativeWindowSurface {
164public:
165 static std::unique_ptr<android::NativeWindowSurface> create(
166 const sp<IGraphicBufferProducer>& producer) {
167 return std::make_unique<NativeWindowSurface>(producer);
168 }
169
170 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
171 : surface(new Surface(producer, false)) {}
172
173 ~NativeWindowSurface() override = default;
174
175private:
176 sp<ANativeWindow> getNativeWindow() const override { return surface; }
177
178 void preallocateBuffers() override { surface->allocateBuffers(); }
179
180 sp<Surface> surface;
181};
182
183} // namespace impl
184
David Sodmanbc815282017-11-05 18:57:52 -0800185SurfaceFlingerBE::SurfaceFlingerBE()
186 : mHwcServiceName(getHwcServiceName()),
187 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800188 mFrameBuckets(),
189 mTotalTime(0),
190 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800191 mComposerSequenceId(0) {
192}
193
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800194SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800195 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700197 mTransactionPending(false),
198 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700199 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700200 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700201 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800203 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800205 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800206 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700208 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700209 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700210 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700211 mDebugInSwapBuffers(0),
212 mLastSwapBufferTime(0),
213 mDebugInTransaction(0),
214 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700215 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700216 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000217 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700218 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700219 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700220 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800221 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800222 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700223 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800224 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800225 mCreateBufferQueue(&BufferQueue::createBufferQueue),
226 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800227
228SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800229 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800230
231 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
232 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
233
234 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
235 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
236
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800237 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
238 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700240 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
241 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
242
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700243 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
244 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
245
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800246 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
247 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
248
Steven Thomas050b2c82017-03-06 11:45:16 -0800249 // Vr flinger is only enabled on Daydream ready devices.
250 useVrFlinger = getBool< ISurfaceFlingerConfigs,
251 &ISurfaceFlingerConfigs::useVrFlinger>(false);
252
Fabien Sanglard1971b632017-03-10 14:50:03 -0800253 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
254 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
255
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600256 hasWideColorDisplay =
257 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
258
David Sodman99974d22017-11-28 12:04:33 -0800259 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 // debugging stuff...
262 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700263
Mathias Agopianb4b17302013-03-20 18:36:41 -0700264 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700265 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700266
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267 property_get("debug.sf.showupdates", value, "0");
268 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700269
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700270 property_get("debug.sf.ddms", value, "0");
271 mDebugDDMS = atoi(value);
272 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700273 if (!startDdmConnection()) {
274 // start failed, and DDMS debugging not enabled
275 mDebugDDMS = 0;
276 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700277 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700278 ALOGI_IF(mDebugRegion, "showupdates enabled");
279 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700280
281 property_get("debug.sf.disable_backpressure", value, "0");
282 mPropagateBackpressure = !atoi(value);
283 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700284
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800285 property_get("debug.sf.enable_hwc_vds", value, "0");
286 mUseHwcVirtualDisplays = atoi(value);
287 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800288
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800289 property_get("ro.sf.disable_triple_buffer", value, "1");
290 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800291 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700292
Dan Stoza0a0158c2018-03-16 13:38:54 -0700293 // TODO (b/74616334): Reduce the default value once we isolate the leak
294 const size_t defaultListSize = 4 * MAX_LAYERS;
295 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
296 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
297
Romain Guy11d63f42017-07-20 12:47:14 -0700298 // We should be reading 'persist.sys.sf.color_saturation' here
299 // but since /data may be encrypted, we need to wait until after vold
300 // comes online to attempt to read the property. The property is
301 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800302
303 if (useTrebleTestingOverride()) {
304 // Without the override SurfaceFlinger cannot connect to HIDL
305 // services that are not listed in the manifests. Considered
306 // deriving the setting from the set service name, but it
307 // would be brittle if the name that's not 'default' is used
308 // for production purposes later on.
309 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
310 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311}
312
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800313void SurfaceFlinger::onFirstRef()
314{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800315 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800316}
317
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318SurfaceFlinger::~SurfaceFlinger()
319{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Dan Stozac7014012014-02-14 15:03:43 -0800322void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800323{
324 // the window manager died on us. prepare its eulogy.
325
Andy McFadden13a082e2012-08-24 10:16:42 -0700326 // restore initial conditions (default device unblank, etc)
327 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800328
329 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700330 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800331}
332
Robert Carr1db73f62016-12-21 12:58:51 -0800333static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700334 status_t err = client->initCheck();
335 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800336 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 }
Robert Carr1db73f62016-12-21 12:58:51 -0800338 return nullptr;
339}
340
341sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
342 return initClient(new Client(this));
343}
344
345sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
346 const sp<IGraphicBufferProducer>& gbp) {
347 if (authenticateSurfaceTexture(gbp) == false) {
348 return nullptr;
349 }
350 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
351 if (layer == nullptr) {
352 return nullptr;
353 }
354
355 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356}
357
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700358sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
359 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700360{
361 class DisplayToken : public BBinder {
362 sp<SurfaceFlinger> flinger;
363 virtual ~DisplayToken() {
364 // no more references, this display must be terminated
365 Mutex::Autolock _l(flinger->mStateLock);
366 flinger->mCurrentState.displays.removeItem(this);
367 flinger->setTransactionFlags(eDisplayTransactionNeeded);
368 }
369 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700370 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700371 : flinger(flinger) {
372 }
373 };
374
375 sp<BBinder> token = new DisplayToken(this);
376
377 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700379 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700380 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800381 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700382 return token;
383}
384
Jesse Hall6c913be2013-08-08 12:15:49 -0700385void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
386 Mutex::Autolock _l(mStateLock);
387
388 ssize_t idx = mCurrentState.displays.indexOfKey(display);
389 if (idx < 0) {
390 ALOGW("destroyDisplay: invalid display token");
391 return;
392 }
393
394 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
395 if (!info.isVirtualDisplay()) {
396 ALOGE("destroyDisplay called for non-virtual display");
397 return;
398 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800399 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700400 mCurrentState.displays.removeItemsAt(idx);
401 setTransactionFlags(eDisplayTransactionNeeded);
402}
403
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700405 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800407 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700408 }
Jesse Hall692c7232012-11-08 15:41:56 -0800409 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700410}
411
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412void SurfaceFlinger::bootFinished()
413{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700414 if (mStartPropertySetThread->join() != NO_ERROR) {
415 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800416 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 const nsecs_t now = systemTime();
418 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000419 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700420
421 // wait patiently for the window manager death
422 const String16 name("window");
423 sp<IBinder> window(defaultServiceManager()->getService(name));
424 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700426 }
427
Steven Thomas050b2c82017-03-06 11:45:16 -0800428 if (mVrFlinger) {
429 mVrFlinger->OnBootFinished();
430 }
431
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700432 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700433 // formerly we would just kill the process, but we now ask it to exit so it
434 // can choose where to stop the animation.
435 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700436
437 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
438 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
439 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700440
Thierry Strudel2924d012017-08-14 15:19:37 -0700441 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700442 readPersistentProperties();
443 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700444 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445}
446
Mathias Agopian3f844832013-08-07 21:24:32 -0700447void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700448 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800449 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700450 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700451 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800452 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
453 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700454 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700455 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700456 return true;
457 }
458 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700459 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700460}
461
Lloyd Piquee83f9312018-02-01 12:53:17 -0800462class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700464 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 const char* name) :
466 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700467 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700468 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000469 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
470 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 mDispSync(dispSync),
472 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 mVsyncMutex(),
474 mPhaseOffset(phaseOffset),
475 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700476
Lloyd Piquee83f9312018-02-01 12:53:17 -0800477 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478
Lloyd Piquee83f9312018-02-01 12:53:17 -0800479 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000482 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483 static_cast<DispSync::Callback*>(this));
484 if (err != NO_ERROR) {
485 ALOGE("error registering vsync callback: %s (%d)",
486 strerror(-err), err);
487 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700488 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 } else {
490 status_t err = mDispSync->removeEventListener(
491 static_cast<DispSync::Callback*>(this));
492 if (err != NO_ERROR) {
493 ALOGE("error unregistering vsync callback: %s (%d)",
494 strerror(-err), err);
495 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700496 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700498 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499 }
500
Lloyd Piquee83f9312018-02-01 12:53:17 -0800501 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700502 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 mCallback = callback;
504 }
505
Lloyd Piquee83f9312018-02-01 12:53:17 -0800506 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700507 Mutex::Autolock lock(mVsyncMutex);
508
509 // Normalize phaseOffset to [0, period)
510 auto period = mDispSync->getPeriod();
511 phaseOffset %= period;
512 if (phaseOffset < 0) {
513 // If we're here, then phaseOffset is in (-period, 0). After this
514 // operation, it will be in (0, period)
515 phaseOffset += period;
516 }
517 mPhaseOffset = phaseOffset;
518
519 // If we're not enabled, we don't need to mess with the listeners
520 if (!mEnabled) {
521 return;
522 }
523
524 // Remove the listener with the old offset
525 status_t err = mDispSync->removeEventListener(
526 static_cast<DispSync::Callback*>(this));
527 if (err != NO_ERROR) {
528 ALOGE("error unregistering vsync callback: %s (%d)",
529 strerror(-err), err);
530 }
531
532 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000533 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534 static_cast<DispSync::Callback*>(this));
535 if (err != NO_ERROR) {
536 ALOGE("error registering vsync callback: %s (%d)",
537 strerror(-err), err);
538 }
539 }
540
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541private:
542 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800543 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700545 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700546 callback = mCallback;
547
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700548 if (mTraceVsync) {
549 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700550 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700551 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 }
553
Peiyong Lin566a3b42018-01-09 18:22:43 -0800554 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555 callback->onVSyncEvent(when);
556 }
557 }
558
Tim Murray4a4e4a22016-04-19 16:29:23 +0000559 const char* const mName;
560
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 int mValue;
562
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700563 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700564 const String8 mVsyncOnLabel;
565 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700566
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568
569 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800570 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571
572 Mutex mVsyncMutex; // Protects the following
573 nsecs_t mPhaseOffset;
574 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575};
576
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700578public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800579 InjectVSyncSource() = default;
580 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700581
Lloyd Piquee83f9312018-02-01 12:53:17 -0800582 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700583 std::lock_guard<std::mutex> lock(mCallbackMutex);
584 mCallback = callback;
585 }
586
Lloyd Piquee83f9312018-02-01 12:53:17 -0800587 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700588 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700589 if (mCallback) {
590 mCallback->onVSyncEvent(when);
591 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700592 }
593
Lloyd Piquee83f9312018-02-01 12:53:17 -0800594 void setVSyncEnabled(bool) override {}
595 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700596
597private:
598 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800599 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700600};
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
607
Thierry Strudel2924d012017-08-14 15:19:37 -0700608 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800613 mEventThreadSource =
614 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
615 true, "app");
616 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
617 "appEventThread");
618 mSfEventThreadSource =
619 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
620 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800621
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800622 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
623 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800624 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800627 getBE().mRenderEngine =
628 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
629 hasWideColorDisplay
630 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
631 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800632 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700633
634 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
635 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800636 getBE().mHwc.reset(
637 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700638 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800639 // Process any initial hotplug and resulting display changes.
640 processDisplayHotplugEventsLocked();
641 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
642 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800643
Lloyd Piquefcd86612017-12-14 17:15:36 -0800644 // make the default display GLContext current so that we can create textures
645 // when creating Layers (which may happens before we render something)
646 getDefaultDisplayDeviceLocked()->makeCurrent();
647
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 if (useVrFlinger) {
649 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700650 // This callback is called from the vr flinger dispatch thread. We
651 // need to call signalTransaction(), which requires holding
652 // mStateLock when we're not on the main thread. Acquiring
653 // mStateLock from the vr flinger dispatch thread might trigger a
654 // deadlock in surface flinger (see b/66916578), so post a message
655 // to be handled on the main thread instead.
656 sp<LambdaMessage> message = new LambdaMessage([=]() {
657 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
658 mVrFlingerRequestsDisplay = requestDisplay;
659 signalTransaction();
660 });
661 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 };
David Sodman105b7dc2017-11-04 20:28:14 -0700663 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
664 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800665 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 if (!mVrFlinger) {
667 ALOGE("Failed to start vrflinger");
668 }
669 }
670
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800671 mEventControlThread = std::make_unique<impl::EventControlThread>(
672 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700673
Mathias Agopian92a979a2012-08-02 18:32:23 -0700674 // initialize our drawing state
675 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700676
Andy McFadden13a082e2012-08-24 10:16:42 -0700677 // set initial conditions (e.g. unblank default device)
678 initializeDisplays();
679
David Sodmanbc815282017-11-05 18:57:52 -0800680 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700681
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 // Inform native graphics APIs whether the present timestamp is supported:
683 if (getHwComposer().hasCapability(
684 HWC2::Capability::PresentFenceIsNotReliable)) {
685 mStartPropertySetThread = new StartPropertySetThread(false);
686 } else {
687 mStartPropertySetThread = new StartPropertySetThread(true);
688 }
689
690 if (mStartPropertySetThread->Start() != NO_ERROR) {
691 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800692 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800693
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700695}
696
Romain Guy11d63f42017-07-20 12:47:14 -0700697void SurfaceFlinger::readPersistentProperties() {
698 char value[PROPERTY_VALUE_MAX];
699
700 property_get("persist.sys.sf.color_saturation", value, "1.0");
701 mSaturation = atof(value);
702 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100703
704 property_get("persist.sys.sf.native_mode", value, "0");
705 mForceNativeColorMode = atoi(value) == 1;
706 if (mForceNativeColorMode) {
707 ALOGV("Forcing native color mode");
708 }
Romain Guy11d63f42017-07-20 12:47:14 -0700709}
710
Mathias Agopiana67e4182012-06-19 17:26:12 -0700711void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800712 // Start boot animation service by setting a property mailbox
713 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800715 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700716 if (mStartPropertySetThread->join() != NO_ERROR) {
717 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800718 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700719}
720
Mathias Agopian875d8e12013-06-07 15:35:48 -0700721size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800722 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700723}
724
Mathias Agopian875d8e12013-06-07 15:35:48 -0700725size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800726 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700727}
728
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800730
Jamie Gennis582270d2011-08-17 18:19:00 -0700731bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800732 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800733 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800734 return authenticateSurfaceTextureLocked(bufferProducer);
735}
736
737bool SurfaceFlinger::authenticateSurfaceTextureLocked(
738 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800739 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800740 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800741}
742
Brian Anderson6b376712017-04-04 10:51:39 -0700743status_t SurfaceFlinger::getSupportedFrameTimestamps(
744 std::vector<FrameEvent>* outSupported) const {
745 *outSupported = {
746 FrameEvent::REQUESTED_PRESENT,
747 FrameEvent::ACQUIRE,
748 FrameEvent::LATCH,
749 FrameEvent::FIRST_REFRESH_START,
750 FrameEvent::LAST_REFRESH_START,
751 FrameEvent::GPU_COMPOSITION_DONE,
752 FrameEvent::DEQUEUE_READY,
753 FrameEvent::RELEASE,
754 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700755 ConditionalLock _l(mStateLock,
756 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700757 if (!getHwComposer().hasCapability(
758 HWC2::Capability::PresentFenceIsNotReliable)) {
759 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
760 }
761 return NO_ERROR;
762}
763
Dan Stoza7f7da322014-05-02 15:26:25 -0700764status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
765 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800766 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700767 return BAD_VALUE;
768 }
769
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500770 if (!display.get())
771 return NAME_NOT_FOUND;
772
Jesse Hall692c7232012-11-08 15:41:56 -0800773 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700774 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800775 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700776 type = i;
777 break;
778 }
779 }
780
781 if (type < 0) {
782 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700783 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784
Mathias Agopian8b736f12012-08-13 17:54:26 -0700785 // TODO: Not sure if display density should handled by SF any longer
786 class Density {
787 static int getDensityFromProperty(char const* propName) {
788 char property[PROPERTY_VALUE_MAX];
789 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800790 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700791 density = atoi(property);
792 }
793 return density;
794 }
795 public:
796 static int getEmuDensity() {
797 return getDensityFromProperty("qemu.sf.lcd_density"); }
798 static int getBuildDensity() {
799 return getDensityFromProperty("ro.sf.lcd_density"); }
800 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700801
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700803
Steven Thomas6d8110b2017-08-31 18:24:21 -0700804 ConditionalLock _l(mStateLock,
805 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 DisplayInfo info = DisplayInfo();
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 float xdpi = hwConfig->getDpiX();
810 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811
812 if (type == DisplayDevice::DISPLAY_PRIMARY) {
813 // The density of the device is provided by a build property
814 float density = Density::getBuildDensity() / 160.0f;
815 if (density == 0) {
816 // the build doesn't provide a density -- this is wrong!
817 // use xdpi instead
818 ALOGE("ro.sf.lcd_density must be defined as a build property");
819 density = xdpi / 160.0f;
820 }
821 if (Density::getEmuDensity()) {
822 // if "qemu.sf.lcd_density" is specified, it overrides everything
823 xdpi = ydpi = density = Density::getEmuDensity();
824 density /= 160.0f;
825 }
826 info.density = density;
827
828 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700829 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800830 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 } else {
832 // TODO: where should this value come from?
833 static const int TV_DENSITY = 213;
834 info.density = TV_DENSITY / 160.0f;
835 info.orientation = 0;
836 }
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 info.w = hwConfig->getWidth();
839 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 info.xdpi = xdpi;
841 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900843 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844
Andy McFadden91b2ca82014-06-13 14:04:23 -0700845 // This is how far in advance a buffer must be queued for
846 // presentation at a given time. If you want a buffer to appear
847 // on the screen at time N, you must submit the buffer before
848 // (N - presentationDeadline).
849 //
850 // Normally it's one full refresh period (to give SF a chance to
851 // latch the buffer), but this can be reduced by configuring a
852 // DispSync offset. Any additional delays introduced by the hardware
853 // composer or panel must be accounted for here.
854 //
855 // We add an additional 1ms to allow for processing time and
856 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800858 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700859
860 // All non-virtual displays are currently considered secure.
861 info.secure = true;
862
Michael Wright28f24d02016-07-12 13:30:53 -0700863 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700864 }
865
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 return NO_ERROR;
867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800869status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800871 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700872 return BAD_VALUE;
873 }
874
875 // FIXME for now we always return stats for the primary display
876 memset(stats, 0, sizeof(*stats));
877 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
878 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
879 return NO_ERROR;
880}
881
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700882int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800883 if (display == nullptr) {
884 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800885 return BAD_VALUE;
886 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700887
888 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800889 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700890 return device->getActiveConfig();
891 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700892
Dan Stoza24a42e92015-03-09 10:04:11 -0700893 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700896void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
897 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
898 this);
899 int32_t type = hw->getDisplayType();
900 int currentMode = hw->getActiveConfig();
901
902 if (mode == currentMode) {
903 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
904 return;
905 }
906
907 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
908 ALOGW("Trying to set config for virtual display");
909 return;
910 }
911
912 hw->setActiveConfig(mode);
913 getHwComposer().setActiveConfig(type, mode);
914}
915
916status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
917 class MessageSetActiveConfig: public MessageBase {
918 SurfaceFlinger& mFlinger;
919 sp<IBinder> mDisplay;
920 int mMode;
921 public:
922 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
923 int mode) :
924 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
925 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700926 Vector<DisplayInfo> configs;
927 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700928 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700929 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700930 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700931 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700932 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700933 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800934 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700936 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
938 ALOGW("Attempt to set active config = %d for virtual display",
939 mMode);
940 } else {
941 mFlinger.setActiveConfigInternal(hw, mMode);
942 }
943 return true;
944 }
945 };
946 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
947 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700948 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700949}
Michael Wright28f24d02016-07-12 13:30:53 -0700950status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700951 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700952 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
953 return BAD_VALUE;
954 }
955
956 if (!display.get()) {
957 return NAME_NOT_FOUND;
958 }
959
960 int32_t type = NAME_NOT_FOUND;
961 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
962 if (display == mBuiltinDisplays[i]) {
963 type = i;
964 break;
965 }
966 }
967
968 if (type < 0) {
969 return type;
970 }
971
Peiyong Lina52f0292018-03-14 17:26:31 -0700972 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700973 {
974 ConditionalLock _l(mStateLock,
975 std::this_thread::get_id() != mMainThreadId);
976 modes = getHwComposer().getColorModes(type);
977 }
Michael Wright28f24d02016-07-12 13:30:53 -0700978 outColorModes->clear();
979 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
980
981 return NO_ERROR;
982}
983
Peiyong Lina52f0292018-03-14 17:26:31 -0700984ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700985 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700986 if (device != nullptr) {
987 return device->getActiveColorMode();
988 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700990}
991
992void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700994 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700995 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700996
997 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700998 return;
999 }
1000
1001 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1002 ALOGW("Trying to set config for virtual display");
1003 return;
1004 }
1005
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1007 hw->getDisplayType());
1008
Michael Wright28f24d02016-07-12 13:30:53 -07001009 hw->setActiveColorMode(mode);
1010 getHwComposer().setActiveColorMode(type, mode);
1011}
1012
1013
1014status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001015 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001016 class MessageSetActiveColorMode: public MessageBase {
1017 SurfaceFlinger& mFlinger;
1018 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001020 public:
1021 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001023 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1024 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001026 mFlinger.getDisplayColorModes(mDisplay, &modes);
1027 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001028 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001029 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1030 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001031 return true;
1032 }
1033 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1034 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001035 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1036 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001037 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001038 ALOGW("Attempt to set active color mode %s %d for virtual display",
1039 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001040 } else {
1041 mFlinger.setActiveColorModeInternal(hw, mMode);
1042 }
1043 return true;
1044 }
1045 };
1046 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1047 postMessageSync(msg);
1048 return NO_ERROR;
1049}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001050
Svetoslavd85084b2014-03-20 10:28:31 -07001051status_t SurfaceFlinger::clearAnimationFrameStats() {
1052 Mutex::Autolock _l(mStateLock);
1053 mAnimFrameTracker.clearStats();
1054 return NO_ERROR;
1055}
1056
1057status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1058 Mutex::Autolock _l(mStateLock);
1059 mAnimFrameTracker.getStats(outStats);
1060 return NO_ERROR;
1061}
1062
Dan Stozac4f471e2016-03-24 09:31:08 -07001063status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1064 HdrCapabilities* outCapabilities) const {
1065 Mutex::Autolock _l(mStateLock);
1066
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001067 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001068 if (displayDevice == nullptr) {
1069 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1070 return BAD_VALUE;
1071 }
1072
1073 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001074 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001075 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001076 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1077 // insert HDR10 as we will force client composition for HDR10
1078 // layers
1079 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1080 types.push_back(HAL_HDR_HDR10);
1081
1082 *outCapabilities = HdrCapabilities(types,
1083 capabilities->getDesiredMaxLuminance(),
1084 capabilities->getDesiredMaxAverageLuminance(),
1085 capabilities->getDesiredMinLuminance());
1086 } else {
1087 *outCapabilities = std::move(*capabilities);
1088 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001089 } else {
1090 return BAD_VALUE;
1091 }
1092
1093 return NO_ERROR;
1094}
1095
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001096status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1098 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099
Chia-I Wu90f669f2017-10-05 14:24:41 -07001100 if (mInjectVSyncs == enable) {
1101 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001102 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103
1104 if (enable) {
1105 ALOGV("VSync Injections enabled");
1106 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001107 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001108 mInjectorEventThread =
1109 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1110 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001112 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 } else {
1114 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001115 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001116 }
1117
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001118 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 });
1120 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001121 return NO_ERROR;
1122}
1123
1124status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 Mutex::Autolock _l(mStateLock);
1126
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001127 if (!mInjectVSyncs) {
1128 ALOGE("VSync Injections not enabled");
1129 return BAD_VALUE;
1130 }
1131 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1132 ALOGV("Injecting VSync inside SurfaceFlinger");
1133 mVSyncInjector->onInjectSyncEvent(when);
1134 }
1135 return NO_ERROR;
1136}
1137
Lloyd Pique755e3192018-01-31 16:46:15 -08001138status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1139 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001140 IPCThreadState* ipc = IPCThreadState::self();
1141 const int pid = ipc->getCallingPid();
1142 const int uid = ipc->getCallingUid();
1143 if ((uid != AID_SHELL) &&
1144 !PermissionCache::checkPermission(sDump, pid, uid)) {
1145 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1146 return PERMISSION_DENIED;
1147 }
1148
1149 // Try to acquire a lock for 1s, fail gracefully
1150 const status_t err = mStateLock.timedLock(s2ns(1));
1151 const bool locked = (err == NO_ERROR);
1152 if (!locked) {
1153 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1154 return TIMED_OUT;
1155 }
1156
1157 outLayers->clear();
1158 mCurrentState.traverseInZOrder([&](Layer* layer) {
1159 outLayers->push_back(layer->getLayerDebugInfo());
1160 });
1161
1162 mStateLock.unlock();
1163 return NO_ERROR;
1164}
1165
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001166// ----------------------------------------------------------------------------
1167
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001168sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1169 ISurfaceComposer::VsyncSource vsyncSource) {
1170 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1171 return mSFEventThread->createEventConnection();
1172 } else {
1173 return mEventThread->createEventConnection();
1174 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001175}
1176
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001177// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001178
1179void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001180 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001181}
1182
1183void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001184 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001185}
1186
1187void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001188 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001189}
1190
1191void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001192 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001193 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001197 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001198 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001199}
1200
1201status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001202 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001203 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001204 if (res == NO_ERROR) {
1205 msg->wait();
1206 }
1207 return res;
1208}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001209
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001210void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001211 do {
1212 waitForEvent();
1213 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001214}
1215
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216void SurfaceFlinger::enableHardwareVsync() {
1217 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001218 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001220 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1221 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001223 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224}
1225
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 Mutex::Autolock _l(mHWVsyncLock);
1228
Jesse Hall948fe0c2013-10-14 12:56:09 -07001229 if (makeAvailable) {
1230 mHWVsyncAvailable = true;
1231 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001232 // Hardware vsync is not currently available, so abort the resync
1233 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001234 return;
1235 }
1236
David Sodman105b7dc2017-11-04 20:28:14 -07001237 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001239
1240 mPrimaryDispSync.reset();
1241 mPrimaryDispSync.setPeriod(period);
1242
1243 if (!mPrimaryHWVsyncEnabled) {
1244 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001245 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1246 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001247 mPrimaryHWVsyncEnabled = true;
1248 }
1249}
1250
Jesse Hall948fe0c2013-10-14 12:56:09 -07001251void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252 Mutex::Autolock _l(mHWVsyncLock);
1253 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1255 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 mPrimaryDispSync.endResync();
1257 mPrimaryHWVsyncEnabled = false;
1258 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001259 if (makeUnavailable) {
1260 mHWVsyncAvailable = false;
1261 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262}
1263
Tim Murray4a4e4a22016-04-19 16:29:23 +00001264void SurfaceFlinger::resyncWithRateLimit() {
1265 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001266
1267 // No explicit locking is needed here since EventThread holds a lock while calling this method
1268 static nsecs_t sLastResyncAttempted = 0;
1269 const nsecs_t now = systemTime();
1270 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001271 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001272 }
Dan Stoza57164302017-05-08 14:03:54 -07001273 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001274}
1275
Steven Thomasb02664d2017-07-26 18:48:28 -07001276void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1277 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001278 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001279 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001280 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001281 return;
1282 }
1283
1284 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001285 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001286 return;
1287 }
1288
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290
Jamie Gennisd1700752013-10-14 12:22:52 -07001291 { // Scope for the lock
1292 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001293 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001296 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001297
1298 if (needsHwVsync) {
1299 enableHardwareVsync();
1300 } else {
1301 disableHardwareVsync(false);
1302 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001303}
1304
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001305void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001306 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1307 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001308}
1309
Lloyd Pique715a2c12017-12-14 17:18:08 -08001310void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1311 HWC2::Connection connection) {
1312 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1313 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001314
Lloyd Piqueba04e622017-12-14 17:11:26 -08001315 // Ignore events that do not have the right sequenceId.
1316 if (sequenceId != getBE().mComposerSequenceId) {
1317 return;
1318 }
1319
Steven Thomasb02664d2017-07-26 18:48:28 -07001320 // Only lock if we're not on the main thread. This function is normally
1321 // called on a hwbinder thread, but for the primary display it's called on
1322 // the main thread with the state lock already held, so don't attempt to
1323 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001324 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001325
Lloyd Pique715a2c12017-12-14 17:18:08 -08001326 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001327
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001328 if (std::this_thread::get_id() == mMainThreadId) {
1329 // Process all pending hot plug events immediately if we are on the main thread.
1330 processDisplayHotplugEventsLocked();
1331 }
1332
Lloyd Piqueba04e622017-12-14 17:11:26 -08001333 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001334}
1335
Steven Thomasb02664d2017-07-26 18:48:28 -07001336void SurfaceFlinger::onRefreshReceived(int sequenceId,
1337 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001338 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001341 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001342 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001343}
1344
Dan Stoza9e56aa02015-11-02 13:00:03 -08001345void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001348 getHwComposer().setVsyncEnabled(disp,
1349 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001350}
1351
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001353void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 // Clear the drawing state so that the logic inside of
1356 // handleTransactionLocked will fire. It will determine the delta between
1357 // mCurrentState and mDrawingState and re-apply all changes when we make the
1358 // transition.
1359 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001360 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361 mDisplays.clear();
1362}
1363
Steven Thomas050b2c82017-03-06 11:45:16 -08001364void SurfaceFlinger::updateVrFlinger() {
1365 if (!mVrFlinger)
1366 return;
1367 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001368 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001369 return;
1370 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001371
David Sodman105b7dc2017-11-04 20:28:14 -07001372 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 ALOGE("Vr flinger is only supported for remote hardware composer"
1374 " service connections. Ignoring request to transition to vr"
1375 " flinger.");
1376 mVrFlingerRequestsDisplay = false;
1377 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001378 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001380 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 int currentDisplayPowerMode = getDisplayDeviceLocked(
1383 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001390 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001391 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1392 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001393 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
David Sodman105b7dc2017-11-04 20:28:14 -07001395 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1396 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001397
1398 if (vrFlingerRequestsDisplay) {
1399 mVrFlinger->GrantDisplayOwnership();
1400 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001403
1404 mVisibleRegionsDirty = true;
1405 invalidateHwcGeometry();
1406
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001407 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1409 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1410 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001413 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 const nsecs_t period = activeConfig->getVsyncPeriod();
1415 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 // Use phase of 0 since phase is not known.
1418 // Use latency of 0, which will snap to the ideal latency.
1419 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001420
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 android_atomic_or(1, &mRepaintEverything);
1422 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423}
1424
Mathias Agopian4fec8732012-06-29 14:12:52 -07001425void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001426 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001427 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001428 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001429 bool frameMissed = !mHadClientComposition &&
1430 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001431 (mPreviousPresentFence->getSignalTime() ==
1432 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001433 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001434 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001435 signalLayerUpdate();
1436 break;
1437 }
1438
Steven Thomas050b2c82017-03-06 11:45:16 -08001439 // Now that we're going to make it to the handleMessageTransaction()
1440 // call below it's safe to call updateVrFlinger(), which will
1441 // potentially trigger a display handoff.
1442 updateVrFlinger();
1443
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 bool refreshNeeded = handleMessageTransaction();
1445 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001446 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001448 // Signal a refresh if a transaction modified the window state,
1449 // a new buffer was latched, or if HWC has requested a full
1450 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 signalRefresh();
1452 }
1453 break;
1454 }
1455 case MessageQueue::REFRESH: {
1456 handleMessageRefresh();
1457 break;
1458 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459 }
1460}
1461
Dan Stoza6b9454d2014-11-07 16:00:59 -08001462bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001463 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001464 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001465 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469}
1470
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474}
1475
1476void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001478
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001479 mRefreshPending = false;
1480
Pablo Ceballos40845df2016-01-25 17:41:15 -08001481 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001482
Brian Andersond6927fb2016-07-23 23:37:30 -07001483 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001484 rebuildLayerStacks();
1485 setUpHWComposer();
1486 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001487 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001488 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001489 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001490 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001491
David Sodman105b7dc2017-11-04 20:28:14 -07001492 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001493
1494 mHadClientComposition = false;
1495 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1496 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1497 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001498 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001499 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001500
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504void SurfaceFlinger::doDebugFlashRegions()
1505{
1506 // is debugging enabled
1507 if (CC_LIKELY(!mDebugRegion))
1508 return;
1509
1510 const bool repaintEverything = mRepaintEverything;
1511 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1512 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001513 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514 // transform the dirty region into this screen's coordinate space
1515 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1516 if (!dirtyRegion.isEmpty()) {
1517 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001518 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519
1520 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001522 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001523 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1524
Mathias Agopianda27af92012-09-13 18:17:13 -07001525 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 }
1527 }
1528 }
1529
1530 postFramebuffer();
1531
1532 if (mDebugRegion > 1) {
1533 usleep(mDebugRegion * 1000);
1534 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001535
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001537 auto& displayDevice = mDisplays[displayId];
1538 if (!displayDevice->isDisplayOn()) {
1539 continue;
1540 }
1541
David Sodman105b7dc2017-11-04 20:28:14 -07001542 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1543 ALOGE_IF(result != NO_ERROR,
1544 "prepareFrame for display %zd failed:"
1545 " %d (%s)",
1546 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001547 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548}
1549
Adrian Roos1e1a1282017-11-01 19:05:31 +01001550void SurfaceFlinger::doTracing(const char* where) {
1551 ATRACE_CALL();
1552 ATRACE_NAME(where);
1553 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001554 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001555 }
1556}
1557
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001558void SurfaceFlinger::logLayerStats() {
1559 ATRACE_CALL();
1560 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1561 int32_t hwcId = -1;
1562 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1563 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1564 if (displayDevice->isPrimary()) {
1565 hwcId = displayDevice->getHwcDisplayId();
1566 break;
1567 }
1568 }
1569 if (hwcId < 0) {
1570 ALOGE("LayerStats: Hmmm, no primary display?");
1571 return;
1572 }
1573 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1574 }
1575}
1576
Brian Andersond6927fb2016-07-23 23:37:30 -07001577void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001579 ATRACE_CALL();
1580 ALOGV("preComposition");
1581
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001583 mDrawingState.traverseInZOrder([&](Layer* layer) {
1584 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585 needExtraInvalidate = true;
1586 }
Robert Carr2047fae2016-11-28 14:09:09 -08001587 });
1588
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 if (needExtraInvalidate) {
1590 signalLayerUpdate();
1591 }
1592}
1593
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594void SurfaceFlinger::updateCompositorTiming(
1595 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1596 std::shared_ptr<FenceTime>& presentFenceTime) {
1597 // Update queue of past composite+present times and determine the
1598 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001599 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001601 while (!getBE().mCompositePresentTimes.empty()) {
1602 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 // Cached values should have been updated before calling this method,
1604 // which helps avoid duplicate syscalls.
1605 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1606 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1607 break;
1608 }
1609 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001610 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611 }
1612
1613 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001614 while (getBE().mCompositePresentTimes.size() > 16) {
1615 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616 }
1617
Brian Andersond0010582017-03-07 13:20:31 -08001618 setCompositorTimingSnapped(
1619 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1620}
1621
1622void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1623 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624 // Integer division and modulo round toward 0 not -inf, so we need to
1625 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001626 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1628 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1629
Brian Andersond0010582017-03-07 13:20:31 -08001630 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1631 if (idealLatency <= 0) {
1632 idealLatency = vsyncInterval;
1633 }
1634
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635 // Snap the latency to a value that removes scheduling jitter from the
1636 // composition and present times, which often have >1ms of jitter.
1637 // Reducing jitter is important if an app attempts to extrapolate
1638 // something (such as user input) to an accurate diasplay time.
1639 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1640 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001641 nsecs_t bias = vsyncInterval / 2;
1642 int64_t extraVsyncs =
1643 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1644 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1645 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646
David Sodman99974d22017-11-28 12:04:33 -08001647 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1648 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1649 getBE().mCompositorTiming.interval = vsyncInterval;
1650 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651}
1652
1653void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001654{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 ATRACE_CALL();
1656 ALOGV("postComposition");
1657
Brian Anderson3546a3f2016-07-14 11:51:14 -07001658 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001659 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001660 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001661 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001662 }
1663
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664 // |mStateLock| not needed as we are on the main thread
1665 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001666
David Sodman73beded2017-11-15 11:56:06 -08001667 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001669 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001670 glCompositionDoneFenceTime =
1671 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001672 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 } else {
1674 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1675 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001676
David Sodman73beded2017-11-15 11:56:06 -08001677 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001678 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001679 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001680 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001681
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1683 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1684
1685 // We use the refreshStartTime which might be sampled a little later than
1686 // when we started doing work for this frame, but that should be okay
1687 // since updateCompositorTiming has snapping logic.
1688 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001689 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001690 CompositorTiming compositorTiming;
1691 {
David Sodman99974d22017-11-28 12:04:33 -08001692 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1693 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001694 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695
Robert Carr2047fae2016-11-28 14:09:09 -08001696 mDrawingState.traverseInZOrder([&](Layer* layer) {
1697 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001698 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001699 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001700 recordBufferingStats(layer->getName().string(),
1701 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001702 }
Robert Carr2047fae2016-11-28 14:09:09 -08001703 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001704
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001705 if (presentFenceTime->isValid()) {
1706 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001707 enableHardwareVsync();
1708 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001709 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001710 }
1711 }
1712
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001713 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001714 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001715 enableHardwareVsync();
1716 }
1717 }
1718
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001719 if (mAnimCompositionPending) {
1720 mAnimCompositionPending = false;
1721
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001723 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001724 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001725 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001726 // The HWC doesn't support present fences, so use the refresh
1727 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001729 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001730 mAnimFrameTracker.setActualPresentTime(presentTime);
1731 }
1732 mAnimFrameTracker.advanceFrame();
1733 }
Dan Stozab90cf072015-03-05 11:05:59 -08001734
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001735 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1736 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001737 return;
1738 }
1739
1740 nsecs_t currentTime = systemTime();
1741 if (mHasPoweredOff) {
1742 mHasPoweredOff = false;
1743 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001744 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001746 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1747 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001748 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001749 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001750 }
David Sodman4a36e932017-11-07 14:29:47 -08001751 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001752 }
David Sodman4a36e932017-11-07 14:29:47 -08001753 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754}
1755
1756void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 ATRACE_CALL();
1758 ALOGV("rebuildLayerStacks");
1759
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001761 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001762 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001763 mVisibleRegionsDirty = false;
1764 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001765
Jeff Sharkey76488112017-02-27 14:15:18 -07001766 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1767 Region opaqueRegion;
1768 Region dirtyRegion;
1769 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001770 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001771 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1772 const Transform& tr(displayDevice->getTransform());
1773 const Rect bounds(displayDevice->getBounds());
1774 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001775 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001776
Jeff Sharkey76488112017-02-27 14:15:18 -07001777 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001778 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001779 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1780 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 Region drawRegion(tr.transform(
1782 layer->visibleNonTransparentRegion));
1783 drawRegion.andSelf(bounds);
1784 if (!drawRegion.isEmpty()) {
1785 layersSortedByZ.add(layer);
1786 } else {
1787 // Clear out the HWC layer if this layer was
1788 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001789 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001790 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001791 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001792 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001793 // WM changes displayDevice->layerStack upon sleep/awake.
1794 // Here we make sure we delete the HWC layers even if
1795 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001796 hwcLayerDestroyed = layer->destroyHwcLayer(
1797 displayDevice->getHwcDisplayId());
1798 }
1799
1800 // If a layer is not going to get a release fence because
1801 // it is invisible, but it is also going to release its
1802 // old buffer, add it to the list of layers needing
1803 // fences.
1804 if (hwcLayerDestroyed) {
1805 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1806 mLayersWithQueuedFrames.cend(), layer);
1807 if (found != mLayersWithQueuedFrames.cend()) {
1808 layersNeedingFences.add(layer);
1809 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001810 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 });
1812 }
1813 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001814 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 displayDevice->undefinedRegion.set(bounds);
1816 displayDevice->undefinedRegion.subtractSelf(
1817 tr.transform(opaqueRegion));
1818 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001822
Romain Guy0147a172017-06-01 13:53:56 -07001823mat4 SurfaceFlinger::computeSaturationMatrix() const {
1824 if (mSaturation == 1.0f) {
1825 return mat4();
1826 }
1827
1828 // Rec.709 luma coefficients
1829 float3 luminance{0.213f, 0.715f, 0.072f};
1830 luminance *= 1.0f - mSaturation;
1831 return mat4(
1832 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1833 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1834 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1835 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1836 );
1837}
1838
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001839// pickColorMode translates a given dataspace into the best available color mode.
1840// Currently only support sRGB and Display-P3.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001841ColorMode SurfaceFlinger::pickColorMode(Dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001842 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001843 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001844 }
1845
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001846 switch (dataSpace) {
1847 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1848 // system expects.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001849 case Dataspace::UNKNOWN:
1850 case Dataspace::SRGB:
1851 case Dataspace::V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001852 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001853 break;
1854
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001855 case Dataspace::DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001856 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001857 break;
1858
1859 default:
1860 // TODO (courtneygo): Do we want to assert an error here?
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001861 ALOGE("No color mode mapping for %s (%#x)",
1862 dataspaceDetails(static_cast<android_dataspace>(dataSpace)).c_str(),
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001863 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001864 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001865 break;
1866 }
1867}
1868
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001869Dataspace SurfaceFlinger::bestTargetDataSpace(
1870 Dataspace a, Dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001871 // Only support sRGB and Display-P3 right now.
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001872 if (a == Dataspace::DISPLAY_P3 || b == Dataspace::DISPLAY_P3) {
1873 return Dataspace::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001874 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001875 if (a == Dataspace::V0_SCRGB_LINEAR || b == Dataspace::V0_SCRGB_LINEAR) {
1876 return Dataspace::DISPLAY_P3;
Romain Guy88d37dd2017-05-26 17:57:05 -07001877 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001878 if (a == Dataspace::V0_SCRGB || b == Dataspace::V0_SCRGB) {
1879 return Dataspace::DISPLAY_P3;
Romain Guy88d37dd2017-05-26 17:57:05 -07001880 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001881 if (!hasHdr) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001882 if (a == Dataspace::BT2020_PQ || b == Dataspace::BT2020_PQ) {
1883 return Dataspace::DISPLAY_P3;
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001884 }
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001885 if (a == Dataspace::BT2020_ITU_PQ || b == Dataspace::BT2020_ITU_PQ) {
1886 return Dataspace::DISPLAY_P3;
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001887 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001888 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001889
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001890 return Dataspace::V0_SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001891}
1892
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 ATRACE_CALL();
1895 ALOGV("setUpHWComposer");
1896
Jesse Hall028dc8f2013-08-20 16:35:32 -07001897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001898 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1899 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1900 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1901
1902 // If nothing has changed (!dirty), don't recompose.
1903 // If something changed, but we don't currently have any visible layers,
1904 // and didn't when we last did a composition, then skip it this time.
1905 // The second rule does two things:
1906 // - When all layers are removed from a display, we'll emit one black
1907 // frame, then nothing more until we get new layers.
1908 // - When a display is created with a private layer stack, we won't
1909 // emit any black frames until a layer is added to the layer stack.
1910 bool mustRecompose = dirty && !(empty && wasEmpty);
1911
1912 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1913 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1914 mustRecompose ? "doing" : "skipping",
1915 dirty ? "+" : "-",
1916 empty ? "+" : "-",
1917 wasEmpty ? "+" : "-");
1918
Dan Stoza71433162014-02-04 16:22:36 -08001919 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001920
1921 if (mustRecompose) {
1922 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1923 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001924 }
1925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 // build the h/w work list
1927 if (CC_UNLIKELY(mGeometryInvalid)) {
1928 mGeometryInvalid = false;
1929 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1930 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1931 const auto hwcId = displayDevice->getHwcDisplayId();
1932 if (hwcId >= 0) {
1933 const Vector<sp<Layer>>& currentLayers(
1934 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001935 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001938 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001941 }
1942 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001943
Robert Carrae060832016-11-28 10:51:00 -08001944 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001945 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001947 }
1948 }
1949 }
1950 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 }
Riley Andrews03414a12014-07-01 14:22:59 -07001952
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001953
Romain Guy0147a172017-06-01 13:53:56 -07001954 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 // Set the per-frame data
1957 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1958 auto& displayDevice = mDisplays[displayId];
1959 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001960
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 if (hwcId < 0) {
1962 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001963 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001964 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08001965 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07001966 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001967 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1968 "display %zd: %d", displayId, result);
1969 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001971 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1972 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001973 !displayDevice->getHdrSupport()) {
1974 layer->forceClientComposition(hwcId);
1975 }
1976
chaviwc9232ed2017-11-14 15:31:15 -08001977 if (layer->getForceClientComposition(hwcId)) {
1978 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1979 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1980 continue;
1981 }
1982
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 layer->setPerFrameData(displayDevice);
1984 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001985
1986 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001987 ColorMode newColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001988 Dataspace newDataSpace = Dataspace::V0_SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001989
1990 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001991 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1992 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001993 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
Peiyong Lin34beb7a2018-03-28 11:57:12 -07001994 layer->getName().string(), dataspaceDetails(static_cast<android_dataspace>(layer->getDataSpace())).c_str(),
1995 layer->getDataSpace(), dataspaceDetails(static_cast<android_dataspace>(newDataSpace)).c_str(), newDataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001996 }
1997 newColorMode = pickColorMode(newDataSpace);
1998
Thierry Strudel2924d012017-08-14 15:19:37 -07001999 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002000 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 }
2002
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002003 mPreviousColorMatrix = colorMatrix;
2004
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002006 auto& displayDevice = mDisplays[displayId];
2007 if (!displayDevice->isDisplayOn()) {
2008 continue;
2009 }
2010
David Sodman105b7dc2017-11-04 20:28:14 -07002011 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2013 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002014 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002016
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017void SurfaceFlinger::doComposition() {
2018 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 ALOGV("doComposition");
2020
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002021 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002022 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002023 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002024 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 // transform the dirty region into this screen's coordinate space
2026 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002027
2028 // repaint the framebuffer (if needed)
2029 doDisplayComposition(hw, dirtyRegion);
2030
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002032 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002033 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002034 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002035 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002036}
2037
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038void SurfaceFlinger::postFramebuffer()
2039{
Mathias Agopian841cde52012-03-01 15:44:37 -08002040 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002042
Mathias Agopiana44b0412011-10-16 18:46:35 -07002043 const nsecs_t now = systemTime();
2044 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002045
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2047 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002048 if (!displayDevice->isDisplayOn()) {
2049 continue;
2050 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 const auto hwcId = displayDevice->getHwcDisplayId();
2052 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002053 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002054 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002055 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002056 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002058 // The layer buffer from the previous frame (if any) is released
2059 // by HWC only when the release fence from this frame (if any) is
2060 // signaled. Always get the release fence from HWC first.
2061 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002062 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002063
2064 // If the layer was client composited in the previous frame, we
2065 // need to merge with the previous client target acquire fence.
2066 // Since we do not track that, always merge with the current
2067 // client target acquire fence when it is available, even though
2068 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002070 releaseFence = Fence::merge("LayerRelease", releaseFence,
2071 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002072 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002073
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 layer->onLayerDisplayed(releaseFence);
2075 }
Chia-I Wu83806892017-11-16 10:50:20 -08002076
2077 // We've got a list of layers needing fences, that are disjoint with
2078 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2079 // supply them with the present fence.
2080 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002081 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002082 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2083 layer->onLayerDisplayed(presentFence);
2084 }
2085 }
2086
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002088 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002089 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002090 }
2091
Mathias Agopiana44b0412011-10-16 18:46:35 -07002092 mLastSwapBufferTime = systemTime() - now;
2093 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002094
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002095 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002096 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2097 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2098 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2099 logFrameStats();
2100 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102}
2103
Mathias Agopian87baae12012-07-31 12:38:26 -07002104void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105{
Mathias Agopian841cde52012-03-01 15:44:37 -08002106 ATRACE_CALL();
2107
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002108 // here we keep a copy of the drawing state (that is the state that's
2109 // going to be overwritten by handleTransactionLocked()) outside of
2110 // mStateLock so that the side-effects of the State assignment
2111 // don't happen with mStateLock held (which can cause deadlocks).
2112 State drawingState(mDrawingState);
2113
Mathias Agopianca4d3602011-05-19 15:38:14 -07002114 Mutex::Autolock _l(mStateLock);
2115 const nsecs_t now = systemTime();
2116 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117
Mathias Agopianca4d3602011-05-19 15:38:14 -07002118 // Here we're guaranteed that some transaction flags are set
2119 // so we can call handleTransactionLocked() unconditionally.
2120 // We call getTransactionFlags(), which will also clear the flags,
2121 // with mStateLock held to guarantee that mCurrentState won't change
2122 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002123
Mathias Agopiane57f2922012-08-09 16:29:12 -07002124 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002126
Mathias Agopianca4d3602011-05-19 15:38:14 -07002127 mLastTransactionTime = systemTime() - now;
2128 mDebugInTransaction = 0;
2129 invalidateHwcGeometry();
2130 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002131}
2132
Lloyd Pique715a2c12017-12-14 17:18:08 -08002133DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002134 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002135 // Figure out whether the event is for the primary display or an
2136 // external display by matching the Hwc display id against one for a
2137 // connected display. If we did not find a match, we then check what
2138 // displays are not already connected to determine the type. If we don't
2139 // have a connected primary display, we assume the new display is meant to
2140 // be the primary display, and then if we don't have an external display,
2141 // we assume it is that.
2142 const auto primaryDisplayId =
2143 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2144 const auto externalDisplayId =
2145 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2146 if (primaryDisplayId && primaryDisplayId == display) {
2147 return DisplayDevice::DISPLAY_PRIMARY;
2148 } else if (externalDisplayId && externalDisplayId == display) {
2149 return DisplayDevice::DISPLAY_EXTERNAL;
2150 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2151 return DisplayDevice::DISPLAY_PRIMARY;
2152 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2153 return DisplayDevice::DISPLAY_EXTERNAL;
2154 }
2155
2156 return DisplayDevice::DISPLAY_ID_INVALID;
2157}
2158
Lloyd Piqueba04e622017-12-14 17:11:26 -08002159void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2160 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002161 auto displayType = determineDisplayType(event.display, event.connection);
2162 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2163 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2164 continue;
2165 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002166
2167 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2168 ALOGE("External displays are not supported by the vr hardware composer.");
2169 continue;
2170 }
2171
Lloyd Pique715a2c12017-12-14 17:18:08 -08002172 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002173
2174 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002175 if (!mBuiltinDisplays[displayType].get()) {
2176 ALOGV("Creating built in display %d", displayType);
2177 mBuiltinDisplays[displayType] = new BBinder();
2178 // All non-virtual displays are currently considered secure.
2179 DisplayDeviceState info(displayType, true);
2180 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2181 "Built-in Screen" : "External Screen";
2182 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002183 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002184 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002185 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002186 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002187
Lloyd Piquefcd86612017-12-14 17:15:36 -08002188 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2189 if (idx >= 0) {
2190 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002191 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002192 mCurrentState.displays.removeItemsAt(idx);
2193 }
2194 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195 }
2196
2197 processDisplayChangesLocked();
2198 }
2199
2200 mPendingHotplugEvents.clear();
2201}
2202
Lloyd Pique09594832018-01-22 17:48:03 -08002203sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2204 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2205 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2206 bool hasWideColorSupport = false;
2207 if (hasWideColorDisplay) {
2208 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2209 for (ColorMode colorMode : modes) {
2210 switch (colorMode) {
2211 case ColorMode::DISPLAY_P3:
2212 case ColorMode::ADOBE_RGB:
2213 case ColorMode::DCI_P3:
2214 hasWideColorSupport = true;
2215 break;
2216 default:
2217 break;
2218 }
2219 }
2220 }
2221
2222 bool hasHdrSupport = false;
2223 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2224 getHwComposer().getHdrCapabilities(state.type);
2225 if (hdrCapabilities) {
2226 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2227 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2228 hasHdrSupport = iter != types.cend();
2229 }
2230
2231 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2232 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2233
2234 /*
2235 * Create our display's surface
2236 */
2237 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2238 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2239 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2240 renderSurface->setNativeWindow(nativeWindow.get());
2241 const int displayWidth = renderSurface->queryWidth();
2242 const int displayHeight = renderSurface->queryHeight();
2243
2244 // Make sure that composition can never be stalled by a virtual display
2245 // consumer that isn't processing buffers fast enough. We have to do this
2246 // in two places:
2247 // * Here, in case the display is composed entirely by HWC.
2248 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2249 // window's swap interval in eglMakeCurrent, so they'll override the
2250 // interval we set here.
2251 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2252 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2253 }
2254
2255 // virtual displays are always considered enabled
2256 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2257 : HWC_POWER_MODE_OFF;
2258
2259 sp<DisplayDevice> hw =
2260 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2261 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2262 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2263
2264 if (maxFrameBufferAcquiredBuffers >= 3) {
2265 nativeWindowSurface->preallocateBuffers();
2266 }
2267
2268 ColorMode defaultColorMode = ColorMode::NATIVE;
2269 if (hasWideColorSupport) {
2270 defaultColorMode = ColorMode::SRGB;
2271 }
2272 setActiveColorModeInternal(hw, defaultColorMode);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002273 hw->setCompositionDataSpace(Dataspace::UNKNOWN);
Lloyd Pique09594832018-01-22 17:48:03 -08002274 hw->setLayerStack(state.layerStack);
2275 hw->setProjection(state.orientation, state.viewport, state.frame);
2276 hw->setDisplayName(state.displayName);
2277
2278 return hw;
2279}
2280
Lloyd Pique347200f2017-12-14 17:00:15 -08002281void SurfaceFlinger::processDisplayChangesLocked() {
2282 // here we take advantage of Vector's copy-on-write semantics to
2283 // improve performance by skipping the transaction entirely when
2284 // know that the lists are identical
2285 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2286 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2287 if (!curr.isIdenticalTo(draw)) {
2288 mVisibleRegionsDirty = true;
2289 const size_t cc = curr.size();
2290 size_t dc = draw.size();
2291
2292 // find the displays that were removed
2293 // (ie: in drawing state but not in current state)
2294 // also handle displays that changed
2295 // (ie: displays that are in both lists)
2296 for (size_t i = 0; i < dc;) {
2297 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2298 if (j < 0) {
2299 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002300 // Call makeCurrent() on the primary display so we can
2301 // be sure that nothing associated with this display
2302 // is current.
2303 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2304 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2305 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2306 if (hw != nullptr) hw->disconnect(getHwComposer());
2307 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2308 mEventThread->onHotplugReceived(draw[i].type, false);
2309 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002310 } else {
2311 // this display is in both lists. see if something changed.
2312 const DisplayDeviceState& state(curr[j]);
2313 const wp<IBinder>& display(curr.keyAt(j));
2314 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2315 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2316 if (state_binder != draw_binder) {
2317 // changing the surface is like destroying and
2318 // recreating the DisplayDevice, so we just remove it
2319 // from the drawing state, so that it get re-added
2320 // below.
2321 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2322 if (hw != nullptr) hw->disconnect(getHwComposer());
2323 mDisplays.removeItem(display);
2324 mDrawingState.displays.removeItemsAt(i);
2325 dc--;
2326 // at this point we must loop to the next item
2327 continue;
2328 }
2329
2330 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2331 if (disp != nullptr) {
2332 if (state.layerStack != draw[i].layerStack) {
2333 disp->setLayerStack(state.layerStack);
2334 }
2335 if ((state.orientation != draw[i].orientation) ||
2336 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2337 disp->setProjection(state.orientation, state.viewport, state.frame);
2338 }
2339 if (state.width != draw[i].width || state.height != draw[i].height) {
2340 disp->setDisplaySize(state.width, state.height);
2341 }
2342 }
2343 }
2344 ++i;
2345 }
2346
2347 // find displays that were added
2348 // (ie: in current state but not in drawing state)
2349 for (size_t i = 0; i < cc; i++) {
2350 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2351 const DisplayDeviceState& state(curr[i]);
2352
2353 sp<DisplaySurface> dispSurface;
2354 sp<IGraphicBufferProducer> producer;
2355 sp<IGraphicBufferProducer> bqProducer;
2356 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002357 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002358
2359 int32_t hwcId = -1;
2360 if (state.isVirtualDisplay()) {
2361 // Virtual displays without a surface are dormant:
2362 // they have external state (layer stack, projection,
2363 // etc.) but no internal state (i.e. a DisplayDevice).
2364 if (state.surface != nullptr) {
2365 // Allow VR composer to use virtual displays.
2366 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2367 int width = 0;
2368 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2369 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2370 int height = 0;
2371 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2372 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2373 int intFormat = 0;
2374 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2375 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002376 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002377
2378 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2379 }
2380
2381 // TODO: Plumb requested format back up to consumer
2382
2383 sp<VirtualDisplaySurface> vds =
2384 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2385 bqProducer, bqConsumer,
2386 state.displayName);
2387
2388 dispSurface = vds;
2389 producer = vds;
2390 }
2391 } else {
2392 ALOGE_IF(state.surface != nullptr,
2393 "adding a supported display, but rendering "
2394 "surface is provided (%p), ignoring it",
2395 state.surface.get());
2396
2397 hwcId = state.type;
2398 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2399 producer = bqProducer;
2400 }
2401
2402 const wp<IBinder>& display(curr.keyAt(i));
2403 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002404 mDisplays.add(display,
2405 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2406 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002407 if (!state.isVirtualDisplay()) {
2408 mEventThread->onHotplugReceived(state.type, true);
2409 }
2410 }
2411 }
2412 }
2413 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002414
2415 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002416}
2417
Mathias Agopian87baae12012-07-31 12:38:26 -07002418void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002419{
Dan Stoza7dde5992015-05-22 09:51:44 -07002420 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002421 mCurrentState.traverseInZOrder([](Layer* layer) {
2422 layer->notifyAvailableFrames();
2423 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425 /*
2426 * Traversal of the children
2427 * (perform the transaction for each of them if needed)
2428 */
2429
Mathias Agopian3559b072012-08-15 13:46:03 -07002430 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002431 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002433 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434
2435 const uint32_t flags = layer->doTransaction(0);
2436 if (flags & Layer::eVisibleRegion)
2437 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002438 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 }
2440
2441 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002442 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 */
2444
Mathias Agopiane57f2922012-08-09 16:29:12 -07002445 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002446 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002447 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002450 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002451 // The transform hint might have changed for some layers
2452 // (either because a display has changed, or because a layer
2453 // as changed).
2454 //
2455 // Walk through all the layers in currentLayers,
2456 // and update their transform hint.
2457 //
2458 // If a layer is visible only on a single display, then that
2459 // display is used to calculate the hint, otherwise we use the
2460 // default display.
2461 //
2462 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2463 // the hint is set before we acquire a buffer from the surface texture.
2464 //
2465 // NOTE: layer transactions have taken place already, so we use their
2466 // drawing state. However, SurfaceFlinger's own transaction has not
2467 // happened yet, so we must use the current state layer list
2468 // (soon to become the drawing state list).
2469 //
2470 sp<const DisplayDevice> disp;
2471 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002472 bool first = true;
2473 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002474 // NOTE: we rely on the fact that layers are sorted by
2475 // layerStack first (so we don't have to traverse the list
2476 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002477 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002478 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002479 currentlayerStack = layerStack;
2480 // figure out if this layerstack is mirrored
2481 // (more than one display) if so, pick the default display,
2482 // if not, pick the only display it's on.
2483 disp.clear();
2484 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2485 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002486 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002487 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002488 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002489 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002490 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002491 break;
2492 }
2493 }
2494 }
2495 }
Chet Haase91d25932013-04-11 15:24:55 -07002496
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002497 if (disp == nullptr) {
2498 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2499 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002500
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002501 // could be null when this layer is using a layerStack
2502 // that is not visible on any display. Also can occur at
2503 // screen off/on times.
2504 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002505 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002506
2507 // disp can be null if there is no display available at all to get
2508 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002509 if (disp != nullptr) {
2510 layer->updateTransformHint(disp);
2511 }
Robert Carr2047fae2016-11-28 14:09:09 -08002512
2513 first = false;
2514 });
Mathias Agopian84300952012-11-21 16:02:13 -08002515 }
2516
2517
Mathias Agopian3559b072012-08-15 13:46:03 -07002518 /*
2519 * Perform our own transaction if needed
2520 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002521
2522 if (mLayersAdded) {
2523 mLayersAdded = false;
2524 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002525 mVisibleRegionsDirty = true;
2526 }
2527
2528 // some layers might have been removed, so
2529 // we need to update the regions they're exposing.
2530 if (mLayersRemoved) {
2531 mLayersRemoved = false;
2532 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002533 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002534 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002535 // this layer is not visible anymore
2536 // TODO: we could traverse the tree from front to back and
2537 // compute the actual visible region
2538 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539 Region visibleReg;
2540 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002541 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002542 }
Robert Carr2047fae2016-11-28 14:09:09 -08002543 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 }
2545
2546 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002547
2548 updateCursorAsync();
2549}
2550
2551void SurfaceFlinger::updateCursorAsync()
2552{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002553 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2554 auto& displayDevice = mDisplays[displayId];
2555 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002556 continue;
2557 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558
2559 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2560 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002561 }
2562 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563}
2564
2565void SurfaceFlinger::commitTransaction()
2566{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002567 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002568 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002569 for (const auto& l : mLayersPendingRemoval) {
2570 recordBufferingStats(l->getName().string(),
2571 l->getOccupancyHistory(true));
2572 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002573 }
2574 mLayersPendingRemoval.clear();
2575 }
2576
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002577 // If this transaction is part of a window animation then the next frame
2578 // we composite should be considered an animation as well.
2579 mAnimCompositionPending = mAnimTransactionPending;
2580
Mathias Agopian4fec8732012-06-29 14:12:52 -07002581 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002582 mDrawingState.traverseInZOrder([](Layer* layer) {
2583 layer->commitChildList();
2584 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002585 mTransactionPending = false;
2586 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002587 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588}
2589
Chia-I Wuab0c3192017-08-01 11:29:00 -07002590void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002591 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592{
Mathias Agopian841cde52012-03-01 15:44:37 -08002593 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002594 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002595
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 Region aboveOpaqueLayers;
2597 Region aboveCoveredLayers;
2598 Region dirty;
2599
Mathias Agopian87baae12012-07-31 12:38:26 -07002600 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601
Robert Carr2047fae2016-11-28 14:09:09 -08002602 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002604 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605
Jesse Hall01e29052013-02-19 16:13:35 -08002606 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002607 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002608 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002609
Mathias Agopianab028732010-03-16 16:41:46 -07002610 /*
2611 * opaqueRegion: area of a surface that is fully opaque.
2612 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002614
2615 /*
2616 * visibleRegion: area of a surface that is visible on screen
2617 * and not fully transparent. This is essentially the layer's
2618 * footprint minus the opaque regions above it.
2619 * Areas covered by a translucent surface are considered visible.
2620 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002622
2623 /*
2624 * coveredRegion: area of a surface that is covered by all
2625 * visible regions above it (which includes the translucent areas).
2626 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002628
Jesse Halla8026d22012-09-25 13:25:04 -07002629 /*
2630 * transparentRegion: area of a surface that is hinted to be completely
2631 * transparent. This is only used to tell when the layer has no visible
2632 * non-transparent regions and can be removed from the layer list. It
2633 * does not affect the visibleRegion of this layer or any layers
2634 * beneath it. The hint may not be correct if apps don't respect the
2635 * SurfaceView restrictions (which, sadly, some don't).
2636 */
2637 Region transparentRegion;
2638
Mathias Agopianab028732010-03-16 16:41:46 -07002639
2640 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002641 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002642 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002646 if (!visibleRegion.isEmpty()) {
2647 // Remove the transparent area from the visible region
2648 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002649 if (tr.preserveRects()) {
2650 // transform the transparent region
2651 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002653 // transformation too complex, can't do the
2654 // transparent region optimization.
2655 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002656 }
Mathias Agopianab028732010-03-16 16:41:46 -07002657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658
Mathias Agopianab028732010-03-16 16:41:46 -07002659 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002661 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002662 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2663 // the opaque region is the layer's footprint
2664 opaqueRegion = visibleRegion;
2665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 }
2667 }
2668
Robert Carre5f4f692018-01-12 13:12:28 -08002669 if (visibleRegion.isEmpty()) {
2670 layer->clearVisibilityRegions();
2671 return;
2672 }
2673
Mathias Agopianab028732010-03-16 16:41:46 -07002674 // Clip the covered region to the visible region
2675 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2676
2677 // Update aboveCoveredLayers for next (lower) layer
2678 aboveCoveredLayers.orSelf(visibleRegion);
2679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 // subtract the opaque region covered by the layers above us
2681 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
2683 // compute this layer's dirty region
2684 if (layer->contentDirty) {
2685 // we need to invalidate the whole region
2686 dirty = visibleRegion;
2687 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 layer->contentDirty = false;
2690 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002691 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002692 * the exposed region consists of two components:
2693 * 1) what's VISIBLE now and was COVERED before
2694 * 2) what's EXPOSED now less what was EXPOSED before
2695 *
2696 * note that (1) is conservative, we start with the whole
2697 * visible region but only keep what used to be covered by
2698 * something -- which mean it may have been exposed.
2699 *
2700 * (2) handles areas that were not covered by anything but got
2701 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002702 */
Mathias Agopianab028732010-03-16 16:41:46 -07002703 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002704 const Region oldVisibleRegion = layer->visibleRegion;
2705 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002706 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2707 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 }
2709 dirty.subtractSelf(aboveOpaqueLayers);
2710
2711 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002712 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713
Mathias Agopianab028732010-03-16 16:41:46 -07002714 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002716
Jesse Halla8026d22012-09-25 13:25:04 -07002717 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 layer->setVisibleRegion(visibleRegion);
2719 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002720 layer->setVisibleNonTransparentRegion(
2721 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002722 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Mathias Agopian87baae12012-07-31 12:38:26 -07002724 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
Chia-I Wuab0c3192017-08-01 11:29:00 -07002727void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002728 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002729 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002730 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002731 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002732 }
2733 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002734}
2735
Dan Stoza6b9454d2014-11-07 16:00:59 -08002736bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002738 ALOGV("handlePageFlip");
2739
Brian Andersond6927fb2016-07-23 23:37:30 -07002740 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741
Mathias Agopian4fec8732012-06-29 14:12:52 -07002742 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002743 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002744 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002745
2746 // Store the set of layers that need updates. This set must not change as
2747 // buffers are being latched, as this could result in a deadlock.
2748 // Example: Two producers share the same command stream and:
2749 // 1.) Layer 0 is latched
2750 // 2.) Layer 0 gets a new frame
2751 // 2.) Layer 1 gets a new frame
2752 // 3.) Layer 1 is latched.
2753 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2754 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002755 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002756 if (layer->hasQueuedFrame()) {
2757 frameQueued = true;
2758 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002759 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002760 } else {
2761 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002762 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002763 } else {
2764 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002765 }
Robert Carr2047fae2016-11-28 14:09:09 -08002766 });
2767
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002769 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002770 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002771 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002772 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002773 newDataLatched = true;
2774 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002776
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002777 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002778
2779 // If we will need to wake up at some time in the future to deal with a
2780 // queued frame that shouldn't be displayed during this vsync period, wake
2781 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002782 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002783 signalLayerUpdate();
2784 }
2785
2786 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002787 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788}
2789
Mathias Agopianad456f92011-01-13 17:53:01 -08002790void SurfaceFlinger::invalidateHwcGeometry()
2791{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002793}
2794
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002795
Fabien Sanglard830b8472016-11-30 16:35:58 -08002796void SurfaceFlinger::doDisplayComposition(
2797 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002798 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799{
Dan Stoza71433162014-02-04 16:22:36 -08002800 // We only need to actually compose the display if:
2801 // 1) It is being handled by hardware composer, which may need this to
2802 // keep its virtual display state machine in sync, or
2803 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002804 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002805 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002807 return;
2808 }
2809
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002811 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002812
2813 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002814 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815}
2816
Chia-I Wub02087d2017-11-09 10:19:54 -08002817bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002818{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002820
Chia-I Wub02087d2017-11-09 10:19:54 -08002821 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002822 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002824
2825 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002826 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2827 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002828 if (applyColorMatrix) {
2829 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2830 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2831 }
2832
David Sodman105b7dc2017-11-04 20:28:14 -07002833 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 if (hasClientComposition) {
2835 ALOGV("hasClientComposition");
2836
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002837 Dataspace outputDataspace = Dataspace::UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002838 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002839 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002840 outputDataspace = Dataspace::DISPLAY_P3;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002841 }
2842 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2843
Chia-I Wu7f402902017-11-09 12:51:10 -08002844 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002845 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002847 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002848
2849 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002850 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002851 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2852 }
2853 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002854 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002855
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002856 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002857 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002859 // when using overlays, we assume a fully transparent framebuffer
2860 // NOTE: we could reduce how much we need to clear, for instance
2861 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002862 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002863 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002864 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002865 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002866 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002867 // we're left with the letterbox region
2868 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002870
2871 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002872 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002873
Mathias Agopianb9494d52012-04-18 02:28:45 -07002874 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002875 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002876 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002878 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002879 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002880
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002882 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002883 // scissor on the main display. It should never be needed
2884 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 const Rect& bounds(displayDevice->getBounds());
2886 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002887 if (scissor != bounds) {
2888 // scissor doesn't match the screen's dimensions, so we
2889 // need to clear everything outside of it and enable
2890 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002891
Mathias Agopianf45c5102012-10-24 16:29:17 -07002892 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002894 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002895 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002896 }
2897 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002898 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002899
Mathias Agopian85d751c2012-08-29 16:59:24 -07002900 /*
2901 * and then, render the layers targeted at the framebuffer
2902 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002903
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904 ALOGV("Rendering client layers");
2905 const Transform& displayTransform = displayDevice->getTransform();
2906 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002907 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 bool firstLayer = true;
2909 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002910 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 displayTransform.transform(layer->visibleRegion)));
2912 ALOGV("Layer: %s", layer->getName().string());
2913 ALOGV(" Composition type: %s",
2914 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002915 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 switch (layer->getCompositionType(hwcId)) {
2917 case HWC2::Composition::Cursor:
2918 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002919 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002921 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002923 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002924 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002925 // never clear the very first layer since we're
2926 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002927 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002928 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002929 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002930 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002932 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002933 break;
2934 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002936 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 } else {
2939 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002940 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002942 }
2943 } else {
2944 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002946 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002948 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002949 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002950 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002951 }
2952 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002953
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002954 if (applyColorMatrix) {
2955 getRenderEngine().setupColorTransform(oldColorMatrix);
2956 }
2957
Mathias Agopianf45c5102012-10-24 16:29:17 -07002958 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002959 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002960 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961}
2962
Fabien Sanglard830b8472016-11-30 16:35:58 -08002963void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2964 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002965 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002966 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967}
2968
Dan Stoza7d89d062015-04-30 13:29:25 -07002969status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002970 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002971 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002972 const sp<Layer>& lbc,
2973 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002974{
Dan Stoza7d89d062015-04-30 13:29:25 -07002975 // add this layer to the current state list
2976 {
2977 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002979 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2980 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002981 return NO_MEMORY;
2982 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002983 if (parent == nullptr) {
2984 mCurrentState.layersSortedByZ.add(lbc);
2985 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002986 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002987 ALOGE("addClientLayer called with a removed parent");
2988 return NAME_NOT_FOUND;
2989 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002990 parent->addChild(lbc);
2991 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002992
Dan Stoza101d8dc2018-02-27 15:42:25 -08002993 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002994 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2995 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2996 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2997 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2998 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002999 mLayersAdded = true;
3000 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003001 }
3002
Mathias Agopian96f08192010-06-02 23:28:45 -07003003 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003004 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003005
Dan Stoza7d89d062015-04-30 13:29:25 -07003006 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003007}
3008
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003009status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003010 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003011 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3012}
Robert Carr7f9b8992017-03-10 11:08:39 -08003013
chaviwca27f252018-02-06 16:46:39 -08003014status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3015 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003016 if (layer->isPendingRemoval()) {
3017 return NO_ERROR;
3018 }
3019
Robert Carr1f0a16a2016-10-24 16:27:39 -07003020 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003021 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003022 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003023 if (topLevelOnly) {
3024 return NO_ERROR;
3025 }
3026
Chia-I Wu98f1c102017-05-30 14:54:08 -07003027 sp<Layer> ancestor = p;
3028 while (ancestor->getParent() != nullptr) {
3029 ancestor = ancestor->getParent();
3030 }
3031 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3032 ALOGE("removeLayer called with a layer whose parent has been removed");
3033 return NAME_NOT_FOUND;
3034 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003035
3036 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003037 } else {
3038 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003039 }
3040
Robert Carr136e2f62017-02-08 17:54:29 -08003041 // As a matter of normal operation, the LayerCleaner will produce a second
3042 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3043 // so we will succeed in promoting it, but it's already been removed
3044 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3045 // otherwise something has gone wrong and we are leaking the layer.
3046 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003047 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3048 layer->getName().string(),
3049 (p != nullptr) ? p->getName().string() : "no-parent");
3050 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003051 } else if (index < 0) {
3052 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003053 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003054
Chia-I Wuc6657022017-08-15 11:18:17 -07003055 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003056 mLayersPendingRemoval.add(layer);
3057 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003058 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003059 setTransactionFlags(eTransactionNeeded);
3060 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061}
3062
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003063uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003064 return android_atomic_release_load(&mTransactionFlags);
3065}
3066
Mathias Agopian3f844832013-08-07 21:24:32 -07003067uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3069}
3070
Mathias Agopian3f844832013-08-07 21:24:32 -07003071uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3073 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003074 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 }
3076 return old;
3077}
3078
chaviwca27f252018-02-06 16:46:39 -08003079bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3080 for (const ComposerState& state : states) {
3081 // Here we need to check that the interface we're given is indeed
3082 // one of our own. A malicious client could give us a nullptr
3083 // IInterface, or one of its own or even one of our own but a
3084 // different type. All these situations would cause us to crash.
3085 if (state.client == nullptr) {
3086 return true;
3087 }
3088
3089 sp<IBinder> binder = IInterface::asBinder(state.client);
3090 if (binder == nullptr) {
3091 return true;
3092 }
3093
3094 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3095 return true;
3096 }
3097 }
3098 return false;
3099}
3100
Mathias Agopian8b33f032012-07-24 20:43:54 -07003101void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003102 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003103 const Vector<DisplayState>& displays,
3104 uint32_t flags)
3105{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003106 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003107 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003108 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003109
chaviwca27f252018-02-06 16:46:39 -08003110 if (containsAnyInvalidClientState(states)) {
3111 return;
3112 }
3113
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003114 if (flags & eAnimation) {
3115 // For window updates that are part of an animation we must wait for
3116 // previous animation "frames" to be handled.
3117 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003118 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003119 if (CC_UNLIKELY(err != NO_ERROR)) {
3120 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003121 // caller after a few seconds.
3122 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3123 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003124 mAnimTransactionPending = false;
3125 break;
3126 }
3127 }
3128 }
3129
chaviwca27f252018-02-06 16:46:39 -08003130 for (const DisplayState& display : displays) {
3131 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003132 }
3133
chaviwca27f252018-02-06 16:46:39 -08003134 for (const ComposerState& state : states) {
3135 transactionFlags |= setClientStateLocked(state);
3136 }
3137
3138 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3139 // as destroyed should only occur after setting all other states. This is to allow for a
3140 // child re-parent to happen before marking its original parent as destroyed (which would
3141 // then mark the child as destroyed).
3142 for (const ComposerState& state : states) {
3143 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003144 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003145
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003146 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3147 // anyway. This can be used as a flush mechanism for previous async transactions.
3148 // Empty animation transaction can be used to simulate back-pressure, so also force a
3149 // transaction for empty animation transactions.
3150 if (transactionFlags == 0 &&
3151 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003152 transactionFlags = eTransactionNeeded;
3153 }
3154
Mathias Agopian386aa982011-11-07 21:58:03 -08003155 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003156 if (mInterceptor->isEnabled()) {
3157 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003158 }
Irvel468051e2016-06-13 16:44:44 -07003159
Mathias Agopian386aa982011-11-07 21:58:03 -08003160 // this triggers the transaction
3161 setTransactionFlags(transactionFlags);
3162
3163 // if this is a synchronous transaction, wait for it to take effect
3164 // before returning.
3165 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003166 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003167 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003168 if (flags & eAnimation) {
3169 mAnimTransactionPending = true;
3170 }
3171 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003172 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3173 if (CC_UNLIKELY(err != NO_ERROR)) {
3174 // just in case something goes wrong in SF, return to the
3175 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003176 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3177 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003178 break;
3179 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181 }
3182}
3183
Mathias Agopiane57f2922012-08-09 16:29:12 -07003184uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3185{
Jesse Hall9a143922012-10-04 16:29:19 -07003186 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3187 if (dpyIdx < 0)
3188 return 0;
3189
Mathias Agopiane57f2922012-08-09 16:29:12 -07003190 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003191 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003192 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003193 const uint32_t what = s.what;
3194 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003195 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003196 disp.surface = s.surface;
3197 flags |= eDisplayTransactionNeeded;
3198 }
3199 }
3200 if (what & DisplayState::eLayerStackChanged) {
3201 if (disp.layerStack != s.layerStack) {
3202 disp.layerStack = s.layerStack;
3203 flags |= eDisplayTransactionNeeded;
3204 }
3205 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003206 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003207 if (disp.orientation != s.orientation) {
3208 disp.orientation = s.orientation;
3209 flags |= eDisplayTransactionNeeded;
3210 }
3211 if (disp.frame != s.frame) {
3212 disp.frame = s.frame;
3213 flags |= eDisplayTransactionNeeded;
3214 }
3215 if (disp.viewport != s.viewport) {
3216 disp.viewport = s.viewport;
3217 flags |= eDisplayTransactionNeeded;
3218 }
3219 }
Michael Lentine47e45402014-07-18 15:34:25 -07003220 if (what & DisplayState::eDisplaySizeChanged) {
3221 if (disp.width != s.width) {
3222 disp.width = s.width;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (disp.height != s.height) {
3226 disp.height = s.height;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003230 }
3231 return flags;
3232}
3233
chaviwca27f252018-02-06 16:46:39 -08003234uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3235 const layer_state_t& s = composerState.state;
3236 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3237
Mathias Agopian13127d82013-03-05 17:47:11 -08003238 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003239 if (layer == nullptr) {
3240 return 0;
3241 }
3242
3243 if (layer->isPendingRemoval()) {
3244 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3245 return 0;
3246 }
3247
3248 uint32_t flags = 0;
3249
3250 const uint32_t what = s.what;
3251 bool geometryAppliesWithResize =
3252 what & layer_state_t::eGeometryAppliesWithResize;
3253 if (what & layer_state_t::ePositionChanged) {
3254 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3255 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003256 }
chaviw8b3871a2017-11-01 17:41:01 -07003257 }
3258 if (what & layer_state_t::eLayerChanged) {
3259 // NOTE: index needs to be calculated before we update the state
3260 const auto& p = layer->getParent();
3261 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003262 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003263 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003264 mCurrentState.layersSortedByZ.removeAt(idx);
3265 mCurrentState.layersSortedByZ.add(layer);
3266 // we need traversal (state changed)
3267 // AND transaction (list changed)
3268 flags |= eTransactionNeeded|eTraversalNeeded;
3269 }
chaviw8b3871a2017-11-01 17:41:01 -07003270 } else {
3271 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003272 flags |= eTransactionNeeded|eTraversalNeeded;
3273 }
3274 }
chaviw8b3871a2017-11-01 17:41:01 -07003275 }
3276 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003277 // NOTE: index needs to be calculated before we update the state
3278 const auto& p = layer->getParent();
3279 if (p == nullptr) {
3280 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3281 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3282 mCurrentState.layersSortedByZ.removeAt(idx);
3283 mCurrentState.layersSortedByZ.add(layer);
3284 // we need traversal (state changed)
3285 // AND transaction (list changed)
3286 flags |= eTransactionNeeded|eTraversalNeeded;
3287 }
3288 } else {
3289 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3290 flags |= eTransactionNeeded|eTraversalNeeded;
3291 }
chaviw8b3871a2017-11-01 17:41:01 -07003292 }
3293 }
3294 if (what & layer_state_t::eSizeChanged) {
3295 if (layer->setSize(s.w, s.h)) {
3296 flags |= eTraversalNeeded;
3297 }
3298 }
3299 if (what & layer_state_t::eAlphaChanged) {
3300 if (layer->setAlpha(s.alpha))
3301 flags |= eTraversalNeeded;
3302 }
3303 if (what & layer_state_t::eColorChanged) {
3304 if (layer->setColor(s.color))
3305 flags |= eTraversalNeeded;
3306 }
3307 if (what & layer_state_t::eMatrixChanged) {
3308 if (layer->setMatrix(s.matrix))
3309 flags |= eTraversalNeeded;
3310 }
3311 if (what & layer_state_t::eTransparentRegionChanged) {
3312 if (layer->setTransparentRegionHint(s.transparentRegion))
3313 flags |= eTraversalNeeded;
3314 }
3315 if (what & layer_state_t::eFlagsChanged) {
3316 if (layer->setFlags(s.flags, s.mask))
3317 flags |= eTraversalNeeded;
3318 }
3319 if (what & layer_state_t::eCropChanged) {
3320 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3321 flags |= eTraversalNeeded;
3322 }
3323 if (what & layer_state_t::eFinalCropChanged) {
3324 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3325 flags |= eTraversalNeeded;
3326 }
3327 if (what & layer_state_t::eLayerStackChanged) {
3328 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3329 // We only allow setting layer stacks for top level layers,
3330 // everything else inherits layer stack from its parent.
3331 if (layer->hasParent()) {
3332 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3333 layer->getName().string());
3334 } else if (idx < 0) {
3335 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3336 "that also does not appear in the top level layer list. Something"
3337 " has gone wrong.", layer->getName().string());
3338 } else if (layer->setLayerStack(s.layerStack)) {
3339 mCurrentState.layersSortedByZ.removeAt(idx);
3340 mCurrentState.layersSortedByZ.add(layer);
3341 // we need traversal (state changed)
3342 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003343 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003344 }
3345 }
3346 if (what & layer_state_t::eDeferTransaction) {
3347 if (s.barrierHandle != nullptr) {
3348 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3349 } else if (s.barrierGbp != nullptr) {
3350 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3351 if (authenticateSurfaceTextureLocked(gbp)) {
3352 const auto& otherLayer =
3353 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3354 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3355 } else {
3356 ALOGE("Attempt to defer transaction to to an"
3357 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003358 }
3359 }
chaviw8b3871a2017-11-01 17:41:01 -07003360 // We don't trigger a traversal here because if no other state is
3361 // changed, we don't want this to cause any more work
3362 }
3363 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003364 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003365 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003366 if (!hadParent) {
3367 mCurrentState.layersSortedByZ.remove(layer);
3368 }
chaviw8b3871a2017-11-01 17:41:01 -07003369 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003370 }
chaviw8b3871a2017-11-01 17:41:01 -07003371 }
3372 if (what & layer_state_t::eReparentChildren) {
3373 if (layer->reparentChildren(s.reparentHandle)) {
3374 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003375 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003376 }
chaviw8b3871a2017-11-01 17:41:01 -07003377 if (what & layer_state_t::eDetachChildren) {
3378 layer->detachChildren();
3379 }
3380 if (what & layer_state_t::eOverrideScalingModeChanged) {
3381 layer->setOverrideScalingMode(s.overrideScalingMode);
3382 // We don't trigger a traversal here because if no other state is
3383 // changed, we don't want this to cause any more work
3384 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003385 return flags;
3386}
3387
chaviwca27f252018-02-06 16:46:39 -08003388void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3389 const layer_state_t& state = composerState.state;
3390 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3391
3392 sp<Layer> layer(client->getLayerUser(state.surface));
3393 if (layer == nullptr) {
3394 return;
3395 }
3396
3397 if (layer->isPendingRemoval()) {
3398 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3399 return;
3400 }
3401
3402 if (state.what & layer_state_t::eDestroySurface) {
3403 removeLayerLocked(mStateLock, layer);
3404 }
3405}
3406
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003407status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003408 const String8& name,
3409 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003410 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003411 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003412 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003414 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003415 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003416 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003417 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003418 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003419
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003420 status_t result = NO_ERROR;
3421
3422 sp<Layer> layer;
3423
Cody Northropbc755282017-03-31 12:00:08 -06003424 String8 uniqueName = getUniqueLayerName(name);
3425
Mathias Agopian3165cc22012-08-08 19:42:09 -07003426 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3427 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003428 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003429 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003430 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003431
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003432 break;
chaviw13fdc492017-06-27 12:40:18 -07003433 case ISurfaceComposerClient::eFXSurfaceColor:
3434 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003435 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003436 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003437 break;
3438 default:
3439 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440 break;
3441 }
3442
Dan Stoza7d89d062015-04-30 13:29:25 -07003443 if (result != NO_ERROR) {
3444 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003445 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003446
Chia-I Wuab0c3192017-08-01 11:29:00 -07003447 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3448 // TODO b/64227542
3449 if (windowType == 441731) {
3450 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3451 layer->setPrimaryDisplayOnly();
3452 }
3453
Albert Chaulk479c60c2017-01-27 14:21:34 -05003454 layer->setInfo(windowType, ownerUid);
3455
Robert Carr1f0a16a2016-10-24 16:27:39 -07003456 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003457 if (result != NO_ERROR) {
3458 return result;
3459 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003460 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003461
3462 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003463 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464}
3465
Cody Northropbc755282017-03-31 12:00:08 -06003466String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3467{
3468 bool matchFound = true;
3469 uint32_t dupeCounter = 0;
3470
3471 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3472 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3473
3474 // Loop over layers until we're sure there is no matching name
3475 while (matchFound) {
3476 matchFound = false;
3477 mDrawingState.traverseInZOrder([&](Layer* layer) {
3478 if (layer->getName() == uniqueName) {
3479 matchFound = true;
3480 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3481 }
3482 });
3483 }
3484
3485 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3486
3487 return uniqueName;
3488}
3489
David Sodman0c69cad2017-08-21 12:12:51 -07003490status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003491 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3492 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493{
3494 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003495 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496 case PIXEL_FORMAT_TRANSPARENT:
3497 case PIXEL_FORMAT_TRANSLUCENT:
3498 format = PIXEL_FORMAT_RGBA_8888;
3499 break;
3500 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003501 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003502 break;
3503 }
3504
David Sodman0c69cad2017-08-21 12:12:51 -07003505 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3506 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003508 *handle = layer->getHandle();
3509 *gbp = layer->getProducer();
3510 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003512
David Sodman0c69cad2017-08-21 12:12:51 -07003513 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003514 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515}
3516
chaviw13fdc492017-06-27 12:40:18 -07003517status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003519 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520{
chaviw13fdc492017-06-27 12:40:18 -07003521 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003524}
3525
Mathias Agopianac9fa422013-02-11 16:40:36 -08003526status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527{
Robert Carr9524cb32017-02-13 11:32:32 -08003528 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003529 status_t err = NO_ERROR;
3530 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003531 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003532 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003533 err = removeLayer(l);
3534 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3535 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003536 }
3537 return err;
3538}
3539
Mathias Agopian13127d82013-03-05 17:47:11 -08003540status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003541{
Mathias Agopian67106042013-03-14 19:18:13 -07003542 // called by ~LayerCleaner() when all references to the IBinder (handle)
3543 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003544 sp<Layer> l = layer.promote();
3545 if (l == nullptr) {
3546 // The layer has already been removed, carry on
3547 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003548 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003549 // If we have a parent, then we can continue to live as long as it does.
3550 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551}
3552
Mathias Agopianb60314a2012-04-10 22:09:54 -07003553// ---------------------------------------------------------------------------
3554
Andy McFadden13a082e2012-08-24 10:16:42 -07003555void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003556 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003557 Vector<ComposerState> state;
3558 Vector<DisplayState> displays;
3559 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003560 d.what = DisplayState::eDisplayProjectionChanged |
3561 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003562 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003563 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003564 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003565 d.frame.makeInvalid();
3566 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003567 d.width = 0;
3568 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003569 displays.add(d);
3570 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003571 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3572 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003573
David Sodman105b7dc2017-11-04 20:28:14 -07003574 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003575 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003576 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003577
Brian Andersond0010582017-03-07 13:20:31 -08003578 // Use phase of 0 since phase is not known.
3579 // Use latency of 0, which will snap to the ideal latency.
3580 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003581}
3582
3583void SurfaceFlinger::initializeDisplays() {
3584 class MessageScreenInitialized : public MessageBase {
3585 SurfaceFlinger* flinger;
3586 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003587 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003588 virtual bool handler() {
3589 flinger->onInitializeDisplays();
3590 return true;
3591 }
3592 };
3593 sp<MessageBase> msg = new MessageScreenInitialized(this);
3594 postMessageAsync(msg); // we may be called from main thread, use async message
3595}
3596
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003597void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003598 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003599 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3600 this);
3601 int32_t type = hw->getDisplayType();
3602 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003603
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003604 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003605 return;
3606 }
3607
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003608 hw->setPowerMode(mode);
3609 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3610 ALOGW("Trying to set power mode for virtual display");
3611 return;
3612 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003613
Lloyd Pique4d234852018-01-22 17:21:36 -08003614 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003615 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003616 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3617 if (idx < 0) {
3618 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3619 return;
3620 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003621 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003622 }
3623
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003624 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003625 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003626 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003627 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3628 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003629 // FIXME: eventthread only knows about the main display right now
3630 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003631 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003632 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003634 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003635 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003636 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003637
3638 struct sched_param param = {0};
3639 param.sched_priority = 1;
3640 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3641 ALOGW("Couldn't set SCHED_FIFO on display on");
3642 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003643 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003644 // Turn off the display
3645 struct sched_param param = {0};
3646 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3647 ALOGW("Couldn't set SCHED_OTHER on display off");
3648 }
3649
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003650 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3651 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003652 disableHardwareVsync(true); // also cancels any in-progress resync
3653
Mathias Agopiancde87a32012-09-13 14:09:01 -07003654 // FIXME: eventthread only knows about the main display right now
3655 mEventThread->onScreenReleased();
3656 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003657
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003658 getHwComposer().setPowerMode(type, mode);
3659 mVisibleRegionsDirty = true;
3660 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003661 } else if (mode == HWC_POWER_MODE_DOZE ||
3662 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003663 // Update display while dozing
3664 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003665 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3666 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003667 // FIXME: eventthread only knows about the main display right now
3668 mEventThread->onScreenAcquired();
3669 resyncToHardwareVsync(true);
3670 }
3671 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3672 // Leave display going to doze
3673 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3674 disableHardwareVsync(true); // also cancels any in-progress resync
3675 // FIXME: eventthread only knows about the main display right now
3676 mEventThread->onScreenReleased();
3677 }
3678 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003679 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003680 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003681 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003682 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003683 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003684}
3685
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003686void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3687 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003688 SurfaceFlinger& mFlinger;
3689 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003690 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003691 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003692 MessageSetPowerMode(SurfaceFlinger& flinger,
3693 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3694 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003695 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003697 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003698 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003699 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003700 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 ALOGW("Attempt to set power mode = %d for virtual display",
3702 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003703 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003704 mFlinger.setPowerModeInternal(
3705 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003706 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003707 return true;
3708 }
3709 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003711 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003712}
3713
3714// ---------------------------------------------------------------------------
3715
Lloyd Pique755e3192018-01-31 16:46:15 -08003716status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3717 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003718 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003719
Mathias Agopianbd115332013-04-18 16:41:04 -07003720 IPCThreadState* ipc = IPCThreadState::self();
3721 const int pid = ipc->getCallingPid();
3722 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003723
Mathias Agopianbd115332013-04-18 16:41:04 -07003724 if ((uid != AID_SHELL) &&
3725 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003726 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003727 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003729 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003730 // (this would indicate SF is stuck, but we want to be able to
3731 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003732 status_t err = mStateLock.timedLock(s2ns(1));
3733 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003734 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003735 result.appendFormat(
3736 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3737 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003738 }
3739
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003740 bool dumpAll = true;
3741 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003742 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003743
3744 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003745 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003746 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3747 dumpAll = false;
3748 }
3749
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003750 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003751 if ((index < numArgs) &&
3752 (args[index] == String16("--list"))) {
3753 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003754 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003755 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003756 }
3757
3758 if ((index < numArgs) &&
3759 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003760 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003761 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003762 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003763 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003764
3765 if ((index < numArgs) &&
3766 (args[index] == String16("--latency-clear"))) {
3767 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003768 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003769 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003770 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003771
3772 if ((index < numArgs) &&
3773 (args[index] == String16("--dispsync"))) {
3774 index++;
3775 mPrimaryDispSync.dump(result);
3776 dumpAll = false;
3777 }
Dan Stozab90cf072015-03-05 11:05:59 -08003778
3779 if ((index < numArgs) &&
3780 (args[index] == String16("--static-screen"))) {
3781 index++;
3782 dumpStaticScreenStats(result);
3783 dumpAll = false;
3784 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003785
3786 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003787 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003788 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003789 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003790 dumpAll = false;
3791 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003792
3793 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3794 index++;
3795 dumpWideColorInfo(result);
3796 dumpAll = false;
3797 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003798
3799 if ((index < numArgs) &&
3800 (args[index] == String16("--enable-layer-stats"))) {
3801 index++;
3802 mLayerStats.enable();
3803 dumpAll = false;
3804 }
3805
3806 if ((index < numArgs) &&
3807 (args[index] == String16("--disable-layer-stats"))) {
3808 index++;
3809 mLayerStats.disable();
3810 dumpAll = false;
3811 }
3812
3813 if ((index < numArgs) &&
3814 (args[index] == String16("--clear-layer-stats"))) {
3815 index++;
3816 mLayerStats.clear();
3817 dumpAll = false;
3818 }
3819
3820 if ((index < numArgs) &&
3821 (args[index] == String16("--dump-layer-stats"))) {
3822 index++;
3823 mLayerStats.dump(result);
3824 dumpAll = false;
3825 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003827
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003828 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003829 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003830 }
3831
Mathias Agopian9795c422009-08-26 16:36:26 -07003832 if (locked) {
3833 mStateLock.unlock();
3834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003835 }
3836 write(fd, result.string(), result.size());
3837 return NO_ERROR;
3838}
3839
Dan Stozac7014012014-02-14 15:03:43 -08003840void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3841 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842{
Robert Carr2047fae2016-11-28 14:09:09 -08003843 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003845 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003846}
3847
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003848void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003849 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003850{
3851 String8 name;
3852 if (index < args.size()) {
3853 name = String8(args[index]);
3854 index++;
3855 }
3856
David Sodman105b7dc2017-11-04 20:28:14 -07003857 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003858 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003859 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003860
3861 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003862 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003863 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003864 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003865 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003866 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003867 }
Robert Carr2047fae2016-11-28 14:09:09 -08003868 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003869 }
3870}
3871
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003873 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003874{
3875 String8 name;
3876 if (index < args.size()) {
3877 name = String8(args[index]);
3878 index++;
3879 }
3880
Robert Carr2047fae2016-11-28 14:09:09 -08003881 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003882 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003883 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003884 }
Robert Carr2047fae2016-11-28 14:09:09 -08003885 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003886
Svetoslavd85084b2014-03-20 10:28:31 -07003887 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003888}
3889
Jamie Gennis6547ff42013-07-16 20:12:42 -07003890// This should only be called from the main thread. Otherwise it would need
3891// the lock and should use mCurrentState rather than mDrawingState.
3892void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003893 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003894 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003895 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003896
3897 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3898}
3899
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003900void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003901{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003902 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003903
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003904 if (isLayerTripleBufferingDisabled())
3905 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003906
3907 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003908 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003909 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003910 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003911 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3912 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003913 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003914}
3915
Dan Stozab90cf072015-03-05 11:05:59 -08003916void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3917{
3918 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003919 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3920 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003921 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003922 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003923 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3924 b + 1, bucketTimeSec, percent);
3925 }
David Sodman4a36e932017-11-07 14:29:47 -08003926 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003927 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003928 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003929 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003930 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003931}
3932
Dan Stozae77c7662016-05-13 11:37:28 -07003933void SurfaceFlinger::recordBufferingStats(const char* layerName,
3934 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003935 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3936 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003937 for (const auto& segment : history) {
3938 if (!segment.usedThirdBuffer) {
3939 stats.twoBufferTime += segment.totalTime;
3940 }
3941 if (segment.occupancyAverage < 1.0f) {
3942 stats.doubleBufferedTime += segment.totalTime;
3943 } else if (segment.occupancyAverage < 2.0f) {
3944 stats.tripleBufferedTime += segment.totalTime;
3945 }
3946 ++stats.numSegments;
3947 stats.totalTime += segment.totalTime;
3948 }
3949}
3950
Brian Andersond6927fb2016-07-23 23:37:30 -07003951void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3952 result.appendFormat("Layer frame timestamps:\n");
3953
3954 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3955 const size_t count = currentLayers.size();
3956 for (size_t i=0 ; i<count ; i++) {
3957 currentLayers[i]->dumpFrameEvents(result);
3958 }
3959}
3960
Dan Stozae77c7662016-05-13 11:37:28 -07003961void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3962 result.append("Buffering stats:\n");
3963 result.append(" [Layer name] <Active time> <Two buffer> "
3964 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003965 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003966 typedef std::tuple<std::string, float, float, float> BufferTuple;
3967 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003968 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003969 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003970 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003971 if (stats.numSegments == 0) {
3972 continue;
3973 }
3974 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3975 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3976 stats.totalTime;
3977 float doubleBufferRatio = static_cast<float>(
3978 stats.doubleBufferedTime) / stats.totalTime;
3979 float tripleBufferRatio = static_cast<float>(
3980 stats.tripleBufferedTime) / stats.totalTime;
3981 sorted.insert({activeTime, {name, twoBufferRatio,
3982 doubleBufferRatio, tripleBufferRatio}});
3983 }
3984 for (const auto& sortedPair : sorted) {
3985 float activeTime = sortedPair.first;
3986 const BufferTuple& values = sortedPair.second;
3987 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3988 std::get<0>(values).c_str(), activeTime,
3989 std::get<1>(values), std::get<2>(values),
3990 std::get<3>(values));
3991 }
3992 result.append("\n");
3993}
3994
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003995void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3996 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003997 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003998
3999 // TODO: print out if wide-color mode is active or not
4000
4001 for (size_t d = 0; d < mDisplays.size(); d++) {
4002 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4003 int32_t hwcId = displayDevice->getHwcDisplayId();
4004 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4005 continue;
4006 }
4007
4008 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004009 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004010 for (auto&& mode : modes) {
4011 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4012 }
4013
Peiyong Lina52f0292018-03-14 17:26:31 -07004014 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004015 result.appendFormat(" Current color mode: %s (%d)\n",
4016 decodeColorMode(currentMode).c_str(), currentMode);
4017 }
4018 result.append("\n");
4019}
4020
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004021LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004022 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004023 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4024 const State& state = useDrawing ? mDrawingState : mCurrentState;
4025 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004026 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004027 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004028 });
4029
4030 return layersProto;
4031}
4032
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004033LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4034 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004035 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004036
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004037 SizeProto* resolution = layersProto.mutable_resolution();
4038 resolution->set_w(displayDevice->getWidth());
4039 resolution->set_h(displayDevice->getHeight());
4040
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004041 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4042 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4043 layersProto.set_global_transform(
4044 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4045
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004046 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004047 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004048 LayerProto* layerProto = layersProto.add_layers();
4049 layer->writeToProto(layerProto, hwcId);
4050 }
4051 });
4052
4053 return layersProto;
4054}
4055
Mathias Agopian74d211a2013-04-22 16:55:35 +02004056void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4057 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004058{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004059 bool colorize = false;
4060 if (index < args.size()
4061 && (args[index] == String16("--color"))) {
4062 colorize = true;
4063 index++;
4064 }
4065
4066 Colorizer colorizer(colorize);
4067
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004068 // figure out if we're stuck somewhere
4069 const nsecs_t now = systemTime();
4070 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4071 const nsecs_t inTransaction(mDebugInTransaction);
4072 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4073 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4074
4075 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004076 * Dump library configuration.
4077 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004078
4079 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004080 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004081 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004082 appendSfConfigString(result);
4083 appendUiConfigString(result);
4084 appendGuiConfigString(result);
4085 result.append("\n");
4086
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004087 result.append("\nWide-Color information:\n");
4088 dumpWideColorInfo(result);
4089
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004090 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004091 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004092 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004093 result.append(SyncFeatures::getInstance().toString());
4094 result.append("\n");
4095
David Sodman105b7dc2017-11-04 20:28:14 -07004096 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004097
Andy McFadden41d67d72014-04-25 16:58:34 -07004098 colorizer.bold(result);
4099 result.append("DispSync configuration: ");
4100 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004101 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004102 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004103 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004104 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004105 result.append("\n");
4106
Dan Stozab90cf072015-03-05 11:05:59 -08004107 // Dump static screen stats
4108 result.append("\n");
4109 dumpStaticScreenStats(result);
4110 result.append("\n");
4111
Dan Stozae77c7662016-05-13 11:37:28 -07004112 dumpBufferingStats(result);
4113
Andy McFadden4803b742012-09-24 19:07:20 -07004114 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004115 * Dump the visible layer list
4116 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004117 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004118 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004119 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4120 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004121 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004122
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004123 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004124 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004125 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004126 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004127
4128 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004129 * Dump Display state
4130 */
4131
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004132 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004133 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004134 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004135 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4136 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004137 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004138 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004139 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004140
4141 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 * Dump SurfaceFlinger global state
4143 */
4144
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004145 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004146 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004147 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148
Mathias Agopian888c8222012-08-04 21:10:38 -07004149 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004150 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004151
David Sodmanbc815282017-11-05 18:57:52 -08004152 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004153
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004154 if (hw) {
4155 hw->undefinedRegion.dump(result, "undefinedRegion");
4156 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4157 hw->getOrientation(), hw->isDisplayOn());
4158 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004159 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004160 " last eglSwapBuffers() time: %f us\n"
4161 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004162 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163 " refresh-rate : %f fps\n"
4164 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004165 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004166 " gpu_to_cpu_unsupported : %d\n"
4167 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004168 mLastSwapBufferTime/1000.0,
4169 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004170 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004171 1e9 / activeConfig->getVsyncPeriod(),
4172 activeConfig->getDpiX(),
4173 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004174 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004175
Mathias Agopian74d211a2013-04-22 16:55:35 +02004176 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004177 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004178
Mathias Agopian74d211a2013-04-22 16:55:35 +02004179 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004180 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004181
4182 /*
4183 * VSYNC state
4184 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004185 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004186 result.append("\n");
4187
4188 /*
4189 * HWC layer minidump
4190 */
4191 for (size_t d = 0; d < mDisplays.size(); d++) {
4192 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4193 int32_t hwcId = displayDevice->getHwcDisplayId();
4194 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4195 continue;
4196 }
4197
4198 result.appendFormat("Display %d HWC layers:\n", hwcId);
4199 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004200 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004201 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004202 });
Dan Stozae22aec72016-08-01 13:20:59 -07004203 result.append("\n");
4204 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004205
4206 /*
4207 * Dump HWComposer state
4208 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004209 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004210 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004212 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004213 result.appendFormat(" h/w composer %s\n",
4214 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004215 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004216
4217 /*
4218 * Dump gralloc state
4219 */
4220 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4221 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004222
4223 /*
4224 * Dump VrFlinger state if in use.
4225 */
4226 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4227 result.append("VrFlinger state:\n");
4228 result.append(mVrFlinger->Dump().c_str());
4229 result.append("\n");
4230 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231}
4232
Mathias Agopian13127d82013-03-05 17:47:11 -08004233const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004234SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004235 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004236 wp<IBinder> dpy;
4237 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4238 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4239 dpy = mDisplays.keyAt(i);
4240 break;
4241 }
4242 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004243 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004244 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4245 // Just use the primary display so we have something to return
4246 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4247 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004248 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004249}
4250
Keun young Park63f165f2012-08-31 10:53:36 -07004251bool SurfaceFlinger::startDdmConnection()
4252{
4253 void* libddmconnection_dso =
4254 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4255 if (!libddmconnection_dso) {
4256 return false;
4257 }
4258 void (*DdmConnection_start)(const char* name);
4259 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004260 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004261 if (!DdmConnection_start) {
4262 dlclose(libddmconnection_dso);
4263 return false;
4264 }
4265 (*DdmConnection_start)(getServiceName());
4266 return true;
4267}
4268
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004269status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004270 switch (code) {
4271 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004272 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004274 case CLEAR_ANIMATION_FRAME_STATS:
4275 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004276 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004277 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004278 case ENABLE_VSYNC_INJECTIONS:
4279 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 {
4281 // codes that require permission check
4282 IPCThreadState* ipc = IPCThreadState::self();
4283 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004284 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004285 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004286 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004287 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004288 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004290 break;
4291 }
Robert Carr1db73f62016-12-21 12:58:51 -08004292 /*
4293 * Calling setTransactionState is safe, because you need to have been
4294 * granted a reference to Client* and Handle* to do anything with it.
4295 *
4296 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4297 */
4298 case SET_TRANSACTION_STATE:
4299 case CREATE_SCOPED_CONNECTION:
4300 {
4301 return OK;
4302 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004303 case CAPTURE_SCREEN:
4304 {
4305 // codes that require permission check
4306 IPCThreadState* ipc = IPCThreadState::self();
4307 const int pid = ipc->getCallingPid();
4308 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004309 if ((uid != AID_GRAPHICS) &&
4310 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004311 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004312 return PERMISSION_DENIED;
4313 }
4314 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004315 }
chaviwa76b2712017-09-20 12:02:26 -07004316 case CAPTURE_LAYERS: {
4317 IPCThreadState* ipc = IPCThreadState::self();
4318 const int pid = ipc->getCallingPid();
4319 const int uid = ipc->getCallingUid();
4320 if ((uid != AID_GRAPHICS) &&
4321 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4322 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4323 return PERMISSION_DENIED;
4324 }
4325 break;
4326 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004327 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004328 return OK;
4329}
4330
4331status_t SurfaceFlinger::onTransact(
4332 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4333{
4334 status_t credentialCheck = CheckTransactCodeCredentials(code);
4335 if (credentialCheck != OK) {
4336 return credentialCheck;
4337 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004339 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4340 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004341 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004342 IPCThreadState* ipc = IPCThreadState::self();
4343 const int uid = ipc->getCallingUid();
4344 if (CC_UNLIKELY(uid != AID_SYSTEM
4345 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004346 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004347 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004348 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004349 return PERMISSION_DENIED;
4350 }
4351 int n;
4352 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004353 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004354 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004355 return NO_ERROR;
4356 case 1002: // SHOW_UPDATES
4357 n = data.readInt32();
4358 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004359 invalidateHwcGeometry();
4360 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004361 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004363 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004364 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004366 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004367 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004368 setTransactionFlags(
4369 eTransactionNeeded|
4370 eDisplayTransactionNeeded|
4371 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004372 return NO_ERROR;
4373 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004374 case 1006:{ // send empty update
4375 signalRefresh();
4376 return NO_ERROR;
4377 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004378 case 1008: // toggle use of hw composer
4379 n = data.readInt32();
4380 mDebugDisableHWC = n ? 1 : 0;
4381 invalidateHwcGeometry();
4382 repaintEverything();
4383 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004384 case 1009: // toggle use of transform hint
4385 n = data.readInt32();
4386 mDebugDisableTransformHint = n ? 1 : 0;
4387 invalidateHwcGeometry();
4388 repaintEverything();
4389 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004390 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004391 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 reply->writeInt32(0);
4393 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004394 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004395 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004396 return NO_ERROR;
4397 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004398 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004399 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004400 return NO_ERROR;
4401 }
4402 case 1014: {
4403 // daltonize
4404 n = data.readInt32();
4405 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004406 case 1:
4407 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4408 break;
4409 case 2:
4410 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4411 break;
4412 case 3:
4413 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4414 break;
4415 default:
4416 mDaltonizer.setType(ColorBlindnessType::None);
4417 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004418 }
4419 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004420 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004421 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004422 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004423 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004424 invalidateHwcGeometry();
4425 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004426 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004427 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004428 case 1015: {
4429 // apply a color matrix
4430 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004431 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004432 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004433 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004434 for (size_t j = 0; j < 4; j++) {
4435 mColorMatrix[i][j] = data.readFloat();
4436 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004437 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004438 } else {
4439 mColorMatrix = mat4();
4440 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004441
4442 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4443 // the division by w in the fragment shader
4444 float4 lastRow(transpose(mColorMatrix)[3]);
4445 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4446 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4447 }
4448
Alan Viverette9c5a3332013-09-12 20:04:35 -07004449 invalidateHwcGeometry();
4450 repaintEverything();
4451 return NO_ERROR;
4452 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004453 // This is an experimental interface
4454 // Needs to be shifted to proper binder interface when we productize
4455 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004456 n = data.readInt32();
4457 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004458 return NO_ERROR;
4459 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004460 case 1017: {
4461 n = data.readInt32();
4462 mForceFullDamage = static_cast<bool>(n);
4463 return NO_ERROR;
4464 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004465 case 1018: { // Modify Choreographer's phase offset
4466 n = data.readInt32();
4467 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4468 return NO_ERROR;
4469 }
4470 case 1019: { // Modify SurfaceFlinger's phase offset
4471 n = data.readInt32();
4472 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4473 return NO_ERROR;
4474 }
Irvel468051e2016-06-13 16:44:44 -07004475 case 1020: { // Layer updates interceptor
4476 n = data.readInt32();
4477 if (n) {
4478 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004479 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004480 }
4481 else{
4482 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004483 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004484 }
4485 return NO_ERROR;
4486 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004487 case 1021: { // Disable HWC virtual displays
4488 n = data.readInt32();
4489 mUseHwcVirtualDisplays = !n;
4490 return NO_ERROR;
4491 }
Romain Guy0147a172017-06-01 13:53:56 -07004492 case 1022: { // Set saturation boost
4493 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4494
4495 invalidateHwcGeometry();
4496 repaintEverything();
4497 return NO_ERROR;
4498 }
Romain Guy54f154a2017-10-24 21:40:32 +01004499 case 1023: { // Set native mode
4500 mForceNativeColorMode = data.readInt32() == 1;
4501
4502 invalidateHwcGeometry();
4503 repaintEverything();
4504 return NO_ERROR;
4505 }
4506 case 1024: { // Is wide color gamut rendering/color management supported?
4507 reply->writeBool(hasWideColorDisplay);
4508 return NO_ERROR;
4509 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004510 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004511 n = data.readInt32();
4512 if (n) {
4513 ALOGV("LayerTracing enabled");
4514 mTracing.enable();
4515 doTracing("tracing.enable");
4516 reply->writeInt32(NO_ERROR);
4517 } else {
4518 ALOGV("LayerTracing disabled");
4519 status_t err = mTracing.disable();
4520 reply->writeInt32(err);
4521 }
4522 return NO_ERROR;
4523 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004524 case 1026: { // Get layer tracing status
4525 reply->writeBool(mTracing.isEnabled());
4526 return NO_ERROR;
4527 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 }
4529 }
4530 return err;
4531}
4532
Steven Thomas6d8110b2017-08-31 18:24:21 -07004533void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004534 android_atomic_or(1, &mRepaintEverything);
Jeffrey Kardatzkea9dcf112018-04-03 10:45:55 -07004535 for (size_t dpy = 0; dpy < mDisplays.size(); dpy++) {
4536 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
4537 const Rect bounds(displayDevice->getBounds());
4538 displayDevice->dirtyRegion.orSelf(Region(bounds));
4539 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004540 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004541}
4542
Steven Thomas6d8110b2017-08-31 18:24:21 -07004543void SurfaceFlinger::repaintEverything() {
4544 ConditionalLock _l(mStateLock,
4545 std::this_thread::get_id() != mMainThreadId);
4546 repaintEverythingLocked();
4547}
4548
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004549// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4550class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004551public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004552 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4553 ~WindowDisconnector() {
4554 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004555 }
4556
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004557private:
4558 ANativeWindow* mWindow;
4559 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004560};
4561
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004562status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4563 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4564 int32_t minLayerZ, int32_t maxLayerZ,
4565 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004566 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004567 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004568
chaviwa76b2712017-09-20 12:02:26 -07004569 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4570
4571 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004572 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4573
chaviwa76b2712017-09-20 12:02:26 -07004574 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4575
4576 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4577 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004578 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004579}
4580
4581status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004582 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004583 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004584 ATRACE_CALL();
4585
4586 class LayerRenderArea : public RenderArea {
4587 public:
Robert Carr578038f2018-03-09 12:25:24 -08004588 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4589 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4590 : RenderArea(reqHeight, reqWidth),
4591 mLayer(layer),
4592 mCrop(crop),
4593 mFlinger(flinger),
4594 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004595 Rect getBounds() const override {
4596 const Layer::State& layerState(mLayer->getDrawingState());
4597 return Rect(layerState.active.w, layerState.active.h);
4598 }
4599 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4600 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4601 bool isSecure() const override { return false; }
4602 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004603 const Transform& getTransform() const { return mTransform; }
4604
4605 class ReparentForDrawing {
4606 public:
4607 const sp<Layer>& oldParent;
4608 const sp<Layer>& newParent;
4609
4610 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4611 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004612 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004613 }
Robert Carr15eae092018-03-23 13:43:53 -07004614 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004615 };
4616
4617 void render(std::function<void()> drawLayers) override {
4618 if (!mChildrenOnly) {
4619 mTransform = mLayer->getTransform().inverse();
4620 drawLayers();
4621 } else {
4622 Rect bounds = getBounds();
4623 screenshotParentLayer =
4624 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4625 bounds.getWidth(), bounds.getHeight(), 0);
4626
4627 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4628 drawLayers();
4629 }
4630 }
chaviwa76b2712017-09-20 12:02:26 -07004631
chaviw7206d492017-11-10 16:16:12 -08004632 Rect getSourceCrop() const override {
4633 if (mCrop.isEmpty()) {
4634 return getBounds();
4635 } else {
4636 return mCrop;
4637 }
4638 }
chaviwa76b2712017-09-20 12:02:26 -07004639 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004640 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004641
4642 private:
chaviw7206d492017-11-10 16:16:12 -08004643 const sp<Layer> mLayer;
4644 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004645
4646 // In the "childrenOnly" case we reparent the children to a screenshot
4647 // layer which has no properties set and which does not draw.
4648 sp<ContainerLayer> screenshotParentLayer;
4649 Transform mTransform;
4650
4651 SurfaceFlinger* mFlinger;
4652 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004653 };
4654
4655 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4656 auto parent = layerHandle->owner.promote();
4657
chaviw7206d492017-11-10 16:16:12 -08004658 if (parent == nullptr || parent->isPendingRemoval()) {
4659 ALOGE("captureLayers called with a removed parent");
4660 return NAME_NOT_FOUND;
4661 }
4662
Robert Carr578038f2018-03-09 12:25:24 -08004663 const int uid = IPCThreadState::self()->getCallingUid();
4664 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4665 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4666 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4667 return PERMISSION_DENIED;
4668 }
4669
chaviw7206d492017-11-10 16:16:12 -08004670 Rect crop(sourceCrop);
4671 if (sourceCrop.width() <= 0) {
4672 crop.left = 0;
4673 crop.right = parent->getCurrentState().active.w;
4674 }
4675
4676 if (sourceCrop.height() <= 0) {
4677 crop.top = 0;
4678 crop.bottom = parent->getCurrentState().active.h;
4679 }
4680
4681 int32_t reqWidth = crop.width() * frameScale;
4682 int32_t reqHeight = crop.height() * frameScale;
4683
Robert Carr578038f2018-03-09 12:25:24 -08004684 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004685
Robert Carr578038f2018-03-09 12:25:24 -08004686 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004687 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4688 if (!layer->isVisible()) {
4689 return;
Robert Carr578038f2018-03-09 12:25:24 -08004690 } else if (childrenOnly && layer == parent.get()) {
4691 return;
chaviwa76b2712017-09-20 12:02:26 -07004692 }
4693 visitor(layer);
4694 });
4695 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004696 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004697}
4698
4699status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4700 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004701 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004702 bool useIdentityTransform) {
4703 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004704
chaviwa76b2712017-09-20 12:02:26 -07004705 renderArea.updateDimensions();
4706
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004707 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4708 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4709 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4710 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004711
4712 // This mutex protects syncFd and captureResult for communication of the return values from the
4713 // main thread back to this Binder thread
4714 std::mutex captureMutex;
4715 std::condition_variable captureCondition;
4716 std::unique_lock<std::mutex> captureLock(captureMutex);
4717 int syncFd = -1;
4718 std::optional<status_t> captureResult;
4719
Robert Carr03480e22018-01-04 16:02:06 -08004720 const int uid = IPCThreadState::self()->getCallingUid();
4721 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4722
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004723 sp<LambdaMessage> message = new LambdaMessage([&]() {
4724 // If there is a refresh pending, bug out early and tell the binder thread to try again
4725 // after the refresh.
4726 if (mRefreshPending) {
4727 ATRACE_NAME("Skipping screenshot for now");
4728 std::unique_lock<std::mutex> captureLock(captureMutex);
4729 captureResult = std::make_optional<status_t>(EAGAIN);
4730 captureCondition.notify_one();
4731 return;
4732 }
4733
4734 status_t result = NO_ERROR;
4735 int fd = -1;
4736 {
4737 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004738 renderArea.render([&]() {
4739 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4740 useIdentityTransform, forSystem, &fd);
4741 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004742 }
4743
4744 {
4745 std::unique_lock<std::mutex> captureLock(captureMutex);
4746 syncFd = fd;
4747 captureResult = std::make_optional<status_t>(result);
4748 captureCondition.notify_one();
4749 }
4750 });
4751
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004752 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004753 if (result == NO_ERROR) {
4754 captureCondition.wait(captureLock, [&]() { return captureResult; });
4755 while (*captureResult == EAGAIN) {
4756 captureResult.reset();
4757 result = postMessageAsync(message);
4758 if (result != NO_ERROR) {
4759 return result;
4760 }
4761 captureCondition.wait(captureLock, [&]() { return captureResult; });
4762 }
4763 result = *captureResult;
4764 }
4765
4766 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004767 sync_wait(syncFd, -1);
4768 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004769 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004770
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004771 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004772}
4773
chaviwa76b2712017-09-20 12:02:26 -07004774void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4775 TraverseLayersFunction traverseLayers, bool yswap,
4776 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004777 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004778
Lloyd Pique144e1162017-12-20 16:44:52 -08004779 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004780
4781 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004782 const auto raWidth = renderArea.getWidth();
4783 const auto raHeight = renderArea.getHeight();
4784
4785 const auto reqWidth = renderArea.getReqWidth();
4786 const auto reqHeight = renderArea.getReqHeight();
4787 Rect sourceCrop = renderArea.getSourceCrop();
4788
4789 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4790 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004791
Dan Stozac1879002014-05-22 15:59:05 -07004792 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004793 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004794 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004795 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004796 }
4797
4798 // ensure that sourceCrop is inside screen
4799 if (sourceCrop.left < 0) {
4800 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4801 }
chaviwa76b2712017-09-20 12:02:26 -07004802 if (sourceCrop.right > raWidth) {
4803 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004804 }
4805 if (sourceCrop.top < 0) {
4806 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4807 }
chaviwa76b2712017-09-20 12:02:26 -07004808 if (sourceCrop.bottom > raHeight) {
4809 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004810 }
4811
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004812 Dataspace outputDataspace = Dataspace::UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004813 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004814 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004815 outputDataspace = Dataspace::DISPLAY_P3;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004816 }
4817 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004818
Mathias Agopian180f10d2013-04-10 22:55:41 -07004819 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004820 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004821
4822 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004823 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4824 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004825 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004826
4827 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004828 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004829
chaviwa76b2712017-09-20 12:02:26 -07004830 traverseLayers([&](Layer* layer) {
4831 if (filtering) layer->setFiltering(true);
4832 layer->draw(renderArea, useIdentityTransform);
4833 if (filtering) layer->setFiltering(false);
4834 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004835}
4836
chaviwa76b2712017-09-20 12:02:26 -07004837status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4838 TraverseLayersFunction traverseLayers,
4839 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004840 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004841 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004842 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004843 ATRACE_CALL();
4844
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004845 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004846
4847 traverseLayers([&](Layer* layer) {
4848 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4849 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004850
Robert Carr03480e22018-01-04 16:02:06 -08004851 // We allow the system server to take screenshots of secure layers for
4852 // use in situations like the Screen-rotation animation and place
4853 // the impetus on WindowManager to not persist them.
4854 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004855 ALOGW("FB is protected: PERMISSION_DENIED");
4856 return PERMISSION_DENIED;
4857 }
4858
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004859 // this binds the given EGLImage as a framebuffer for the
4860 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004861 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004862 if (bufferBond.getStatus() != NO_ERROR) {
4863 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004864 return INVALID_OPERATION;
4865 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004866
Dan Stozaabcda352017-06-01 14:37:39 -07004867 // this will in fact render into our dequeued buffer
4868 // via an FBO, which means we didn't have to create
4869 // an EGLSurface and therefore we're not
4870 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004871 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004872
Dan Stozaabcda352017-06-01 14:37:39 -07004873 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004874 getRenderEngine().finish();
4875 *outSyncFd = -1;
4876
chaviwa76b2712017-09-20 12:02:26 -07004877 const auto reqWidth = renderArea.getReqWidth();
4878 const auto reqHeight = renderArea.getReqHeight();
4879
Dan Stozaabcda352017-06-01 14:37:39 -07004880 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4881 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004882 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004883 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004884 } else {
4885 base::unique_fd syncFd = getRenderEngine().flush();
4886 if (syncFd < 0) {
4887 getRenderEngine().finish();
4888 }
4889 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004890 }
4891
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004892 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004893}
4894
Mathias Agopiand5556842013-09-19 17:08:37 -07004895void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004896 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004897 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004898 for (size_t y = 0; y < h; y++) {
4899 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4900 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004901 if (p[x] != 0xFF000000) return;
4902 }
4903 }
chaviwa76b2712017-09-20 12:02:26 -07004904 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004905
Robert Carr2047fae2016-11-28 14:09:09 -08004906 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004907 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004908 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004909 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4910 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4911 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4912 static_cast<float>(state.color.a));
4913 i++;
4914 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004915 }
4916}
4917
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004918// ---------------------------------------------------------------------------
4919
Dan Stoza412903f2017-04-27 13:42:17 -07004920void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4921 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004922}
4923
Dan Stoza412903f2017-04-27 13:42:17 -07004924void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4925 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004926}
4927
chaviwa76b2712017-09-20 12:02:26 -07004928void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4929 int32_t maxLayerZ,
4930 const LayerVector::Visitor& visitor) {
4931 // We loop through the first level of layers without traversing,
4932 // as we need to interpret min/max layer Z in the top level Z space.
4933 for (const auto& layer : mDrawingState.layersSortedByZ) {
4934 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4935 continue;
4936 }
4937 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004938 // relative layers are traversed in Layer::traverseInZOrder
4939 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004940 continue;
4941 }
4942 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004943 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4944 return;
4945 }
chaviwa76b2712017-09-20 12:02:26 -07004946 if (!layer->isVisible()) {
4947 return;
4948 }
4949 visitor(layer);
4950 });
4951 }
4952}
4953
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004955
4956
4957#if defined(__gl_h_)
4958#error "don't include gl/gl.h in this file"
4959#endif
4960
4961#if defined(__gl2_h_)
4962#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004963#endif