blob: 90743f2e10fc900ef6e3dac0175b17e0c3c16bad [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;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108
Steven Thomasb02664d2017-07-26 18:48:28 -0700109namespace {
110class ConditionalLock {
111public:
112 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
113 if (lock) {
114 mMutex.lock();
115 }
116 }
117 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
118private:
119 Mutex& mMutex;
120 bool mLocked;
121};
122} // namespace anonymous
123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124// ---------------------------------------------------------------------------
125
Mathias Agopian99b49842011-06-27 16:05:52 -0700126const String16 sHardwareTest("android.permission.HARDWARE_TEST");
127const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
128const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
129const String16 sDump("android.permission.DUMP");
130
131// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800132int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
133int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800140// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600141bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700142
Kalle Raitaa099a242017-01-11 11:17:29 -0800143
144std::string getHwcServiceName() {
145 char value[PROPERTY_VALUE_MAX] = {};
146 property_get("debug.sf.hwc_service_name", value, "default");
147 ALOGI("Using HWComposer service: '%s'", value);
148 return std::string(value);
149}
150
151bool useTrebleTestingOverride() {
152 char value[PROPERTY_VALUE_MAX] = {};
153 property_get("debug.sf.treble_testing_override", value, "false");
154 ALOGI("Treble testing override: '%s'", value);
155 return std::string(value) == "true";
156}
157
Lloyd Pique09594832018-01-22 17:48:03 -0800158NativeWindowSurface::~NativeWindowSurface() = default;
159
160namespace impl {
161
162class NativeWindowSurface final : public android::NativeWindowSurface {
163public:
164 static std::unique_ptr<android::NativeWindowSurface> create(
165 const sp<IGraphicBufferProducer>& producer) {
166 return std::make_unique<NativeWindowSurface>(producer);
167 }
168
169 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
170 : surface(new Surface(producer, false)) {}
171
172 ~NativeWindowSurface() override = default;
173
174private:
175 sp<ANativeWindow> getNativeWindow() const override { return surface; }
176
177 void preallocateBuffers() override { surface->allocateBuffers(); }
178
179 sp<Surface> surface;
180};
181
182} // namespace impl
183
David Sodmanbc815282017-11-05 18:57:52 -0800184SurfaceFlingerBE::SurfaceFlingerBE()
185 : mHwcServiceName(getHwcServiceName()),
186 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800187 mFrameBuckets(),
188 mTotalTime(0),
189 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800190 mComposerSequenceId(0) {
191}
192
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800193SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800194 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700196 mTransactionPending(false),
197 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700198 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700199 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700200 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800202 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800204 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800205 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700208 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700209 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700210 mDebugInSwapBuffers(0),
211 mLastSwapBufferTime(0),
212 mDebugInTransaction(0),
213 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700214 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700215 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000216 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700217 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700218 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700219 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800220 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700222 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800223 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800224 mCreateBufferQueue(&BufferQueue::createBufferQueue),
225 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800226
227SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800228 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800229
230 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
231 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
232
233 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
234 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
235
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800236 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
237 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700239 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
240 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
241
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700242 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
243 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
244
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800245 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
246 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
247
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 // Vr flinger is only enabled on Daydream ready devices.
249 useVrFlinger = getBool< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::useVrFlinger>(false);
251
Fabien Sanglard1971b632017-03-10 14:50:03 -0800252 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
254
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600255 hasWideColorDisplay =
256 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
257
David Sodman99974d22017-11-28 12:04:33 -0800258 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 // debugging stuff...
261 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262
Mathias Agopianb4b17302013-03-20 18:36:41 -0700263 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700264 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 property_get("debug.sf.showupdates", value, "0");
267 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700268
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700269 property_get("debug.sf.ddms", value, "0");
270 mDebugDDMS = atoi(value);
271 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700272 if (!startDdmConnection()) {
273 // start failed, and DDMS debugging not enabled
274 mDebugDDMS = 0;
275 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700276 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700277 ALOGI_IF(mDebugRegion, "showupdates enabled");
278 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700279
280 property_get("debug.sf.disable_backpressure", value, "0");
281 mPropagateBackpressure = !atoi(value);
282 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700283
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800284 property_get("debug.sf.enable_hwc_vds", value, "0");
285 mUseHwcVirtualDisplays = atoi(value);
286 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800287
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800288 property_get("ro.sf.disable_triple_buffer", value, "1");
289 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800290 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700291
Dan Stoza0a0158c2018-03-16 13:38:54 -0700292 // TODO (b/74616334): Reduce the default value once we isolate the leak
293 const size_t defaultListSize = 4 * MAX_LAYERS;
294 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
295 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
296
Romain Guy11d63f42017-07-20 12:47:14 -0700297 // We should be reading 'persist.sys.sf.color_saturation' here
298 // but since /data may be encrypted, we need to wait until after vold
299 // comes online to attempt to read the property. The property is
300 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800301
302 if (useTrebleTestingOverride()) {
303 // Without the override SurfaceFlinger cannot connect to HIDL
304 // services that are not listed in the manifests. Considered
305 // deriving the setting from the set service name, but it
306 // would be brittle if the name that's not 'default' is used
307 // for production purposes later on.
308 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
309 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310}
311
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800312void SurfaceFlinger::onFirstRef()
313{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800314 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800315}
316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317SurfaceFlinger::~SurfaceFlinger()
318{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319}
320
Dan Stozac7014012014-02-14 15:03:43 -0800321void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800322{
323 // the window manager died on us. prepare its eulogy.
324
Andy McFadden13a082e2012-08-24 10:16:42 -0700325 // restore initial conditions (default device unblank, etc)
326 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800327
328 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700329 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800330}
331
Robert Carr1db73f62016-12-21 12:58:51 -0800332static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700333 status_t err = client->initCheck();
334 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800335 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 }
Robert Carr1db73f62016-12-21 12:58:51 -0800337 return nullptr;
338}
339
340sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
341 return initClient(new Client(this));
342}
343
344sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
345 const sp<IGraphicBufferProducer>& gbp) {
346 if (authenticateSurfaceTexture(gbp) == false) {
347 return nullptr;
348 }
349 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
350 if (layer == nullptr) {
351 return nullptr;
352 }
353
354 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355}
356
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700357sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
358 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700359{
360 class DisplayToken : public BBinder {
361 sp<SurfaceFlinger> flinger;
362 virtual ~DisplayToken() {
363 // no more references, this display must be terminated
364 Mutex::Autolock _l(flinger->mStateLock);
365 flinger->mCurrentState.displays.removeItem(this);
366 flinger->setTransactionFlags(eDisplayTransactionNeeded);
367 }
368 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700369 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700370 : flinger(flinger) {
371 }
372 };
373
374 sp<BBinder> token = new DisplayToken(this);
375
376 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700377 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700378 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700379 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800380 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381 return token;
382}
383
Jesse Hall6c913be2013-08-08 12:15:49 -0700384void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
385 Mutex::Autolock _l(mStateLock);
386
387 ssize_t idx = mCurrentState.displays.indexOfKey(display);
388 if (idx < 0) {
389 ALOGW("destroyDisplay: invalid display token");
390 return;
391 }
392
393 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
394 if (!info.isVirtualDisplay()) {
395 ALOGE("destroyDisplay called for non-virtual display");
396 return;
397 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800398 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700399 mCurrentState.displays.removeItemsAt(idx);
400 setTransactionFlags(eDisplayTransactionNeeded);
401}
402
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700404 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700405 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800406 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700407 }
Jesse Hall692c7232012-11-08 15:41:56 -0800408 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409}
410
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411void SurfaceFlinger::bootFinished()
412{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700413 if (mStartPropertySetThread->join() != NO_ERROR) {
414 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800415 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416 const nsecs_t now = systemTime();
417 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000418 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700419
420 // wait patiently for the window manager death
421 const String16 name("window");
422 sp<IBinder> window(defaultServiceManager()->getService(name));
423 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700425 }
426
Steven Thomas050b2c82017-03-06 11:45:16 -0800427 if (mVrFlinger) {
428 mVrFlinger->OnBootFinished();
429 }
430
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700431 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 // formerly we would just kill the process, but we now ask it to exit so it
433 // can choose where to stop the animation.
434 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700435
436 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
437 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
438 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700439
Thierry Strudel2924d012017-08-14 15:19:37 -0700440 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700441 readPersistentProperties();
442 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700443 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444}
445
Mathias Agopian3f844832013-08-07 21:24:32 -0700446void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700447 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800448 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700449 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700450 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800451 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
452 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700453 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700454 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700455 return true;
456 }
457 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700458 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700459}
460
Lloyd Piquee83f9312018-02-01 12:53:17 -0800461class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700463 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000464 const char* name) :
465 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700467 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
469 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700470 mDispSync(dispSync),
471 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 mVsyncMutex(),
473 mPhaseOffset(phaseOffset),
474 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700475
Lloyd Piquee83f9312018-02-01 12:53:17 -0800476 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700477
Lloyd Piquee83f9312018-02-01 12:53:17 -0800478 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000481 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 static_cast<DispSync::Callback*>(this));
483 if (err != NO_ERROR) {
484 ALOGE("error registering vsync callback: %s (%d)",
485 strerror(-err), err);
486 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700487 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 } else {
489 status_t err = mDispSync->removeEventListener(
490 static_cast<DispSync::Callback*>(this));
491 if (err != NO_ERROR) {
492 ALOGE("error unregistering vsync callback: %s (%d)",
493 strerror(-err), err);
494 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700497 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 }
499
Lloyd Piquee83f9312018-02-01 12:53:17 -0800500 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700501 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 mCallback = callback;
503 }
504
Lloyd Piquee83f9312018-02-01 12:53:17 -0800505 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 Mutex::Autolock lock(mVsyncMutex);
507
508 // Normalize phaseOffset to [0, period)
509 auto period = mDispSync->getPeriod();
510 phaseOffset %= period;
511 if (phaseOffset < 0) {
512 // If we're here, then phaseOffset is in (-period, 0). After this
513 // operation, it will be in (0, period)
514 phaseOffset += period;
515 }
516 mPhaseOffset = phaseOffset;
517
518 // If we're not enabled, we don't need to mess with the listeners
519 if (!mEnabled) {
520 return;
521 }
522
523 // Remove the listener with the old offset
524 status_t err = mDispSync->removeEventListener(
525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error unregistering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
530
531 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000532 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 static_cast<DispSync::Callback*>(this));
534 if (err != NO_ERROR) {
535 ALOGE("error registering vsync callback: %s (%d)",
536 strerror(-err), err);
537 }
538 }
539
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540private:
541 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 callback = mCallback;
546
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547 if (mTraceVsync) {
548 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700549 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700550 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 }
552
Peiyong Lin566a3b42018-01-09 18:22:43 -0800553 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 callback->onVSyncEvent(when);
555 }
556 }
557
Tim Murray4a4e4a22016-04-19 16:29:23 +0000558 const char* const mName;
559
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560 int mValue;
561
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700562 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 const String8 mVsyncOnLabel;
564 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700565
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567
568 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570
571 Mutex mVsyncMutex; // Protects the following
572 nsecs_t mPhaseOffset;
573 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574};
575
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700577public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 InjectVSyncSource() = default;
579 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700580
Lloyd Piquee83f9312018-02-01 12:53:17 -0800581 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700582 std::lock_guard<std::mutex> lock(mCallbackMutex);
583 mCallback = callback;
584 }
585
Lloyd Piquee83f9312018-02-01 12:53:17 -0800586 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700587 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700588 if (mCallback) {
589 mCallback->onVSyncEvent(when);
590 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700591 }
592
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 void setVSyncEnabled(bool) override {}
594 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700595
596private:
597 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800598 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700599};
600
Wei Wangf9b05ee2017-07-19 20:59:39 -0700601// Do not call property_set on main thread which will be blocked by init
602// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700604 ALOGI( "SurfaceFlinger's main thread ready to run. "
605 "Initializing graphics H/W...");
606
Thierry Strudel2924d012017-08-14 15:19:37 -0700607 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800612 mEventThreadSource =
613 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
614 true, "app");
615 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
616 "appEventThread");
617 mSfEventThreadSource =
618 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
619 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800620
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800621 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
622 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800623 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800626 getBE().mRenderEngine =
627 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
628 hasWideColorDisplay
629 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
630 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800631 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700632
633 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
634 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800635 getBE().mHwc.reset(
636 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700637 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800638 // Process any initial hotplug and resulting display changes.
639 processDisplayHotplugEventsLocked();
640 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
641 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800642
Lloyd Piquefcd86612017-12-14 17:15:36 -0800643 // make the default display GLContext current so that we can create textures
644 // when creating Layers (which may happens before we render something)
645 getDefaultDisplayDeviceLocked()->makeCurrent();
646
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (useVrFlinger) {
648 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 // This callback is called from the vr flinger dispatch thread. We
650 // need to call signalTransaction(), which requires holding
651 // mStateLock when we're not on the main thread. Acquiring
652 // mStateLock from the vr flinger dispatch thread might trigger a
653 // deadlock in surface flinger (see b/66916578), so post a message
654 // to be handled on the main thread instead.
655 sp<LambdaMessage> message = new LambdaMessage([=]() {
656 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
657 mVrFlingerRequestsDisplay = requestDisplay;
658 signalTransaction();
659 });
660 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 };
David Sodman105b7dc2017-11-04 20:28:14 -0700662 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
663 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800664 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 if (!mVrFlinger) {
666 ALOGE("Failed to start vrflinger");
667 }
668 }
669
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800670 mEventControlThread = std::make_unique<impl::EventControlThread>(
671 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700672
Mathias Agopian92a979a2012-08-02 18:32:23 -0700673 // initialize our drawing state
674 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700675
Andy McFadden13a082e2012-08-24 10:16:42 -0700676 // set initial conditions (e.g. unblank default device)
677 initializeDisplays();
678
David Sodmanbc815282017-11-05 18:57:52 -0800679 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700680
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 // Inform native graphics APIs whether the present timestamp is supported:
682 if (getHwComposer().hasCapability(
683 HWC2::Capability::PresentFenceIsNotReliable)) {
684 mStartPropertySetThread = new StartPropertySetThread(false);
685 } else {
686 mStartPropertySetThread = new StartPropertySetThread(true);
687 }
688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
700 mSaturation = atof(value);
701 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
704 mForceNativeColorMode = atoi(value) == 1;
705 if (mForceNativeColorMode) {
706 ALOGV("Forcing native color mode");
707 }
Romain Guy11d63f42017-07-20 12:47:14 -0700708}
709
Mathias Agopiana67e4182012-06-19 17:26:12 -0700710void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Start boot animation service by setting a property mailbox
712 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800714 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 if (mStartPropertySetThread->join() != NO_ERROR) {
716 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800721 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800725 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800729
Jamie Gennis582270d2011-08-17 18:19:00 -0700730bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800732 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800733 return authenticateSurfaceTextureLocked(bufferProducer);
734}
735
736bool SurfaceFlinger::authenticateSurfaceTextureLocked(
737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800738 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800739 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800740}
741
Brian Anderson6b376712017-04-04 10:51:39 -0700742status_t SurfaceFlinger::getSupportedFrameTimestamps(
743 std::vector<FrameEvent>* outSupported) const {
744 *outSupported = {
745 FrameEvent::REQUESTED_PRESENT,
746 FrameEvent::ACQUIRE,
747 FrameEvent::LATCH,
748 FrameEvent::FIRST_REFRESH_START,
749 FrameEvent::LAST_REFRESH_START,
750 FrameEvent::GPU_COMPOSITION_DONE,
751 FrameEvent::DEQUEUE_READY,
752 FrameEvent::RELEASE,
753 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700756 if (!getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
759 }
760 return NO_ERROR;
761}
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
764 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800765 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 return BAD_VALUE;
767 }
768
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500769 if (!display.get())
770 return NAME_NOT_FOUND;
771
Jesse Hall692c7232012-11-08 15:41:56 -0800772 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700773 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800774 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700775 type = i;
776 break;
777 }
778 }
779
780 if (type < 0) {
781 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700782 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 // TODO: Not sure if display density should handled by SF any longer
785 class Density {
786 static int getDensityFromProperty(char const* propName) {
787 char property[PROPERTY_VALUE_MAX];
788 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800789 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700790 density = atoi(property);
791 }
792 return density;
793 }
794 public:
795 static int getEmuDensity() {
796 return getDensityFromProperty("qemu.sf.lcd_density"); }
797 static int getBuildDensity() {
798 return getDensityFromProperty("ro.sf.lcd_density"); }
799 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700800
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700802
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 DisplayInfo info = DisplayInfo();
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 float xdpi = hwConfig->getDpiX();
809 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810
811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
812 // The density of the device is provided by a build property
813 float density = Density::getBuildDensity() / 160.0f;
814 if (density == 0) {
815 // the build doesn't provide a density -- this is wrong!
816 // use xdpi instead
817 ALOGE("ro.sf.lcd_density must be defined as a build property");
818 density = xdpi / 160.0f;
819 }
820 if (Density::getEmuDensity()) {
821 // if "qemu.sf.lcd_density" is specified, it overrides everything
822 xdpi = ydpi = density = Density::getEmuDensity();
823 density /= 160.0f;
824 }
825 info.density = density;
826
827 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800829 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 } else {
831 // TODO: where should this value come from?
832 static const int TV_DENSITY = 213;
833 info.density = TV_DENSITY / 160.0f;
834 info.orientation = 0;
835 }
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 info.xdpi = xdpi;
840 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900842 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843
Andy McFadden91b2ca82014-06-13 14:04:23 -0700844 // This is how far in advance a buffer must be queued for
845 // presentation at a given time. If you want a buffer to appear
846 // on the screen at time N, you must submit the buffer before
847 // (N - presentationDeadline).
848 //
849 // Normally it's one full refresh period (to give SF a chance to
850 // latch the buffer), but this can be reduced by configuring a
851 // DispSync offset. Any additional delays introduced by the hardware
852 // composer or panel must be accounted for here.
853 //
854 // We add an additional 1ms to allow for processing time and
855 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800857 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
859 // All non-virtual displays are currently considered secure.
860 info.secure = true;
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800870 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
876 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
878 return NO_ERROR;
879}
880
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700881int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800882 if (display == nullptr) {
883 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
887 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800888 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700889 return device->getActiveConfig();
890 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700891
Dan Stoza24a42e92015-03-09 10:04:11 -0700892 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
896 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
897 this);
898 int32_t type = hw->getDisplayType();
899 int currentMode = hw->getActiveConfig();
900
901 if (mode == currentMode) {
902 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
903 return;
904 }
905
906 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
907 ALOGW("Trying to set config for virtual display");
908 return;
909 }
910
911 hw->setActiveConfig(mode);
912 getHwComposer().setActiveConfig(type, mode);
913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
916 class MessageSetActiveConfig: public MessageBase {
917 SurfaceFlinger& mFlinger;
918 sp<IBinder> mDisplay;
919 int mMode;
920 public:
921 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
922 int mode) :
923 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
924 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700925 Vector<DisplayInfo> configs;
926 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700927 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700928 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700929 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700931 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700935 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
937 ALOGW("Attempt to set active config = %d for virtual display",
938 mMode);
939 } else {
940 mFlinger.setActiveConfigInternal(hw, mMode);
941 }
942 return true;
943 }
944 };
945 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
946 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700947 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700948}
Michael Wright28f24d02016-07-12 13:30:53 -0700949status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700950 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
952 return BAD_VALUE;
953 }
954
955 if (!display.get()) {
956 return NAME_NOT_FOUND;
957 }
958
959 int32_t type = NAME_NOT_FOUND;
960 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
961 if (display == mBuiltinDisplays[i]) {
962 type = i;
963 break;
964 }
965 }
966
967 if (type < 0) {
968 return type;
969 }
970
Peiyong Lina52f0292018-03-14 17:26:31 -0700971 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700972 {
973 ConditionalLock _l(mStateLock,
974 std::this_thread::get_id() != mMainThreadId);
975 modes = getHwComposer().getColorModes(type);
976 }
Michael Wright28f24d02016-07-12 13:30:53 -0700977 outColorModes->clear();
978 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
979
980 return NO_ERROR;
981}
982
Peiyong Lina52f0292018-03-14 17:26:31 -0700983ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700984 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700985 if (device != nullptr) {
986 return device->getActiveColorMode();
987 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700989}
990
991void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700993 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700995
996 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return;
998 }
999
1000 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1001 ALOGW("Trying to set config for virtual display");
1002 return;
1003 }
1004
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1006 hw->getDisplayType());
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 hw->setActiveColorMode(mode);
1009 getHwComposer().setActiveColorMode(type, mode);
1010}
1011
1012
1013status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 class MessageSetActiveColorMode: public MessageBase {
1016 SurfaceFlinger& mFlinger;
1017 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001019 public:
1020 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001022 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1023 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 mFlinger.getDisplayColorModes(mDisplay, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001028 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1029 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001030 return true;
1031 }
1032 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1033 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001034 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1035 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001036 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001037 ALOGW("Attempt to set active color mode %s %d for virtual display",
1038 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001039 } else {
1040 mFlinger.setActiveColorModeInternal(hw, mMode);
1041 }
1042 return true;
1043 }
1044 };
1045 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1046 postMessageSync(msg);
1047 return NO_ERROR;
1048}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049
Svetoslavd85084b2014-03-20 10:28:31 -07001050status_t SurfaceFlinger::clearAnimationFrameStats() {
1051 Mutex::Autolock _l(mStateLock);
1052 mAnimFrameTracker.clearStats();
1053 return NO_ERROR;
1054}
1055
1056status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1057 Mutex::Autolock _l(mStateLock);
1058 mAnimFrameTracker.getStats(outStats);
1059 return NO_ERROR;
1060}
1061
Dan Stozac4f471e2016-03-24 09:31:08 -07001062status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1063 HdrCapabilities* outCapabilities) const {
1064 Mutex::Autolock _l(mStateLock);
1065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001066 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 if (displayDevice == nullptr) {
1068 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1069 return BAD_VALUE;
1070 }
1071
1072 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001073 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001075 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1076 // insert HDR10 as we will force client composition for HDR10
1077 // layers
1078 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1079 types.push_back(HAL_HDR_HDR10);
1080
1081 *outCapabilities = HdrCapabilities(types,
1082 capabilities->getDesiredMaxLuminance(),
1083 capabilities->getDesiredMaxAverageLuminance(),
1084 capabilities->getDesiredMinLuminance());
1085 } else {
1086 *outCapabilities = std::move(*capabilities);
1087 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 } else {
1089 return BAD_VALUE;
1090 }
1091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
1103 if (enable) {
1104 ALOGV("VSync Injections enabled");
1105 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001106 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001107 mInjectorEventThread =
1108 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 });
1119 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 IPCThreadState* ipc = IPCThreadState::self();
1140 const int pid = ipc->getCallingPid();
1141 const int uid = ipc->getCallingUid();
1142 if ((uid != AID_SHELL) &&
1143 !PermissionCache::checkPermission(sDump, pid, uid)) {
1144 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1145 return PERMISSION_DENIED;
1146 }
1147
1148 // Try to acquire a lock for 1s, fail gracefully
1149 const status_t err = mStateLock.timedLock(s2ns(1));
1150 const bool locked = (err == NO_ERROR);
1151 if (!locked) {
1152 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1153 return TIMED_OUT;
1154 }
1155
1156 outLayers->clear();
1157 mCurrentState.traverseInZOrder([&](Layer* layer) {
1158 outLayers->push_back(layer->getLayerDebugInfo());
1159 });
1160
1161 mStateLock.unlock();
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
1169 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1170 return mSFEventThread->createEventConnection();
1171 } else {
1172 return mEventThread->createEventConnection();
1173 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001174}
1175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177
1178void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001179 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180}
1181
1182void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001183 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184}
1185
1186void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001187 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001191 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001192 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001196 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001197 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001201 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001202 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203 if (res == NO_ERROR) {
1204 msg->wait();
1205 }
1206 return res;
1207}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001210 do {
1211 waitForEvent();
1212 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213}
1214
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215void SurfaceFlinger::enableHardwareVsync() {
1216 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1220 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 Mutex::Autolock _l(mHWVsyncLock);
1227
Jesse Hall948fe0c2013-10-14 12:56:09 -07001228 if (makeAvailable) {
1229 mHWVsyncAvailable = true;
1230 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 // Hardware vsync is not currently available, so abort the resync
1232 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 return;
1234 }
1235
David Sodman105b7dc2017-11-04 20:28:14 -07001236 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238
1239 mPrimaryDispSync.reset();
1240 mPrimaryDispSync.setPeriod(period);
1241
1242 if (!mPrimaryHWVsyncEnabled) {
1243 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1245 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryHWVsyncEnabled = true;
1247 }
1248}
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 Mutex::Autolock _l(mHWVsyncLock);
1252 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1254 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.endResync();
1256 mPrimaryHWVsyncEnabled = false;
1257 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeUnavailable) {
1259 mHWVsyncAvailable = false;
1260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Tim Murray4a4e4a22016-04-19 16:29:23 +00001263void SurfaceFlinger::resyncWithRateLimit() {
1264 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001265
1266 // No explicit locking is needed here since EventThread holds a lock while calling this method
1267 static nsecs_t sLastResyncAttempted = 0;
1268 const nsecs_t now = systemTime();
1269 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271 }
Dan Stoza57164302017-05-08 14:03:54 -07001272 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001273}
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1276 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001277 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001278 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001279 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 return;
1281 }
1282
1283 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001284 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001285 return;
1286 }
1287
Jamie Gennisd1700752013-10-14 12:22:52 -07001288 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 { // Scope for the lock
1291 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001295 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001296
1297 if (needsHwVsync) {
1298 enableHardwareVsync();
1299 } else {
1300 disableHardwareVsync(false);
1301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302}
1303
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001304void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001305 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1306 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001307}
1308
Lloyd Pique715a2c12017-12-14 17:18:08 -08001309void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1310 HWC2::Connection connection) {
1311 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1312 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313
Lloyd Piqueba04e622017-12-14 17:11:26 -08001314 // Ignore events that do not have the right sequenceId.
1315 if (sequenceId != getBE().mComposerSequenceId) {
1316 return;
1317 }
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Only lock if we're not on the main thread. This function is normally
1320 // called on a hwbinder thread, but for the primary display it's called on
1321 // the main thread with the state lock already held, so don't attempt to
1322 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001323 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001324
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001326
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001327 if (std::this_thread::get_id() == mMainThreadId) {
1328 // Process all pending hot plug events immediately if we are on the main thread.
1329 processDisplayHotplugEventsLocked();
1330 }
1331
Lloyd Piqueba04e622017-12-14 17:11:26 -08001332 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001333}
1334
Steven Thomasb02664d2017-07-26 18:48:28 -07001335void SurfaceFlinger::onRefreshReceived(int sequenceId,
1336 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001340 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001341 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001342}
1343
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001347 getHwComposer().setVsyncEnabled(disp,
1348 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001349}
1350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001352void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354 // Clear the drawing state so that the logic inside of
1355 // handleTransactionLocked will fire. It will determine the delta between
1356 // mCurrentState and mDrawingState and re-apply all changes when we make the
1357 // transition.
1358 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001359 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 mDisplays.clear();
1361}
1362
Steven Thomas050b2c82017-03-06 11:45:16 -08001363void SurfaceFlinger::updateVrFlinger() {
1364 if (!mVrFlinger)
1365 return;
1366 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001368 return;
1369 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 ALOGE("Vr flinger is only supported for remote hardware composer"
1373 " service connections. Ignoring request to transition to vr"
1374 " flinger.");
1375 mVrFlingerRequestsDisplay = false;
1376 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 int currentDisplayPowerMode = getDisplayDeviceLocked(
1382 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001389 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001390 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1391 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001392 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
David Sodman105b7dc2017-11-04 20:28:14 -07001394 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1395 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001396
1397 if (vrFlingerRequestsDisplay) {
1398 mVrFlinger->GrantDisplayOwnership();
1399 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
1403 mVisibleRegionsDirty = true;
1404 invalidateHwcGeometry();
1405
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001406 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1408 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1409 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001412 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 const nsecs_t period = activeConfig->getVsyncPeriod();
1414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Use phase of 0 since phase is not known.
1417 // Use latency of 0, which will snap to the ideal latency.
1418 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 android_atomic_or(1, &mRepaintEverything);
1421 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422}
1423
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001425 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001428 bool frameMissed = !mHadClientComposition &&
1429 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 (mPreviousPresentFence->getSignalTime() ==
1431 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001432 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001433 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001434 signalLayerUpdate();
1435 break;
1436 }
1437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001447 // Signal a refresh if a transaction modified the window state,
1448 // a new buffer was latched, or if HWC has requested a full
1449 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 signalRefresh();
1451 }
1452 break;
1453 }
1454 case MessageQueue::REFRESH: {
1455 handleMessageRefresh();
1456 break;
1457 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 }
1459}
1460
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001462 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001464 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468}
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473}
1474
1475void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001477
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001478 mRefreshPending = false;
1479
Pablo Ceballos40845df2016-01-25 17:41:15 -08001480 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001481
Brian Andersond6927fb2016-07-23 23:37:30 -07001482 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001483 rebuildLayerStacks();
1484 setUpHWComposer();
1485 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001486 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001487 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001488 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001489
David Sodman105b7dc2017-11-04 20:28:14 -07001490 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001491
1492 mHadClientComposition = false;
1493 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1494 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1495 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001496 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001497 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001498
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502void SurfaceFlinger::doDebugFlashRegions()
1503{
1504 // is debugging enabled
1505 if (CC_LIKELY(!mDebugRegion))
1506 return;
1507
1508 const bool repaintEverything = mRepaintEverything;
1509 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1510 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001511 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 // transform the dirty region into this screen's coordinate space
1513 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1514 if (!dirtyRegion.isEmpty()) {
1515 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001516 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517
1518 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001520 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001521 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1522
Mathias Agopianda27af92012-09-13 18:17:13 -07001523 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 }
1525 }
1526 }
1527
1528 postFramebuffer();
1529
1530 if (mDebugRegion > 1) {
1531 usleep(mDebugRegion * 1000);
1532 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001533
Dan Stoza9e56aa02015-11-02 13:00:03 -08001534 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001535 auto& displayDevice = mDisplays[displayId];
1536 if (!displayDevice->isDisplayOn()) {
1537 continue;
1538 }
1539
David Sodman105b7dc2017-11-04 20:28:14 -07001540 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1541 ALOGE_IF(result != NO_ERROR,
1542 "prepareFrame for display %zd failed:"
1543 " %d (%s)",
1544 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001545 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546}
1547
Adrian Roos1e1a1282017-11-01 19:05:31 +01001548void SurfaceFlinger::doTracing(const char* where) {
1549 ATRACE_CALL();
1550 ATRACE_NAME(where);
1551 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001552 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001553 }
1554}
1555
Brian Andersond6927fb2016-07-23 23:37:30 -07001556void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001558 ATRACE_CALL();
1559 ALOGV("preComposition");
1560
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001562 mDrawingState.traverseInZOrder([&](Layer* layer) {
1563 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 needExtraInvalidate = true;
1565 }
Robert Carr2047fae2016-11-28 14:09:09 -08001566 });
1567
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568 if (needExtraInvalidate) {
1569 signalLayerUpdate();
1570 }
1571}
1572
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573void SurfaceFlinger::updateCompositorTiming(
1574 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1575 std::shared_ptr<FenceTime>& presentFenceTime) {
1576 // Update queue of past composite+present times and determine the
1577 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001578 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001579 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001580 while (!getBE().mCompositePresentTimes.empty()) {
1581 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582 // Cached values should have been updated before calling this method,
1583 // which helps avoid duplicate syscalls.
1584 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1585 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1586 break;
1587 }
1588 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001589 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 }
1591
1592 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001593 while (getBE().mCompositePresentTimes.size() > 16) {
1594 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001595 }
1596
Brian Andersond0010582017-03-07 13:20:31 -08001597 setCompositorTimingSnapped(
1598 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1599}
1600
1601void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1602 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 // Integer division and modulo round toward 0 not -inf, so we need to
1604 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001605 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1607 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1608
Brian Andersond0010582017-03-07 13:20:31 -08001609 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1610 if (idealLatency <= 0) {
1611 idealLatency = vsyncInterval;
1612 }
1613
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 // Snap the latency to a value that removes scheduling jitter from the
1615 // composition and present times, which often have >1ms of jitter.
1616 // Reducing jitter is important if an app attempts to extrapolate
1617 // something (such as user input) to an accurate diasplay time.
1618 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1619 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001620 nsecs_t bias = vsyncInterval / 2;
1621 int64_t extraVsyncs =
1622 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1623 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1624 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625
David Sodman99974d22017-11-28 12:04:33 -08001626 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1627 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1628 getBE().mCompositorTiming.interval = vsyncInterval;
1629 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630}
1631
1632void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001634 ATRACE_CALL();
1635 ALOGV("postComposition");
1636
Brian Anderson3546a3f2016-07-14 11:51:14 -07001637 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001638 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001639 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001640 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001641 }
1642
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001643 // |mStateLock| not needed as we are on the main thread
1644 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001645
David Sodman73beded2017-11-15 11:56:06 -08001646 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001647 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001648 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001649 glCompositionDoneFenceTime =
1650 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001651 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001652 } else {
1653 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1654 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655
David Sodman73beded2017-11-15 11:56:06 -08001656 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001657 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001658 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001659 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001660
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1662 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1663
1664 // We use the refreshStartTime which might be sampled a little later than
1665 // when we started doing work for this frame, but that should be okay
1666 // since updateCompositorTiming has snapping logic.
1667 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001668 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001669 CompositorTiming compositorTiming;
1670 {
David Sodman99974d22017-11-28 12:04:33 -08001671 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1672 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001673 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674
Robert Carr2047fae2016-11-28 14:09:09 -08001675 mDrawingState.traverseInZOrder([&](Layer* layer) {
1676 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001677 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001678 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001679 recordBufferingStats(layer->getName().string(),
1680 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001681 }
Robert Carr2047fae2016-11-28 14:09:09 -08001682 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001683
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001684 if (presentFenceTime->isValid()) {
1685 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001686 enableHardwareVsync();
1687 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001688 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001689 }
1690 }
1691
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001692 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001693 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001694 enableHardwareVsync();
1695 }
1696 }
1697
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001698 if (mAnimCompositionPending) {
1699 mAnimCompositionPending = false;
1700
Brian Anderson4e606e32017-03-16 15:34:57 -07001701 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001702 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001704 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001705 // The HWC doesn't support present fences, so use the refresh
1706 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001708 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001709 mAnimFrameTracker.setActualPresentTime(presentTime);
1710 }
1711 mAnimFrameTracker.advanceFrame();
1712 }
Dan Stozab90cf072015-03-05 11:05:59 -08001713
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001714 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1715 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001716 return;
1717 }
1718
1719 nsecs_t currentTime = systemTime();
1720 if (mHasPoweredOff) {
1721 mHasPoweredOff = false;
1722 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001723 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001724 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001725 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1726 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001727 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001728 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001729 }
David Sodman4a36e932017-11-07 14:29:47 -08001730 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001731 }
David Sodman4a36e932017-11-07 14:29:47 -08001732 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001733}
1734
1735void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 ATRACE_CALL();
1737 ALOGV("rebuildLayerStacks");
1738
Mathias Agopiancd60f992012-08-16 16:28:27 -07001739 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001740 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001741 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001742 mVisibleRegionsDirty = false;
1743 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001744
Jeff Sharkey76488112017-02-27 14:15:18 -07001745 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1746 Region opaqueRegion;
1747 Region dirtyRegion;
1748 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001749 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1751 const Transform& tr(displayDevice->getTransform());
1752 const Rect bounds(displayDevice->getBounds());
1753 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001754 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001755
Jeff Sharkey76488112017-02-27 14:15:18 -07001756 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001757 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001758 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1759 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 Region drawRegion(tr.transform(
1761 layer->visibleNonTransparentRegion));
1762 drawRegion.andSelf(bounds);
1763 if (!drawRegion.isEmpty()) {
1764 layersSortedByZ.add(layer);
1765 } else {
1766 // Clear out the HWC layer if this layer was
1767 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001768 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001769 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001771 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001772 // WM changes displayDevice->layerStack upon sleep/awake.
1773 // Here we make sure we delete the HWC layers even if
1774 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001775 hwcLayerDestroyed = layer->destroyHwcLayer(
1776 displayDevice->getHwcDisplayId());
1777 }
1778
1779 // If a layer is not going to get a release fence because
1780 // it is invisible, but it is also going to release its
1781 // old buffer, add it to the list of layers needing
1782 // fences.
1783 if (hwcLayerDestroyed) {
1784 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1785 mLayersWithQueuedFrames.cend(), layer);
1786 if (found != mLayersWithQueuedFrames.cend()) {
1787 layersNeedingFences.add(layer);
1788 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001789 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001790 });
1791 }
1792 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001793 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001794 displayDevice->undefinedRegion.set(bounds);
1795 displayDevice->undefinedRegion.subtractSelf(
1796 tr.transform(opaqueRegion));
1797 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001798 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001799 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001800}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001801
Romain Guy0147a172017-06-01 13:53:56 -07001802mat4 SurfaceFlinger::computeSaturationMatrix() const {
1803 if (mSaturation == 1.0f) {
1804 return mat4();
1805 }
1806
1807 // Rec.709 luma coefficients
1808 float3 luminance{0.213f, 0.715f, 0.072f};
1809 luminance *= 1.0f - mSaturation;
1810 return mat4(
1811 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1812 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1813 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1814 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1815 );
1816}
1817
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001818// pickColorMode translates a given dataspace into the best available color mode.
1819// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001820ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001821 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001822 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001823 }
1824
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001825 switch (dataSpace) {
1826 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1827 // system expects.
1828 case HAL_DATASPACE_UNKNOWN:
1829 case HAL_DATASPACE_SRGB:
1830 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001831 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001832 break;
1833
1834 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001835 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001836 break;
1837
1838 default:
1839 // TODO (courtneygo): Do we want to assert an error here?
1840 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1841 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001842 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001843 break;
1844 }
1845}
1846
Romain Guy0147a172017-06-01 13:53:56 -07001847android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001848 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001849 // Only support sRGB and Display-P3 right now.
1850 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1851 return HAL_DATASPACE_DISPLAY_P3;
1852 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001853 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1854 return HAL_DATASPACE_DISPLAY_P3;
1855 }
1856 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1857 return HAL_DATASPACE_DISPLAY_P3;
1858 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001859 if (!hasHdr) {
1860 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1861 return HAL_DATASPACE_DISPLAY_P3;
1862 }
1863 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1864 return HAL_DATASPACE_DISPLAY_P3;
1865 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001866 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001867
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001868 return HAL_DATASPACE_V0_SRGB;
1869}
1870
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 ATRACE_CALL();
1873 ALOGV("setUpHWComposer");
1874
Jesse Hall028dc8f2013-08-20 16:35:32 -07001875 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001876 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1877 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1878 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1879
1880 // If nothing has changed (!dirty), don't recompose.
1881 // If something changed, but we don't currently have any visible layers,
1882 // and didn't when we last did a composition, then skip it this time.
1883 // The second rule does two things:
1884 // - When all layers are removed from a display, we'll emit one black
1885 // frame, then nothing more until we get new layers.
1886 // - When a display is created with a private layer stack, we won't
1887 // emit any black frames until a layer is added to the layer stack.
1888 bool mustRecompose = dirty && !(empty && wasEmpty);
1889
1890 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1891 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1892 mustRecompose ? "doing" : "skipping",
1893 dirty ? "+" : "-",
1894 empty ? "+" : "-",
1895 wasEmpty ? "+" : "-");
1896
Dan Stoza71433162014-02-04 16:22:36 -08001897 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001898
1899 if (mustRecompose) {
1900 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1901 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001902 }
1903
Dan Stoza9e56aa02015-11-02 13:00:03 -08001904 // build the h/w work list
1905 if (CC_UNLIKELY(mGeometryInvalid)) {
1906 mGeometryInvalid = false;
1907 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1908 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1909 const auto hwcId = displayDevice->getHwcDisplayId();
1910 if (hwcId >= 0) {
1911 const Vector<sp<Layer>>& currentLayers(
1912 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001913 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001914 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001916 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001919 }
1920 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001921
Robert Carrae060832016-11-28 10:51:00 -08001922 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001923 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001925 }
1926 }
1927 }
1928 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 }
Riley Andrews03414a12014-07-01 14:22:59 -07001930
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001931
Romain Guy0147a172017-06-01 13:53:56 -07001932 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001933
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 // Set the per-frame data
1935 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1936 auto& displayDevice = mDisplays[displayId];
1937 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001938
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 if (hwcId < 0) {
1940 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001941 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001942 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001943 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001944 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1945 "display %zd: %d", displayId, result);
1946 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001948 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1949 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001950 !displayDevice->getHdrSupport()) {
1951 layer->forceClientComposition(hwcId);
1952 }
1953
chaviwc9232ed2017-11-14 15:31:15 -08001954 if (layer->getForceClientComposition(hwcId)) {
1955 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1956 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1957 continue;
1958 }
1959
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960 layer->setPerFrameData(displayDevice);
1961 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001962
1963 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001964 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001965 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1966
1967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001968 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1969 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001970 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1971 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1972 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1973 }
1974 newColorMode = pickColorMode(newDataSpace);
1975
Thierry Strudel2924d012017-08-14 15:19:37 -07001976 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001977 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001978 }
1979
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001980 mPreviousColorMatrix = colorMatrix;
1981
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001983 auto& displayDevice = mDisplays[displayId];
1984 if (!displayDevice->isDisplayOn()) {
1985 continue;
1986 }
1987
David Sodman105b7dc2017-11-04 20:28:14 -07001988 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1990 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001991 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001992}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001993
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994void SurfaceFlinger::doComposition() {
1995 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 ALOGV("doComposition");
1997
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001998 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001999 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002000 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002001 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002 // transform the dirty region into this screen's coordinate space
2003 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002004
2005 // repaint the framebuffer (if needed)
2006 doDisplayComposition(hw, dirtyRegion);
2007
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002009 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002010 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002011 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002013}
2014
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015void SurfaceFlinger::postFramebuffer()
2016{
Mathias Agopian841cde52012-03-01 15:44:37 -08002017 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002019
Mathias Agopiana44b0412011-10-16 18:46:35 -07002020 const nsecs_t now = systemTime();
2021 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002022
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2024 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002025 if (!displayDevice->isDisplayOn()) {
2026 continue;
2027 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 const auto hwcId = displayDevice->getHwcDisplayId();
2029 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002030 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002031 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002032 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002033 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002035 // The layer buffer from the previous frame (if any) is released
2036 // by HWC only when the release fence from this frame (if any) is
2037 // signaled. Always get the release fence from HWC first.
2038 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002039 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002040
2041 // If the layer was client composited in the previous frame, we
2042 // need to merge with the previous client target acquire fence.
2043 // Since we do not track that, always merge with the current
2044 // client target acquire fence when it is available, even though
2045 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002047 releaseFence = Fence::merge("LayerRelease", releaseFence,
2048 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002049 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002050
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 layer->onLayerDisplayed(releaseFence);
2052 }
Chia-I Wu83806892017-11-16 10:50:20 -08002053
2054 // We've got a list of layers needing fences, that are disjoint with
2055 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2056 // supply them with the present fence.
2057 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002058 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002059 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2060 layer->onLayerDisplayed(presentFence);
2061 }
2062 }
2063
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002065 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002066 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002067 }
2068
Mathias Agopiana44b0412011-10-16 18:46:35 -07002069 mLastSwapBufferTime = systemTime() - now;
2070 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002071
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002072 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002073 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2074 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2075 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2076 logFrameStats();
2077 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002078 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079}
2080
Mathias Agopian87baae12012-07-31 12:38:26 -07002081void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082{
Mathias Agopian841cde52012-03-01 15:44:37 -08002083 ATRACE_CALL();
2084
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002085 // here we keep a copy of the drawing state (that is the state that's
2086 // going to be overwritten by handleTransactionLocked()) outside of
2087 // mStateLock so that the side-effects of the State assignment
2088 // don't happen with mStateLock held (which can cause deadlocks).
2089 State drawingState(mDrawingState);
2090
Mathias Agopianca4d3602011-05-19 15:38:14 -07002091 Mutex::Autolock _l(mStateLock);
2092 const nsecs_t now = systemTime();
2093 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002094
Mathias Agopianca4d3602011-05-19 15:38:14 -07002095 // Here we're guaranteed that some transaction flags are set
2096 // so we can call handleTransactionLocked() unconditionally.
2097 // We call getTransactionFlags(), which will also clear the flags,
2098 // with mStateLock held to guarantee that mCurrentState won't change
2099 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002100
Mathias Agopiane57f2922012-08-09 16:29:12 -07002101 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002103
Mathias Agopianca4d3602011-05-19 15:38:14 -07002104 mLastTransactionTime = systemTime() - now;
2105 mDebugInTransaction = 0;
2106 invalidateHwcGeometry();
2107 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002108}
2109
Lloyd Pique715a2c12017-12-14 17:18:08 -08002110DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002111 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002112 // Figure out whether the event is for the primary display or an
2113 // external display by matching the Hwc display id against one for a
2114 // connected display. If we did not find a match, we then check what
2115 // displays are not already connected to determine the type. If we don't
2116 // have a connected primary display, we assume the new display is meant to
2117 // be the primary display, and then if we don't have an external display,
2118 // we assume it is that.
2119 const auto primaryDisplayId =
2120 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2121 const auto externalDisplayId =
2122 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2123 if (primaryDisplayId && primaryDisplayId == display) {
2124 return DisplayDevice::DISPLAY_PRIMARY;
2125 } else if (externalDisplayId && externalDisplayId == display) {
2126 return DisplayDevice::DISPLAY_EXTERNAL;
2127 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2128 return DisplayDevice::DISPLAY_PRIMARY;
2129 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2130 return DisplayDevice::DISPLAY_EXTERNAL;
2131 }
2132
2133 return DisplayDevice::DISPLAY_ID_INVALID;
2134}
2135
Lloyd Piqueba04e622017-12-14 17:11:26 -08002136void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2137 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002138 auto displayType = determineDisplayType(event.display, event.connection);
2139 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2140 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2141 continue;
2142 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002143
2144 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2145 ALOGE("External displays are not supported by the vr hardware composer.");
2146 continue;
2147 }
2148
Lloyd Pique715a2c12017-12-14 17:18:08 -08002149 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002150
2151 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002152 if (!mBuiltinDisplays[displayType].get()) {
2153 ALOGV("Creating built in display %d", displayType);
2154 mBuiltinDisplays[displayType] = new BBinder();
2155 // All non-virtual displays are currently considered secure.
2156 DisplayDeviceState info(displayType, true);
2157 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2158 "Built-in Screen" : "External Screen";
2159 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002160 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002161 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002162 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002163 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002164
Lloyd Piquefcd86612017-12-14 17:15:36 -08002165 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2166 if (idx >= 0) {
2167 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002168 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002169 mCurrentState.displays.removeItemsAt(idx);
2170 }
2171 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002172 }
2173
2174 processDisplayChangesLocked();
2175 }
2176
2177 mPendingHotplugEvents.clear();
2178}
2179
Lloyd Pique09594832018-01-22 17:48:03 -08002180sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2181 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2182 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2183 bool hasWideColorSupport = false;
2184 if (hasWideColorDisplay) {
2185 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2186 for (ColorMode colorMode : modes) {
2187 switch (colorMode) {
2188 case ColorMode::DISPLAY_P3:
2189 case ColorMode::ADOBE_RGB:
2190 case ColorMode::DCI_P3:
2191 hasWideColorSupport = true;
2192 break;
2193 default:
2194 break;
2195 }
2196 }
2197 }
2198
2199 bool hasHdrSupport = false;
2200 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2201 getHwComposer().getHdrCapabilities(state.type);
2202 if (hdrCapabilities) {
2203 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2204 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2205 hasHdrSupport = iter != types.cend();
2206 }
2207
2208 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2209 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2210
2211 /*
2212 * Create our display's surface
2213 */
2214 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2215 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2216 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2217 renderSurface->setNativeWindow(nativeWindow.get());
2218 const int displayWidth = renderSurface->queryWidth();
2219 const int displayHeight = renderSurface->queryHeight();
2220
2221 // Make sure that composition can never be stalled by a virtual display
2222 // consumer that isn't processing buffers fast enough. We have to do this
2223 // in two places:
2224 // * Here, in case the display is composed entirely by HWC.
2225 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2226 // window's swap interval in eglMakeCurrent, so they'll override the
2227 // interval we set here.
2228 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2229 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2230 }
2231
2232 // virtual displays are always considered enabled
2233 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2234 : HWC_POWER_MODE_OFF;
2235
2236 sp<DisplayDevice> hw =
2237 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2238 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2239 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2240
2241 if (maxFrameBufferAcquiredBuffers >= 3) {
2242 nativeWindowSurface->preallocateBuffers();
2243 }
2244
2245 ColorMode defaultColorMode = ColorMode::NATIVE;
2246 if (hasWideColorSupport) {
2247 defaultColorMode = ColorMode::SRGB;
2248 }
2249 setActiveColorModeInternal(hw, defaultColorMode);
2250 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2251 hw->setLayerStack(state.layerStack);
2252 hw->setProjection(state.orientation, state.viewport, state.frame);
2253 hw->setDisplayName(state.displayName);
2254
2255 return hw;
2256}
2257
Lloyd Pique347200f2017-12-14 17:00:15 -08002258void SurfaceFlinger::processDisplayChangesLocked() {
2259 // here we take advantage of Vector's copy-on-write semantics to
2260 // improve performance by skipping the transaction entirely when
2261 // know that the lists are identical
2262 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2263 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2264 if (!curr.isIdenticalTo(draw)) {
2265 mVisibleRegionsDirty = true;
2266 const size_t cc = curr.size();
2267 size_t dc = draw.size();
2268
2269 // find the displays that were removed
2270 // (ie: in drawing state but not in current state)
2271 // also handle displays that changed
2272 // (ie: displays that are in both lists)
2273 for (size_t i = 0; i < dc;) {
2274 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2275 if (j < 0) {
2276 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002277 // Call makeCurrent() on the primary display so we can
2278 // be sure that nothing associated with this display
2279 // is current.
2280 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2281 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2282 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2283 if (hw != nullptr) hw->disconnect(getHwComposer());
2284 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2285 mEventThread->onHotplugReceived(draw[i].type, false);
2286 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002287 } else {
2288 // this display is in both lists. see if something changed.
2289 const DisplayDeviceState& state(curr[j]);
2290 const wp<IBinder>& display(curr.keyAt(j));
2291 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2292 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2293 if (state_binder != draw_binder) {
2294 // changing the surface is like destroying and
2295 // recreating the DisplayDevice, so we just remove it
2296 // from the drawing state, so that it get re-added
2297 // below.
2298 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2299 if (hw != nullptr) hw->disconnect(getHwComposer());
2300 mDisplays.removeItem(display);
2301 mDrawingState.displays.removeItemsAt(i);
2302 dc--;
2303 // at this point we must loop to the next item
2304 continue;
2305 }
2306
2307 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2308 if (disp != nullptr) {
2309 if (state.layerStack != draw[i].layerStack) {
2310 disp->setLayerStack(state.layerStack);
2311 }
2312 if ((state.orientation != draw[i].orientation) ||
2313 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2314 disp->setProjection(state.orientation, state.viewport, state.frame);
2315 }
2316 if (state.width != draw[i].width || state.height != draw[i].height) {
2317 disp->setDisplaySize(state.width, state.height);
2318 }
2319 }
2320 }
2321 ++i;
2322 }
2323
2324 // find displays that were added
2325 // (ie: in current state but not in drawing state)
2326 for (size_t i = 0; i < cc; i++) {
2327 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2328 const DisplayDeviceState& state(curr[i]);
2329
2330 sp<DisplaySurface> dispSurface;
2331 sp<IGraphicBufferProducer> producer;
2332 sp<IGraphicBufferProducer> bqProducer;
2333 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002334 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002335
2336 int32_t hwcId = -1;
2337 if (state.isVirtualDisplay()) {
2338 // Virtual displays without a surface are dormant:
2339 // they have external state (layer stack, projection,
2340 // etc.) but no internal state (i.e. a DisplayDevice).
2341 if (state.surface != nullptr) {
2342 // Allow VR composer to use virtual displays.
2343 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2344 int width = 0;
2345 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2346 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2347 int height = 0;
2348 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2349 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2350 int intFormat = 0;
2351 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2352 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2353 auto format = static_cast<android_pixel_format_t>(intFormat);
2354
2355 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2356 }
2357
2358 // TODO: Plumb requested format back up to consumer
2359
2360 sp<VirtualDisplaySurface> vds =
2361 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2362 bqProducer, bqConsumer,
2363 state.displayName);
2364
2365 dispSurface = vds;
2366 producer = vds;
2367 }
2368 } else {
2369 ALOGE_IF(state.surface != nullptr,
2370 "adding a supported display, but rendering "
2371 "surface is provided (%p), ignoring it",
2372 state.surface.get());
2373
2374 hwcId = state.type;
2375 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2376 producer = bqProducer;
2377 }
2378
2379 const wp<IBinder>& display(curr.keyAt(i));
2380 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002381 mDisplays.add(display,
2382 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2383 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002384 if (!state.isVirtualDisplay()) {
2385 mEventThread->onHotplugReceived(state.type, true);
2386 }
2387 }
2388 }
2389 }
2390 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002391
2392 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002393}
2394
Mathias Agopian87baae12012-07-31 12:38:26 -07002395void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002396{
Dan Stoza7dde5992015-05-22 09:51:44 -07002397 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002398 mCurrentState.traverseInZOrder([](Layer* layer) {
2399 layer->notifyAvailableFrames();
2400 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002401
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402 /*
2403 * Traversal of the children
2404 * (perform the transaction for each of them if needed)
2405 */
2406
Mathias Agopian3559b072012-08-15 13:46:03 -07002407 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002408 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002410 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411
2412 const uint32_t flags = layer->doTransaction(0);
2413 if (flags & Layer::eVisibleRegion)
2414 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002415 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002416 }
2417
2418 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002419 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420 */
2421
Mathias Agopiane57f2922012-08-09 16:29:12 -07002422 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002423 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002424 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002425 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426
Mathias Agopian84300952012-11-21 16:02:13 -08002427 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2428 // The transform hint might have changed for some layers
2429 // (either because a display has changed, or because a layer
2430 // as changed).
2431 //
2432 // Walk through all the layers in currentLayers,
2433 // and update their transform hint.
2434 //
2435 // If a layer is visible only on a single display, then that
2436 // display is used to calculate the hint, otherwise we use the
2437 // default display.
2438 //
2439 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2440 // the hint is set before we acquire a buffer from the surface texture.
2441 //
2442 // NOTE: layer transactions have taken place already, so we use their
2443 // drawing state. However, SurfaceFlinger's own transaction has not
2444 // happened yet, so we must use the current state layer list
2445 // (soon to become the drawing state list).
2446 //
2447 sp<const DisplayDevice> disp;
2448 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002449 bool first = true;
2450 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002451 // NOTE: we rely on the fact that layers are sorted by
2452 // layerStack first (so we don't have to traverse the list
2453 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002454 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002455 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002456 currentlayerStack = layerStack;
2457 // figure out if this layerstack is mirrored
2458 // (more than one display) if so, pick the default display,
2459 // if not, pick the only display it's on.
2460 disp.clear();
2461 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2462 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002463 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002464 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002465 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002466 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002467 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002468 break;
2469 }
2470 }
2471 }
2472 }
Chet Haase91d25932013-04-11 15:24:55 -07002473
Robert Carr56a0b9a2017-12-04 16:06:13 -08002474 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002475 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002476 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2477 // redraw after transform hint changes. See bug 8508397.
2478
2479 // could be null when this layer is using a layerStack
2480 // that is not visible on any display. Also can occur at
2481 // screen off/on times.
2482 disp = getDefaultDisplayDeviceLocked();
2483 }
2484 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002485 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002486 if (disp != nullptr) {
2487 layer->updateTransformHint(disp);
2488 }
Robert Carr2047fae2016-11-28 14:09:09 -08002489
2490 first = false;
2491 });
Mathias Agopian84300952012-11-21 16:02:13 -08002492 }
2493
2494
Mathias Agopian3559b072012-08-15 13:46:03 -07002495 /*
2496 * Perform our own transaction if needed
2497 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002498
2499 if (mLayersAdded) {
2500 mLayersAdded = false;
2501 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002502 mVisibleRegionsDirty = true;
2503 }
2504
2505 // some layers might have been removed, so
2506 // we need to update the regions they're exposing.
2507 if (mLayersRemoved) {
2508 mLayersRemoved = false;
2509 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002510 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002512 // this layer is not visible anymore
2513 // TODO: we could traverse the tree from front to back and
2514 // compute the actual visible region
2515 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002516 Region visibleReg;
2517 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002518 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002519 }
Robert Carr2047fae2016-11-28 14:09:09 -08002520 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521 }
2522
2523 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002524
2525 updateCursorAsync();
2526}
2527
2528void SurfaceFlinger::updateCursorAsync()
2529{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002530 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2531 auto& displayDevice = mDisplays[displayId];
2532 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002533 continue;
2534 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002535
2536 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2537 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002538 }
2539 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002540}
2541
2542void SurfaceFlinger::commitTransaction()
2543{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002544 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002545 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002546 for (const auto& l : mLayersPendingRemoval) {
2547 recordBufferingStats(l->getName().string(),
2548 l->getOccupancyHistory(true));
2549 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002550 }
2551 mLayersPendingRemoval.clear();
2552 }
2553
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002554 // If this transaction is part of a window animation then the next frame
2555 // we composite should be considered an animation as well.
2556 mAnimCompositionPending = mAnimTransactionPending;
2557
Mathias Agopian4fec8732012-06-29 14:12:52 -07002558 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002559 mDrawingState.traverseInZOrder([](Layer* layer) {
2560 layer->commitChildList();
2561 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002562 mTransactionPending = false;
2563 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002564 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565}
2566
Chia-I Wuab0c3192017-08-01 11:29:00 -07002567void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002568 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569{
Mathias Agopian841cde52012-03-01 15:44:37 -08002570 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002571 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002572
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 Region aboveOpaqueLayers;
2574 Region aboveCoveredLayers;
2575 Region dirty;
2576
Mathias Agopian87baae12012-07-31 12:38:26 -07002577 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002581 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582
Jesse Hall01e29052013-02-19 16:13:35 -08002583 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002584 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002585 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002586
Mathias Agopianab028732010-03-16 16:41:46 -07002587 /*
2588 * opaqueRegion: area of a surface that is fully opaque.
2589 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002591
2592 /*
2593 * visibleRegion: area of a surface that is visible on screen
2594 * and not fully transparent. This is essentially the layer's
2595 * footprint minus the opaque regions above it.
2596 * Areas covered by a translucent surface are considered visible.
2597 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002599
2600 /*
2601 * coveredRegion: area of a surface that is covered by all
2602 * visible regions above it (which includes the translucent areas).
2603 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002605
Jesse Halla8026d22012-09-25 13:25:04 -07002606 /*
2607 * transparentRegion: area of a surface that is hinted to be completely
2608 * transparent. This is only used to tell when the layer has no visible
2609 * non-transparent regions and can be removed from the layer list. It
2610 * does not affect the visibleRegion of this layer or any layers
2611 * beneath it. The hint may not be correct if apps don't respect the
2612 * SurfaceView restrictions (which, sadly, some don't).
2613 */
2614 Region transparentRegion;
2615
Mathias Agopianab028732010-03-16 16:41:46 -07002616
2617 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002618 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002619 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002620 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002623 if (!visibleRegion.isEmpty()) {
2624 // Remove the transparent area from the visible region
2625 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002626 if (tr.preserveRects()) {
2627 // transform the transparent region
2628 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002629 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002630 // transformation too complex, can't do the
2631 // transparent region optimization.
2632 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002633 }
Mathias Agopianab028732010-03-16 16:41:46 -07002634 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635
Mathias Agopianab028732010-03-16 16:41:46 -07002636 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002638 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002639 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2640 // the opaque region is the layer's footprint
2641 opaqueRegion = visibleRegion;
2642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 }
2644 }
2645
Robert Carre5f4f692018-01-12 13:12:28 -08002646 if (visibleRegion.isEmpty()) {
2647 layer->clearVisibilityRegions();
2648 return;
2649 }
2650
Mathias Agopianab028732010-03-16 16:41:46 -07002651 // Clip the covered region to the visible region
2652 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2653
2654 // Update aboveCoveredLayers for next (lower) layer
2655 aboveCoveredLayers.orSelf(visibleRegion);
2656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 // subtract the opaque region covered by the layers above us
2658 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659
2660 // compute this layer's dirty region
2661 if (layer->contentDirty) {
2662 // we need to invalidate the whole region
2663 dirty = visibleRegion;
2664 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002665 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 layer->contentDirty = false;
2667 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002668 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002669 * the exposed region consists of two components:
2670 * 1) what's VISIBLE now and was COVERED before
2671 * 2) what's EXPOSED now less what was EXPOSED before
2672 *
2673 * note that (1) is conservative, we start with the whole
2674 * visible region but only keep what used to be covered by
2675 * something -- which mean it may have been exposed.
2676 *
2677 * (2) handles areas that were not covered by anything but got
2678 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002679 */
Mathias Agopianab028732010-03-16 16:41:46 -07002680 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002681 const Region oldVisibleRegion = layer->visibleRegion;
2682 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002683 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2684 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 }
2686 dirty.subtractSelf(aboveOpaqueLayers);
2687
2688 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002689 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690
Mathias Agopianab028732010-03-16 16:41:46 -07002691 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002693
Jesse Halla8026d22012-09-25 13:25:04 -07002694 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 layer->setVisibleRegion(visibleRegion);
2696 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002697 layer->setVisibleNonTransparentRegion(
2698 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002699 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700
Mathias Agopian87baae12012-07-31 12:38:26 -07002701 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702}
2703
Chia-I Wuab0c3192017-08-01 11:29:00 -07002704void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002705 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002706 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002707 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002708 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002709 }
2710 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002711}
2712
Dan Stoza6b9454d2014-11-07 16:00:59 -08002713bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715 ALOGV("handlePageFlip");
2716
Brian Andersond6927fb2016-07-23 23:37:30 -07002717 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002720 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002721 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002722
2723 // Store the set of layers that need updates. This set must not change as
2724 // buffers are being latched, as this could result in a deadlock.
2725 // Example: Two producers share the same command stream and:
2726 // 1.) Layer 0 is latched
2727 // 2.) Layer 0 gets a new frame
2728 // 2.) Layer 1 gets a new frame
2729 // 3.) Layer 1 is latched.
2730 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2731 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002732 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002733 if (layer->hasQueuedFrame()) {
2734 frameQueued = true;
2735 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002736 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002737 } else {
2738 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002739 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002740 } else {
2741 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002742 }
Robert Carr2047fae2016-11-28 14:09:09 -08002743 });
2744
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002746 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002747 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002748 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002749 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002750 newDataLatched = true;
2751 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002752 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002753
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002754 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002755
2756 // If we will need to wake up at some time in the future to deal with a
2757 // queued frame that shouldn't be displayed during this vsync period, wake
2758 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002759 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002760 signalLayerUpdate();
2761 }
2762
2763 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002764 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765}
2766
Mathias Agopianad456f92011-01-13 17:53:01 -08002767void SurfaceFlinger::invalidateHwcGeometry()
2768{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002770}
2771
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002772
Fabien Sanglard830b8472016-11-30 16:35:58 -08002773void SurfaceFlinger::doDisplayComposition(
2774 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002775 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776{
Dan Stoza71433162014-02-04 16:22:36 -08002777 // We only need to actually compose the display if:
2778 // 1) It is being handled by hardware composer, which may need this to
2779 // keep its virtual display state machine in sync, or
2780 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002781 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002782 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002784 return;
2785 }
2786
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002788 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002789
2790 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002791 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792}
2793
Chia-I Wub02087d2017-11-09 10:19:54 -08002794bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002795{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002797
Chia-I Wub02087d2017-11-09 10:19:54 -08002798 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002799 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002801
2802 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002803 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2804 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002805 if (applyColorMatrix) {
2806 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2807 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2808 }
2809
David Sodman105b7dc2017-11-04 20:28:14 -07002810 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 if (hasClientComposition) {
2812 ALOGV("hasClientComposition");
2813
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002814 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002815 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002816 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002817 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2818 }
2819 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2820
Chia-I Wu7f402902017-11-09 12:51:10 -08002821 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002822 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002824 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002825
2826 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002827 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002828 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2829 }
2830 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002831 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002832
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002833 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002834 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002836 // when using overlays, we assume a fully transparent framebuffer
2837 // NOTE: we could reduce how much we need to clear, for instance
2838 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002839 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002840 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002841 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002842 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002843 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002844 // we're left with the letterbox region
2845 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002847
2848 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002850
Mathias Agopianb9494d52012-04-18 02:28:45 -07002851 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002852 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002853 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002855 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002856 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002857
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002859 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002860 // scissor on the main display. It should never be needed
2861 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002862 const Rect& bounds(displayDevice->getBounds());
2863 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002864 if (scissor != bounds) {
2865 // scissor doesn't match the screen's dimensions, so we
2866 // need to clear everything outside of it and enable
2867 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002868
Mathias Agopianf45c5102012-10-24 16:29:17 -07002869 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002871 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002872 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002873 }
2874 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002875 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002876
Mathias Agopian85d751c2012-08-29 16:59:24 -07002877 /*
2878 * and then, render the layers targeted at the framebuffer
2879 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002880
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 ALOGV("Rendering client layers");
2882 const Transform& displayTransform = displayDevice->getTransform();
2883 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002884 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 bool firstLayer = true;
2886 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002887 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 displayTransform.transform(layer->visibleRegion)));
2889 ALOGV("Layer: %s", layer->getName().string());
2890 ALOGV(" Composition type: %s",
2891 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002892 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 switch (layer->getCompositionType(hwcId)) {
2894 case HWC2::Composition::Cursor:
2895 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002896 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002898 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002899 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002900 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002901 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002902 // never clear the very first layer since we're
2903 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002904 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002905 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002906 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002907 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002909 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002910 break;
2911 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002913 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 } else {
2916 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002917 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002919 }
2920 } else {
2921 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002923 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002924 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002925 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002926 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002927 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002928 }
2929 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002930
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002931 if (applyColorMatrix) {
2932 getRenderEngine().setupColorTransform(oldColorMatrix);
2933 }
2934
Mathias Agopianf45c5102012-10-24 16:29:17 -07002935 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002936 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002937 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938}
2939
Fabien Sanglard830b8472016-11-30 16:35:58 -08002940void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2941 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002942 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002943 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944}
2945
Dan Stoza7d89d062015-04-30 13:29:25 -07002946status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002947 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002948 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002949 const sp<Layer>& lbc,
2950 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002951{
Dan Stoza7d89d062015-04-30 13:29:25 -07002952 // add this layer to the current state list
2953 {
2954 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002956 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2957 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002958 return NO_MEMORY;
2959 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002960 if (parent == nullptr) {
2961 mCurrentState.layersSortedByZ.add(lbc);
2962 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002963 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002964 ALOGE("addClientLayer called with a removed parent");
2965 return NAME_NOT_FOUND;
2966 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002967 parent->addChild(lbc);
2968 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002969
Dan Stoza101d8dc2018-02-27 15:42:25 -08002970 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002971 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2972 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2973 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2974 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2975 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976 mLayersAdded = true;
2977 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002978 }
2979
Mathias Agopian96f08192010-06-02 23:28:45 -07002980 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002981 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002982
Dan Stoza7d89d062015-04-30 13:29:25 -07002983 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002984}
2985
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002986status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002987 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002988 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2989}
Robert Carr7f9b8992017-03-10 11:08:39 -08002990
chaviwca27f252018-02-06 16:46:39 -08002991status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2992 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002993 if (layer->isPendingRemoval()) {
2994 return NO_ERROR;
2995 }
2996
Robert Carr1f0a16a2016-10-24 16:27:39 -07002997 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002998 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002999 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003000 if (topLevelOnly) {
3001 return NO_ERROR;
3002 }
3003
Chia-I Wu98f1c102017-05-30 14:54:08 -07003004 sp<Layer> ancestor = p;
3005 while (ancestor->getParent() != nullptr) {
3006 ancestor = ancestor->getParent();
3007 }
3008 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3009 ALOGE("removeLayer called with a layer whose parent has been removed");
3010 return NAME_NOT_FOUND;
3011 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003012
3013 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003014 } else {
3015 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003016 }
3017
Robert Carr136e2f62017-02-08 17:54:29 -08003018 // As a matter of normal operation, the LayerCleaner will produce a second
3019 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3020 // so we will succeed in promoting it, but it's already been removed
3021 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3022 // otherwise something has gone wrong and we are leaking the layer.
3023 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003024 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3025 layer->getName().string(),
3026 (p != nullptr) ? p->getName().string() : "no-parent");
3027 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003028 } else if (index < 0) {
3029 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003030 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003031
Chia-I Wuc6657022017-08-15 11:18:17 -07003032 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003033 mLayersPendingRemoval.add(layer);
3034 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003035 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003036 setTransactionFlags(eTransactionNeeded);
3037 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038}
3039
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003040uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003041 return android_atomic_release_load(&mTransactionFlags);
3042}
3043
Mathias Agopian3f844832013-08-07 21:24:32 -07003044uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3046}
3047
Mathias Agopian3f844832013-08-07 21:24:32 -07003048uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3050 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003051 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 }
3053 return old;
3054}
3055
chaviwca27f252018-02-06 16:46:39 -08003056bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3057 for (const ComposerState& state : states) {
3058 // Here we need to check that the interface we're given is indeed
3059 // one of our own. A malicious client could give us a nullptr
3060 // IInterface, or one of its own or even one of our own but a
3061 // different type. All these situations would cause us to crash.
3062 if (state.client == nullptr) {
3063 return true;
3064 }
3065
3066 sp<IBinder> binder = IInterface::asBinder(state.client);
3067 if (binder == nullptr) {
3068 return true;
3069 }
3070
3071 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3072 return true;
3073 }
3074 }
3075 return false;
3076}
3077
Mathias Agopian8b33f032012-07-24 20:43:54 -07003078void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003079 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003080 const Vector<DisplayState>& displays,
3081 uint32_t flags)
3082{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003083 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003084 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003085 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003086
chaviwca27f252018-02-06 16:46:39 -08003087 if (containsAnyInvalidClientState(states)) {
3088 return;
3089 }
3090
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003091 if (flags & eAnimation) {
3092 // For window updates that are part of an animation we must wait for
3093 // previous animation "frames" to be handled.
3094 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003095 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003096 if (CC_UNLIKELY(err != NO_ERROR)) {
3097 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003098 // caller after a few seconds.
3099 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3100 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003101 mAnimTransactionPending = false;
3102 break;
3103 }
3104 }
3105 }
3106
chaviwca27f252018-02-06 16:46:39 -08003107 for (const DisplayState& display : displays) {
3108 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003109 }
3110
chaviwca27f252018-02-06 16:46:39 -08003111 for (const ComposerState& state : states) {
3112 transactionFlags |= setClientStateLocked(state);
3113 }
3114
3115 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3116 // as destroyed should only occur after setting all other states. This is to allow for a
3117 // child re-parent to happen before marking its original parent as destroyed (which would
3118 // then mark the child as destroyed).
3119 for (const ComposerState& state : states) {
3120 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003121 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003122
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003123 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3124 // anyway. This can be used as a flush mechanism for previous async transactions.
3125 // Empty animation transaction can be used to simulate back-pressure, so also force a
3126 // transaction for empty animation transactions.
3127 if (transactionFlags == 0 &&
3128 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003129 transactionFlags = eTransactionNeeded;
3130 }
3131
Mathias Agopian386aa982011-11-07 21:58:03 -08003132 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003133 if (mInterceptor->isEnabled()) {
3134 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003135 }
Irvel468051e2016-06-13 16:44:44 -07003136
Mathias Agopian386aa982011-11-07 21:58:03 -08003137 // this triggers the transaction
3138 setTransactionFlags(transactionFlags);
3139
3140 // if this is a synchronous transaction, wait for it to take effect
3141 // before returning.
3142 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003143 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003144 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003145 if (flags & eAnimation) {
3146 mAnimTransactionPending = true;
3147 }
3148 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003149 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3150 if (CC_UNLIKELY(err != NO_ERROR)) {
3151 // just in case something goes wrong in SF, return to the
3152 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003153 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3154 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003155 break;
3156 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003157 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 }
3159}
3160
Mathias Agopiane57f2922012-08-09 16:29:12 -07003161uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3162{
Jesse Hall9a143922012-10-04 16:29:19 -07003163 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3164 if (dpyIdx < 0)
3165 return 0;
3166
Mathias Agopiane57f2922012-08-09 16:29:12 -07003167 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003168 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003169 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003170 const uint32_t what = s.what;
3171 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003172 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003173 disp.surface = s.surface;
3174 flags |= eDisplayTransactionNeeded;
3175 }
3176 }
3177 if (what & DisplayState::eLayerStackChanged) {
3178 if (disp.layerStack != s.layerStack) {
3179 disp.layerStack = s.layerStack;
3180 flags |= eDisplayTransactionNeeded;
3181 }
3182 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003183 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003184 if (disp.orientation != s.orientation) {
3185 disp.orientation = s.orientation;
3186 flags |= eDisplayTransactionNeeded;
3187 }
3188 if (disp.frame != s.frame) {
3189 disp.frame = s.frame;
3190 flags |= eDisplayTransactionNeeded;
3191 }
3192 if (disp.viewport != s.viewport) {
3193 disp.viewport = s.viewport;
3194 flags |= eDisplayTransactionNeeded;
3195 }
3196 }
Michael Lentine47e45402014-07-18 15:34:25 -07003197 if (what & DisplayState::eDisplaySizeChanged) {
3198 if (disp.width != s.width) {
3199 disp.width = s.width;
3200 flags |= eDisplayTransactionNeeded;
3201 }
3202 if (disp.height != s.height) {
3203 disp.height = s.height;
3204 flags |= eDisplayTransactionNeeded;
3205 }
3206 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003207 }
3208 return flags;
3209}
3210
chaviwca27f252018-02-06 16:46:39 -08003211uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3212 const layer_state_t& s = composerState.state;
3213 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3214
Mathias Agopian13127d82013-03-05 17:47:11 -08003215 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003216 if (layer == nullptr) {
3217 return 0;
3218 }
3219
3220 if (layer->isPendingRemoval()) {
3221 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3222 return 0;
3223 }
3224
3225 uint32_t flags = 0;
3226
3227 const uint32_t what = s.what;
3228 bool geometryAppliesWithResize =
3229 what & layer_state_t::eGeometryAppliesWithResize;
3230 if (what & layer_state_t::ePositionChanged) {
3231 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3232 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003233 }
chaviw8b3871a2017-11-01 17:41:01 -07003234 }
3235 if (what & layer_state_t::eLayerChanged) {
3236 // NOTE: index needs to be calculated before we update the state
3237 const auto& p = layer->getParent();
3238 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003239 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003240 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241 mCurrentState.layersSortedByZ.removeAt(idx);
3242 mCurrentState.layersSortedByZ.add(layer);
3243 // we need traversal (state changed)
3244 // AND transaction (list changed)
3245 flags |= eTransactionNeeded|eTraversalNeeded;
3246 }
chaviw8b3871a2017-11-01 17:41:01 -07003247 } else {
3248 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003249 flags |= eTransactionNeeded|eTraversalNeeded;
3250 }
3251 }
chaviw8b3871a2017-11-01 17:41:01 -07003252 }
3253 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003254 // NOTE: index needs to be calculated before we update the state
3255 const auto& p = layer->getParent();
3256 if (p == nullptr) {
3257 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3258 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3259 mCurrentState.layersSortedByZ.removeAt(idx);
3260 mCurrentState.layersSortedByZ.add(layer);
3261 // we need traversal (state changed)
3262 // AND transaction (list changed)
3263 flags |= eTransactionNeeded|eTraversalNeeded;
3264 }
3265 } else {
3266 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3267 flags |= eTransactionNeeded|eTraversalNeeded;
3268 }
chaviw8b3871a2017-11-01 17:41:01 -07003269 }
3270 }
3271 if (what & layer_state_t::eSizeChanged) {
3272 if (layer->setSize(s.w, s.h)) {
3273 flags |= eTraversalNeeded;
3274 }
3275 }
3276 if (what & layer_state_t::eAlphaChanged) {
3277 if (layer->setAlpha(s.alpha))
3278 flags |= eTraversalNeeded;
3279 }
3280 if (what & layer_state_t::eColorChanged) {
3281 if (layer->setColor(s.color))
3282 flags |= eTraversalNeeded;
3283 }
3284 if (what & layer_state_t::eMatrixChanged) {
3285 if (layer->setMatrix(s.matrix))
3286 flags |= eTraversalNeeded;
3287 }
3288 if (what & layer_state_t::eTransparentRegionChanged) {
3289 if (layer->setTransparentRegionHint(s.transparentRegion))
3290 flags |= eTraversalNeeded;
3291 }
3292 if (what & layer_state_t::eFlagsChanged) {
3293 if (layer->setFlags(s.flags, s.mask))
3294 flags |= eTraversalNeeded;
3295 }
3296 if (what & layer_state_t::eCropChanged) {
3297 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3298 flags |= eTraversalNeeded;
3299 }
3300 if (what & layer_state_t::eFinalCropChanged) {
3301 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3302 flags |= eTraversalNeeded;
3303 }
3304 if (what & layer_state_t::eLayerStackChanged) {
3305 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3306 // We only allow setting layer stacks for top level layers,
3307 // everything else inherits layer stack from its parent.
3308 if (layer->hasParent()) {
3309 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3310 layer->getName().string());
3311 } else if (idx < 0) {
3312 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3313 "that also does not appear in the top level layer list. Something"
3314 " has gone wrong.", layer->getName().string());
3315 } else if (layer->setLayerStack(s.layerStack)) {
3316 mCurrentState.layersSortedByZ.removeAt(idx);
3317 mCurrentState.layersSortedByZ.add(layer);
3318 // we need traversal (state changed)
3319 // AND transaction (list changed)
3320 flags |= eTransactionNeeded|eTraversalNeeded;
3321 }
3322 }
3323 if (what & layer_state_t::eDeferTransaction) {
3324 if (s.barrierHandle != nullptr) {
3325 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3326 } else if (s.barrierGbp != nullptr) {
3327 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3328 if (authenticateSurfaceTextureLocked(gbp)) {
3329 const auto& otherLayer =
3330 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3331 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3332 } else {
3333 ALOGE("Attempt to defer transaction to to an"
3334 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003335 }
3336 }
chaviw8b3871a2017-11-01 17:41:01 -07003337 // We don't trigger a traversal here because if no other state is
3338 // changed, we don't want this to cause any more work
3339 }
3340 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003341 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003342 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003343 if (!hadParent) {
3344 mCurrentState.layersSortedByZ.remove(layer);
3345 }
chaviw8b3871a2017-11-01 17:41:01 -07003346 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003347 }
chaviw8b3871a2017-11-01 17:41:01 -07003348 }
3349 if (what & layer_state_t::eReparentChildren) {
3350 if (layer->reparentChildren(s.reparentHandle)) {
3351 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003352 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003353 }
chaviw8b3871a2017-11-01 17:41:01 -07003354 if (what & layer_state_t::eDetachChildren) {
3355 layer->detachChildren();
3356 }
3357 if (what & layer_state_t::eOverrideScalingModeChanged) {
3358 layer->setOverrideScalingMode(s.overrideScalingMode);
3359 // We don't trigger a traversal here because if no other state is
3360 // changed, we don't want this to cause any more work
3361 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 return flags;
3363}
3364
chaviwca27f252018-02-06 16:46:39 -08003365void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3366 const layer_state_t& state = composerState.state;
3367 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3368
3369 sp<Layer> layer(client->getLayerUser(state.surface));
3370 if (layer == nullptr) {
3371 return;
3372 }
3373
3374 if (layer->isPendingRemoval()) {
3375 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3376 return;
3377 }
3378
3379 if (state.what & layer_state_t::eDestroySurface) {
3380 removeLayerLocked(mStateLock, layer);
3381 }
3382}
3383
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003384status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003385 const String8& name,
3386 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003387 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003388 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003389 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003390{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003391 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003392 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003393 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003394 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003395 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003396
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003397 status_t result = NO_ERROR;
3398
3399 sp<Layer> layer;
3400
Cody Northropbc755282017-03-31 12:00:08 -06003401 String8 uniqueName = getUniqueLayerName(name);
3402
Mathias Agopian3165cc22012-08-08 19:42:09 -07003403 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3404 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003405 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003406 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003407 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003408
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409 break;
chaviw13fdc492017-06-27 12:40:18 -07003410 case ISurfaceComposerClient::eFXSurfaceColor:
3411 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003412 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003413 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003414 break;
3415 default:
3416 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003417 break;
3418 }
3419
Dan Stoza7d89d062015-04-30 13:29:25 -07003420 if (result != NO_ERROR) {
3421 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003423
Chia-I Wuab0c3192017-08-01 11:29:00 -07003424 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3425 // TODO b/64227542
3426 if (windowType == 441731) {
3427 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3428 layer->setPrimaryDisplayOnly();
3429 }
3430
Albert Chaulk479c60c2017-01-27 14:21:34 -05003431 layer->setInfo(windowType, ownerUid);
3432
Robert Carr1f0a16a2016-10-24 16:27:39 -07003433 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003434 if (result != NO_ERROR) {
3435 return result;
3436 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003437 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003438
3439 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003440 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003441}
3442
Cody Northropbc755282017-03-31 12:00:08 -06003443String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3444{
3445 bool matchFound = true;
3446 uint32_t dupeCounter = 0;
3447
3448 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3449 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3450
3451 // Loop over layers until we're sure there is no matching name
3452 while (matchFound) {
3453 matchFound = false;
3454 mDrawingState.traverseInZOrder([&](Layer* layer) {
3455 if (layer->getName() == uniqueName) {
3456 matchFound = true;
3457 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3458 }
3459 });
3460 }
3461
3462 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3463
3464 return uniqueName;
3465}
3466
David Sodman0c69cad2017-08-21 12:12:51 -07003467status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003468 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3469 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470{
3471 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003472 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003473 case PIXEL_FORMAT_TRANSPARENT:
3474 case PIXEL_FORMAT_TRANSLUCENT:
3475 format = PIXEL_FORMAT_RGBA_8888;
3476 break;
3477 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003478 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003479 break;
3480 }
3481
David Sodman0c69cad2017-08-21 12:12:51 -07003482 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3483 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003484 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003485 *handle = layer->getHandle();
3486 *gbp = layer->getProducer();
3487 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003489
David Sodman0c69cad2017-08-21 12:12:51 -07003490 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003491 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492}
3493
chaviw13fdc492017-06-27 12:40:18 -07003494status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003495 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003496 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497{
chaviw13fdc492017-06-27 12:40:18 -07003498 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003499 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003500 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003501}
3502
Mathias Agopianac9fa422013-02-11 16:40:36 -08003503status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504{
Robert Carr9524cb32017-02-13 11:32:32 -08003505 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003506 status_t err = NO_ERROR;
3507 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003508 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003509 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003510 err = removeLayer(l);
3511 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3512 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003513 }
3514 return err;
3515}
3516
Mathias Agopian13127d82013-03-05 17:47:11 -08003517status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003518{
Mathias Agopian67106042013-03-14 19:18:13 -07003519 // called by ~LayerCleaner() when all references to the IBinder (handle)
3520 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003521 sp<Layer> l = layer.promote();
3522 if (l == nullptr) {
3523 // The layer has already been removed, carry on
3524 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003525 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003526 // If we have a parent, then we can continue to live as long as it does.
3527 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528}
3529
Mathias Agopianb60314a2012-04-10 22:09:54 -07003530// ---------------------------------------------------------------------------
3531
Andy McFadden13a082e2012-08-24 10:16:42 -07003532void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003533 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003534 Vector<ComposerState> state;
3535 Vector<DisplayState> displays;
3536 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003537 d.what = DisplayState::eDisplayProjectionChanged |
3538 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003539 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003540 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003541 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003542 d.frame.makeInvalid();
3543 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003544 d.width = 0;
3545 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003546 displays.add(d);
3547 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003548 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3549 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003550
David Sodman105b7dc2017-11-04 20:28:14 -07003551 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003552 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003553 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003554
Brian Andersond0010582017-03-07 13:20:31 -08003555 // Use phase of 0 since phase is not known.
3556 // Use latency of 0, which will snap to the ideal latency.
3557 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003558}
3559
3560void SurfaceFlinger::initializeDisplays() {
3561 class MessageScreenInitialized : public MessageBase {
3562 SurfaceFlinger* flinger;
3563 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003564 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003565 virtual bool handler() {
3566 flinger->onInitializeDisplays();
3567 return true;
3568 }
3569 };
3570 sp<MessageBase> msg = new MessageScreenInitialized(this);
3571 postMessageAsync(msg); // we may be called from main thread, use async message
3572}
3573
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003574void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003575 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003576 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3577 this);
3578 int32_t type = hw->getDisplayType();
3579 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003580
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003581 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003582 return;
3583 }
3584
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003585 hw->setPowerMode(mode);
3586 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3587 ALOGW("Trying to set power mode for virtual display");
3588 return;
3589 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003590
Lloyd Pique4d234852018-01-22 17:21:36 -08003591 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003592 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003593 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3594 if (idx < 0) {
3595 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3596 return;
3597 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003598 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003599 }
3600
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003601 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003602 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003603 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003604 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3605 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003606 // FIXME: eventthread only knows about the main display right now
3607 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003608 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003609 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003611 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003612 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003613 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003614
3615 struct sched_param param = {0};
3616 param.sched_priority = 1;
3617 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3618 ALOGW("Couldn't set SCHED_FIFO on display on");
3619 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003620 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003621 // Turn off the display
3622 struct sched_param param = {0};
3623 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3624 ALOGW("Couldn't set SCHED_OTHER on display off");
3625 }
3626
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003627 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3628 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003629 disableHardwareVsync(true); // also cancels any in-progress resync
3630
Mathias Agopiancde87a32012-09-13 14:09:01 -07003631 // FIXME: eventthread only knows about the main display right now
3632 mEventThread->onScreenReleased();
3633 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003634
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003635 getHwComposer().setPowerMode(type, mode);
3636 mVisibleRegionsDirty = true;
3637 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003638 } else if (mode == HWC_POWER_MODE_DOZE ||
3639 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003640 // Update display while dozing
3641 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003642 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3643 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003644 // FIXME: eventthread only knows about the main display right now
3645 mEventThread->onScreenAcquired();
3646 resyncToHardwareVsync(true);
3647 }
3648 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3649 // Leave display going to doze
3650 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3651 disableHardwareVsync(true); // also cancels any in-progress resync
3652 // FIXME: eventthread only knows about the main display right now
3653 mEventThread->onScreenReleased();
3654 }
3655 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003656 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003657 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003658 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003659 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003660 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003661}
3662
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003663void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3664 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003665 SurfaceFlinger& mFlinger;
3666 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003667 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003668 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003669 MessageSetPowerMode(SurfaceFlinger& flinger,
3670 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3671 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003672 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003673 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003674 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003675 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003676 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003677 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003678 ALOGW("Attempt to set power mode = %d for virtual display",
3679 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003680 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003681 mFlinger.setPowerModeInternal(
3682 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003683 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003684 return true;
3685 }
3686 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003687 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003688 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003689}
3690
3691// ---------------------------------------------------------------------------
3692
Lloyd Pique755e3192018-01-31 16:46:15 -08003693status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3694 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003695 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003696
Mathias Agopianbd115332013-04-18 16:41:04 -07003697 IPCThreadState* ipc = IPCThreadState::self();
3698 const int pid = ipc->getCallingPid();
3699 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003700
Mathias Agopianbd115332013-04-18 16:41:04 -07003701 if ((uid != AID_SHELL) &&
3702 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003703 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003704 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003706 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003707 // (this would indicate SF is stuck, but we want to be able to
3708 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003709 status_t err = mStateLock.timedLock(s2ns(1));
3710 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003711 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003712 result.appendFormat(
3713 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3714 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003715 }
3716
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003717 bool dumpAll = true;
3718 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003719 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003720
3721 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003722 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003723 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3724 dumpAll = false;
3725 }
3726
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003727 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003728 if ((index < numArgs) &&
3729 (args[index] == String16("--list"))) {
3730 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003731 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003732 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003733 }
3734
3735 if ((index < numArgs) &&
3736 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003737 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003738 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003739 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003740 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003741
3742 if ((index < numArgs) &&
3743 (args[index] == String16("--latency-clear"))) {
3744 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003745 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003746 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003747 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003748
3749 if ((index < numArgs) &&
3750 (args[index] == String16("--dispsync"))) {
3751 index++;
3752 mPrimaryDispSync.dump(result);
3753 dumpAll = false;
3754 }
Dan Stozab90cf072015-03-05 11:05:59 -08003755
3756 if ((index < numArgs) &&
3757 (args[index] == String16("--static-screen"))) {
3758 index++;
3759 dumpStaticScreenStats(result);
3760 dumpAll = false;
3761 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003762
3763 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003764 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003765 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003766 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003767 dumpAll = false;
3768 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003769
3770 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3771 index++;
3772 dumpWideColorInfo(result);
3773 dumpAll = false;
3774 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003775 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003776
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003777 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003778 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003779 }
3780
Mathias Agopian9795c422009-08-26 16:36:26 -07003781 if (locked) {
3782 mStateLock.unlock();
3783 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003784 }
3785 write(fd, result.string(), result.size());
3786 return NO_ERROR;
3787}
3788
Dan Stozac7014012014-02-14 15:03:43 -08003789void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3790 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003791{
Robert Carr2047fae2016-11-28 14:09:09 -08003792 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003793 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003794 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003795}
3796
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003797void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003798 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003799{
3800 String8 name;
3801 if (index < args.size()) {
3802 name = String8(args[index]);
3803 index++;
3804 }
3805
David Sodman105b7dc2017-11-04 20:28:14 -07003806 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003807 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003808 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003809
3810 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003811 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003812 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003813 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003814 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003815 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003816 }
Robert Carr2047fae2016-11-28 14:09:09 -08003817 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818 }
3819}
3820
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003821void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003822 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003823{
3824 String8 name;
3825 if (index < args.size()) {
3826 name = String8(args[index]);
3827 index++;
3828 }
3829
Robert Carr2047fae2016-11-28 14:09:09 -08003830 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003831 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003832 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003833 }
Robert Carr2047fae2016-11-28 14:09:09 -08003834 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003835
Svetoslavd85084b2014-03-20 10:28:31 -07003836 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837}
3838
Jamie Gennis6547ff42013-07-16 20:12:42 -07003839// This should only be called from the main thread. Otherwise it would need
3840// the lock and should use mCurrentState rather than mDrawingState.
3841void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003842 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003843 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003844 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003845
3846 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3847}
3848
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003849void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003850{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003851 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003852
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003853 if (isLayerTripleBufferingDisabled())
3854 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003855
3856 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003857 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003858 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003859 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003860 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3861 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003862 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003863}
3864
Dan Stozab90cf072015-03-05 11:05:59 -08003865void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3866{
3867 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003868 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3869 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003870 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003871 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003872 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3873 b + 1, bucketTimeSec, percent);
3874 }
David Sodman4a36e932017-11-07 14:29:47 -08003875 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003876 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003877 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003878 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003879 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003880}
3881
Dan Stozae77c7662016-05-13 11:37:28 -07003882void SurfaceFlinger::recordBufferingStats(const char* layerName,
3883 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003884 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3885 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003886 for (const auto& segment : history) {
3887 if (!segment.usedThirdBuffer) {
3888 stats.twoBufferTime += segment.totalTime;
3889 }
3890 if (segment.occupancyAverage < 1.0f) {
3891 stats.doubleBufferedTime += segment.totalTime;
3892 } else if (segment.occupancyAverage < 2.0f) {
3893 stats.tripleBufferedTime += segment.totalTime;
3894 }
3895 ++stats.numSegments;
3896 stats.totalTime += segment.totalTime;
3897 }
3898}
3899
Brian Andersond6927fb2016-07-23 23:37:30 -07003900void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3901 result.appendFormat("Layer frame timestamps:\n");
3902
3903 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3904 const size_t count = currentLayers.size();
3905 for (size_t i=0 ; i<count ; i++) {
3906 currentLayers[i]->dumpFrameEvents(result);
3907 }
3908}
3909
Dan Stozae77c7662016-05-13 11:37:28 -07003910void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3911 result.append("Buffering stats:\n");
3912 result.append(" [Layer name] <Active time> <Two buffer> "
3913 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003914 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003915 typedef std::tuple<std::string, float, float, float> BufferTuple;
3916 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003917 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003918 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003919 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003920 if (stats.numSegments == 0) {
3921 continue;
3922 }
3923 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3924 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3925 stats.totalTime;
3926 float doubleBufferRatio = static_cast<float>(
3927 stats.doubleBufferedTime) / stats.totalTime;
3928 float tripleBufferRatio = static_cast<float>(
3929 stats.tripleBufferedTime) / stats.totalTime;
3930 sorted.insert({activeTime, {name, twoBufferRatio,
3931 doubleBufferRatio, tripleBufferRatio}});
3932 }
3933 for (const auto& sortedPair : sorted) {
3934 float activeTime = sortedPair.first;
3935 const BufferTuple& values = sortedPair.second;
3936 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3937 std::get<0>(values).c_str(), activeTime,
3938 std::get<1>(values), std::get<2>(values),
3939 std::get<3>(values));
3940 }
3941 result.append("\n");
3942}
3943
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003944void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3945 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003946 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003947
3948 // TODO: print out if wide-color mode is active or not
3949
3950 for (size_t d = 0; d < mDisplays.size(); d++) {
3951 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3952 int32_t hwcId = displayDevice->getHwcDisplayId();
3953 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3954 continue;
3955 }
3956
3957 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003958 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003959 for (auto&& mode : modes) {
3960 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3961 }
3962
Peiyong Lina52f0292018-03-14 17:26:31 -07003963 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003964 result.appendFormat(" Current color mode: %s (%d)\n",
3965 decodeColorMode(currentMode).c_str(), currentMode);
3966 }
3967 result.append("\n");
3968}
3969
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003970LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003971 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003972 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3973 const State& state = useDrawing ? mDrawingState : mCurrentState;
3974 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003975 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003976 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003977 });
3978
3979 return layersProto;
3980}
3981
Mathias Agopian74d211a2013-04-22 16:55:35 +02003982void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3983 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003984{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003985 bool colorize = false;
3986 if (index < args.size()
3987 && (args[index] == String16("--color"))) {
3988 colorize = true;
3989 index++;
3990 }
3991
3992 Colorizer colorizer(colorize);
3993
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003994 // figure out if we're stuck somewhere
3995 const nsecs_t now = systemTime();
3996 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3997 const nsecs_t inTransaction(mDebugInTransaction);
3998 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3999 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4000
4001 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004002 * Dump library configuration.
4003 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004
4005 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004006 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004007 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004008 appendSfConfigString(result);
4009 appendUiConfigString(result);
4010 appendGuiConfigString(result);
4011 result.append("\n");
4012
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004013 result.append("\nWide-Color information:\n");
4014 dumpWideColorInfo(result);
4015
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004016 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004017 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004018 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004019 result.append(SyncFeatures::getInstance().toString());
4020 result.append("\n");
4021
David Sodman105b7dc2017-11-04 20:28:14 -07004022 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004023
Andy McFadden41d67d72014-04-25 16:58:34 -07004024 colorizer.bold(result);
4025 result.append("DispSync configuration: ");
4026 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004027 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004028 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004029 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004030 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004031 result.append("\n");
4032
Dan Stozab90cf072015-03-05 11:05:59 -08004033 // Dump static screen stats
4034 result.append("\n");
4035 dumpStaticScreenStats(result);
4036 result.append("\n");
4037
Dan Stozae77c7662016-05-13 11:37:28 -07004038 dumpBufferingStats(result);
4039
Andy McFadden4803b742012-09-24 19:07:20 -07004040 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004041 * Dump the visible layer list
4042 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004043 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004044 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004045 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4046 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004047 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004048
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004049 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004050 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004051 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004052 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004053
4054 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004055 * Dump Display state
4056 */
4057
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004058 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004059 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004060 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004061 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4062 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004063 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004064 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004065 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004066
4067 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004068 * Dump SurfaceFlinger global state
4069 */
4070
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004071 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004072 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004073 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004074
Mathias Agopian888c8222012-08-04 21:10:38 -07004075 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004076 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004077
David Sodmanbc815282017-11-05 18:57:52 -08004078 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004079
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004080 if (hw) {
4081 hw->undefinedRegion.dump(result, "undefinedRegion");
4082 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4083 hw->getOrientation(), hw->isDisplayOn());
4084 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004085 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004086 " last eglSwapBuffers() time: %f us\n"
4087 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004088 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004089 " refresh-rate : %f fps\n"
4090 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004091 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004092 " gpu_to_cpu_unsupported : %d\n"
4093 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004094 mLastSwapBufferTime/1000.0,
4095 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004096 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004097 1e9 / activeConfig->getVsyncPeriod(),
4098 activeConfig->getDpiX(),
4099 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004100 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004101
Mathias Agopian74d211a2013-04-22 16:55:35 +02004102 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004103 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004104
Mathias Agopian74d211a2013-04-22 16:55:35 +02004105 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004106 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004107
4108 /*
4109 * VSYNC state
4110 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004111 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004112 result.append("\n");
4113
4114 /*
4115 * HWC layer minidump
4116 */
4117 for (size_t d = 0; d < mDisplays.size(); d++) {
4118 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4119 int32_t hwcId = displayDevice->getHwcDisplayId();
4120 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4121 continue;
4122 }
4123
4124 result.appendFormat("Display %d HWC layers:\n", hwcId);
4125 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004126 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004127 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004128 });
Dan Stozae22aec72016-08-01 13:20:59 -07004129 result.append("\n");
4130 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131
4132 /*
4133 * Dump HWComposer state
4134 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004135 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004136 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004137 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004138 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004139 result.appendFormat(" h/w composer %s\n",
4140 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004141 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142
4143 /*
4144 * Dump gralloc state
4145 */
4146 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4147 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004148
4149 /*
4150 * Dump VrFlinger state if in use.
4151 */
4152 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4153 result.append("VrFlinger state:\n");
4154 result.append(mVrFlinger->Dump().c_str());
4155 result.append("\n");
4156 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004157}
4158
Mathias Agopian13127d82013-03-05 17:47:11 -08004159const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004160SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004161 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004162 wp<IBinder> dpy;
4163 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4164 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4165 dpy = mDisplays.keyAt(i);
4166 break;
4167 }
4168 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004169 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004170 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4171 // Just use the primary display so we have something to return
4172 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4173 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004174 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004175}
4176
Keun young Park63f165f2012-08-31 10:53:36 -07004177bool SurfaceFlinger::startDdmConnection()
4178{
4179 void* libddmconnection_dso =
4180 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4181 if (!libddmconnection_dso) {
4182 return false;
4183 }
4184 void (*DdmConnection_start)(const char* name);
4185 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004186 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004187 if (!DdmConnection_start) {
4188 dlclose(libddmconnection_dso);
4189 return false;
4190 }
4191 (*DdmConnection_start)(getServiceName());
4192 return true;
4193}
4194
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004195status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004196 switch (code) {
4197 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004198 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004199 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004200 case CLEAR_ANIMATION_FRAME_STATS:
4201 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004202 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004203 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004204 case ENABLE_VSYNC_INJECTIONS:
4205 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206 {
4207 // codes that require permission check
4208 IPCThreadState* ipc = IPCThreadState::self();
4209 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004210 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004211 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004212 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004213 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004214 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004215 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004216 break;
4217 }
Robert Carr1db73f62016-12-21 12:58:51 -08004218 /*
4219 * Calling setTransactionState is safe, because you need to have been
4220 * granted a reference to Client* and Handle* to do anything with it.
4221 *
4222 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4223 */
4224 case SET_TRANSACTION_STATE:
4225 case CREATE_SCOPED_CONNECTION:
4226 {
4227 return OK;
4228 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004229 case CAPTURE_SCREEN:
4230 {
4231 // codes that require permission check
4232 IPCThreadState* ipc = IPCThreadState::self();
4233 const int pid = ipc->getCallingPid();
4234 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004235 if ((uid != AID_GRAPHICS) &&
4236 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004237 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004238 return PERMISSION_DENIED;
4239 }
4240 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241 }
chaviwa76b2712017-09-20 12:02:26 -07004242 case CAPTURE_LAYERS: {
4243 IPCThreadState* ipc = IPCThreadState::self();
4244 const int pid = ipc->getCallingPid();
4245 const int uid = ipc->getCallingUid();
4246 if ((uid != AID_GRAPHICS) &&
4247 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4248 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4249 return PERMISSION_DENIED;
4250 }
4251 break;
4252 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004253 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004254 return OK;
4255}
4256
4257status_t SurfaceFlinger::onTransact(
4258 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4259{
4260 status_t credentialCheck = CheckTransactCodeCredentials(code);
4261 if (credentialCheck != OK) {
4262 return credentialCheck;
4263 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004265 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4266 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004267 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004268 IPCThreadState* ipc = IPCThreadState::self();
4269 const int uid = ipc->getCallingUid();
4270 if (CC_UNLIKELY(uid != AID_SYSTEM
4271 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004272 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004273 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004274 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004275 return PERMISSION_DENIED;
4276 }
4277 int n;
4278 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004279 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004280 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281 return NO_ERROR;
4282 case 1002: // SHOW_UPDATES
4283 n = data.readInt32();
4284 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004285 invalidateHwcGeometry();
4286 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004287 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004289 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004290 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004291 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004292 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004293 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004294 setTransactionFlags(
4295 eTransactionNeeded|
4296 eDisplayTransactionNeeded|
4297 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004298 return NO_ERROR;
4299 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004300 case 1006:{ // send empty update
4301 signalRefresh();
4302 return NO_ERROR;
4303 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004304 case 1008: // toggle use of hw composer
4305 n = data.readInt32();
4306 mDebugDisableHWC = n ? 1 : 0;
4307 invalidateHwcGeometry();
4308 repaintEverything();
4309 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004310 case 1009: // toggle use of transform hint
4311 n = data.readInt32();
4312 mDebugDisableTransformHint = n ? 1 : 0;
4313 invalidateHwcGeometry();
4314 repaintEverything();
4315 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004317 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004318 reply->writeInt32(0);
4319 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004320 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004321 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004322 return NO_ERROR;
4323 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004324 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004325 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004326 return NO_ERROR;
4327 }
4328 case 1014: {
4329 // daltonize
4330 n = data.readInt32();
4331 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004332 case 1:
4333 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4334 break;
4335 case 2:
4336 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4337 break;
4338 case 3:
4339 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4340 break;
4341 default:
4342 mDaltonizer.setType(ColorBlindnessType::None);
4343 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004344 }
4345 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004346 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004347 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004348 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004349 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004350 invalidateHwcGeometry();
4351 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004352 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004353 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004354 case 1015: {
4355 // apply a color matrix
4356 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004357 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004358 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004359 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004360 for (size_t j = 0; j < 4; j++) {
4361 mColorMatrix[i][j] = data.readFloat();
4362 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004363 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004364 } else {
4365 mColorMatrix = mat4();
4366 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004367
4368 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4369 // the division by w in the fragment shader
4370 float4 lastRow(transpose(mColorMatrix)[3]);
4371 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4372 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4373 }
4374
Alan Viverette9c5a3332013-09-12 20:04:35 -07004375 invalidateHwcGeometry();
4376 repaintEverything();
4377 return NO_ERROR;
4378 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004379 // This is an experimental interface
4380 // Needs to be shifted to proper binder interface when we productize
4381 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004382 n = data.readInt32();
4383 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004384 return NO_ERROR;
4385 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004386 case 1017: {
4387 n = data.readInt32();
4388 mForceFullDamage = static_cast<bool>(n);
4389 return NO_ERROR;
4390 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004391 case 1018: { // Modify Choreographer's phase offset
4392 n = data.readInt32();
4393 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4394 return NO_ERROR;
4395 }
4396 case 1019: { // Modify SurfaceFlinger's phase offset
4397 n = data.readInt32();
4398 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4399 return NO_ERROR;
4400 }
Irvel468051e2016-06-13 16:44:44 -07004401 case 1020: { // Layer updates interceptor
4402 n = data.readInt32();
4403 if (n) {
4404 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004405 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004406 }
4407 else{
4408 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004409 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004410 }
4411 return NO_ERROR;
4412 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004413 case 1021: { // Disable HWC virtual displays
4414 n = data.readInt32();
4415 mUseHwcVirtualDisplays = !n;
4416 return NO_ERROR;
4417 }
Romain Guy0147a172017-06-01 13:53:56 -07004418 case 1022: { // Set saturation boost
4419 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4420
4421 invalidateHwcGeometry();
4422 repaintEverything();
4423 return NO_ERROR;
4424 }
Romain Guy54f154a2017-10-24 21:40:32 +01004425 case 1023: { // Set native mode
4426 mForceNativeColorMode = data.readInt32() == 1;
4427
4428 invalidateHwcGeometry();
4429 repaintEverything();
4430 return NO_ERROR;
4431 }
4432 case 1024: { // Is wide color gamut rendering/color management supported?
4433 reply->writeBool(hasWideColorDisplay);
4434 return NO_ERROR;
4435 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004436 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004437 n = data.readInt32();
4438 if (n) {
4439 ALOGV("LayerTracing enabled");
4440 mTracing.enable();
4441 doTracing("tracing.enable");
4442 reply->writeInt32(NO_ERROR);
4443 } else {
4444 ALOGV("LayerTracing disabled");
4445 status_t err = mTracing.disable();
4446 reply->writeInt32(err);
4447 }
4448 return NO_ERROR;
4449 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004450 case 1026: { // Get layer tracing status
4451 reply->writeBool(mTracing.isEnabled());
4452 return NO_ERROR;
4453 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 }
4455 }
4456 return err;
4457}
4458
Steven Thomas6d8110b2017-08-31 18:24:21 -07004459void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004460 android_atomic_or(1, &mRepaintEverything);
Jeffrey Kardatzkea9dcf112018-04-03 10:45:55 -07004461 for (size_t dpy = 0; dpy < mDisplays.size(); dpy++) {
4462 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
4463 const Rect bounds(displayDevice->getBounds());
4464 displayDevice->dirtyRegion.orSelf(Region(bounds));
4465 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004466 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004467}
4468
Steven Thomas6d8110b2017-08-31 18:24:21 -07004469void SurfaceFlinger::repaintEverything() {
4470 ConditionalLock _l(mStateLock,
4471 std::this_thread::get_id() != mMainThreadId);
4472 repaintEverythingLocked();
4473}
4474
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004475// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4476class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004477public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004478 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4479 ~WindowDisconnector() {
4480 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004481 }
4482
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004483private:
4484 ANativeWindow* mWindow;
4485 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004486};
4487
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004488status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4489 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4490 int32_t minLayerZ, int32_t maxLayerZ,
4491 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004492 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004493 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004494
chaviwa76b2712017-09-20 12:02:26 -07004495 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4496
4497 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004498 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4499
chaviwa76b2712017-09-20 12:02:26 -07004500 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4501
4502 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4503 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004504 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004505}
4506
4507status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004508 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004509 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004510 ATRACE_CALL();
4511
4512 class LayerRenderArea : public RenderArea {
4513 public:
Robert Carr578038f2018-03-09 12:25:24 -08004514 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4515 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4516 : RenderArea(reqHeight, reqWidth),
4517 mLayer(layer),
4518 mCrop(crop),
4519 mFlinger(flinger),
4520 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004521 Rect getBounds() const override {
4522 const Layer::State& layerState(mLayer->getDrawingState());
4523 return Rect(layerState.active.w, layerState.active.h);
4524 }
4525 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4526 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4527 bool isSecure() const override { return false; }
4528 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004529 const Transform& getTransform() const { return mTransform; }
4530
4531 class ReparentForDrawing {
4532 public:
4533 const sp<Layer>& oldParent;
4534 const sp<Layer>& newParent;
4535
4536 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4537 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004538 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004539 }
Robert Carr15eae092018-03-23 13:43:53 -07004540 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004541 };
4542
4543 void render(std::function<void()> drawLayers) override {
4544 if (!mChildrenOnly) {
4545 mTransform = mLayer->getTransform().inverse();
4546 drawLayers();
4547 } else {
4548 Rect bounds = getBounds();
4549 screenshotParentLayer =
4550 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4551 bounds.getWidth(), bounds.getHeight(), 0);
4552
4553 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4554 drawLayers();
4555 }
4556 }
chaviwa76b2712017-09-20 12:02:26 -07004557
chaviw7206d492017-11-10 16:16:12 -08004558 Rect getSourceCrop() const override {
4559 if (mCrop.isEmpty()) {
4560 return getBounds();
4561 } else {
4562 return mCrop;
4563 }
4564 }
chaviwa76b2712017-09-20 12:02:26 -07004565 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004566 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004567
4568 private:
chaviw7206d492017-11-10 16:16:12 -08004569 const sp<Layer> mLayer;
4570 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004571
4572 // In the "childrenOnly" case we reparent the children to a screenshot
4573 // layer which has no properties set and which does not draw.
4574 sp<ContainerLayer> screenshotParentLayer;
4575 Transform mTransform;
4576
4577 SurfaceFlinger* mFlinger;
4578 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004579 };
4580
4581 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4582 auto parent = layerHandle->owner.promote();
4583
chaviw7206d492017-11-10 16:16:12 -08004584 if (parent == nullptr || parent->isPendingRemoval()) {
4585 ALOGE("captureLayers called with a removed parent");
4586 return NAME_NOT_FOUND;
4587 }
4588
Robert Carr578038f2018-03-09 12:25:24 -08004589 const int uid = IPCThreadState::self()->getCallingUid();
4590 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4591 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4592 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4593 return PERMISSION_DENIED;
4594 }
4595
chaviw7206d492017-11-10 16:16:12 -08004596 Rect crop(sourceCrop);
4597 if (sourceCrop.width() <= 0) {
4598 crop.left = 0;
4599 crop.right = parent->getCurrentState().active.w;
4600 }
4601
4602 if (sourceCrop.height() <= 0) {
4603 crop.top = 0;
4604 crop.bottom = parent->getCurrentState().active.h;
4605 }
4606
4607 int32_t reqWidth = crop.width() * frameScale;
4608 int32_t reqHeight = crop.height() * frameScale;
4609
Robert Carr578038f2018-03-09 12:25:24 -08004610 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004611
Robert Carr578038f2018-03-09 12:25:24 -08004612 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004613 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4614 if (!layer->isVisible()) {
4615 return;
Robert Carr578038f2018-03-09 12:25:24 -08004616 } else if (childrenOnly && layer == parent.get()) {
4617 return;
chaviwa76b2712017-09-20 12:02:26 -07004618 }
4619 visitor(layer);
4620 });
4621 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004622 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004623}
4624
4625status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4626 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004627 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004628 bool useIdentityTransform) {
4629 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004630
chaviwa76b2712017-09-20 12:02:26 -07004631 renderArea.updateDimensions();
4632
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004633 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4634 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4635 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4636 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004637
4638 // This mutex protects syncFd and captureResult for communication of the return values from the
4639 // main thread back to this Binder thread
4640 std::mutex captureMutex;
4641 std::condition_variable captureCondition;
4642 std::unique_lock<std::mutex> captureLock(captureMutex);
4643 int syncFd = -1;
4644 std::optional<status_t> captureResult;
4645
Robert Carr03480e22018-01-04 16:02:06 -08004646 const int uid = IPCThreadState::self()->getCallingUid();
4647 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4648
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004649 sp<LambdaMessage> message = new LambdaMessage([&]() {
4650 // If there is a refresh pending, bug out early and tell the binder thread to try again
4651 // after the refresh.
4652 if (mRefreshPending) {
4653 ATRACE_NAME("Skipping screenshot for now");
4654 std::unique_lock<std::mutex> captureLock(captureMutex);
4655 captureResult = std::make_optional<status_t>(EAGAIN);
4656 captureCondition.notify_one();
4657 return;
4658 }
4659
4660 status_t result = NO_ERROR;
4661 int fd = -1;
4662 {
4663 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004664 renderArea.render([&]() {
4665 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4666 useIdentityTransform, forSystem, &fd);
4667 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668 }
4669
4670 {
4671 std::unique_lock<std::mutex> captureLock(captureMutex);
4672 syncFd = fd;
4673 captureResult = std::make_optional<status_t>(result);
4674 captureCondition.notify_one();
4675 }
4676 });
4677
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004678 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004679 if (result == NO_ERROR) {
4680 captureCondition.wait(captureLock, [&]() { return captureResult; });
4681 while (*captureResult == EAGAIN) {
4682 captureResult.reset();
4683 result = postMessageAsync(message);
4684 if (result != NO_ERROR) {
4685 return result;
4686 }
4687 captureCondition.wait(captureLock, [&]() { return captureResult; });
4688 }
4689 result = *captureResult;
4690 }
4691
4692 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004693 sync_wait(syncFd, -1);
4694 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004695 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004696
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004697 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004698}
4699
chaviwa76b2712017-09-20 12:02:26 -07004700void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4701 TraverseLayersFunction traverseLayers, bool yswap,
4702 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004703 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004704
Lloyd Pique144e1162017-12-20 16:44:52 -08004705 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004706
4707 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004708 const auto raWidth = renderArea.getWidth();
4709 const auto raHeight = renderArea.getHeight();
4710
4711 const auto reqWidth = renderArea.getReqWidth();
4712 const auto reqHeight = renderArea.getReqHeight();
4713 Rect sourceCrop = renderArea.getSourceCrop();
4714
4715 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4716 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004717
Dan Stozac1879002014-05-22 15:59:05 -07004718 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004719 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004720 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004721 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004722 }
4723
4724 // ensure that sourceCrop is inside screen
4725 if (sourceCrop.left < 0) {
4726 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4727 }
chaviwa76b2712017-09-20 12:02:26 -07004728 if (sourceCrop.right > raWidth) {
4729 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004730 }
4731 if (sourceCrop.top < 0) {
4732 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4733 }
chaviwa76b2712017-09-20 12:02:26 -07004734 if (sourceCrop.bottom > raHeight) {
4735 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004736 }
4737
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004738 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004739 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004740 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004741 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4742 }
4743 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004744
Mathias Agopian180f10d2013-04-10 22:55:41 -07004745 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004746 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004747
4748 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004749 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4750 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004751 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004752
4753 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004754 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004755
chaviwa76b2712017-09-20 12:02:26 -07004756 traverseLayers([&](Layer* layer) {
4757 if (filtering) layer->setFiltering(true);
4758 layer->draw(renderArea, useIdentityTransform);
4759 if (filtering) layer->setFiltering(false);
4760 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004761}
4762
chaviwa76b2712017-09-20 12:02:26 -07004763status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4764 TraverseLayersFunction traverseLayers,
4765 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004766 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004767 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004768 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004769 ATRACE_CALL();
4770
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004771 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004772
4773 traverseLayers([&](Layer* layer) {
4774 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4775 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004776
Robert Carr03480e22018-01-04 16:02:06 -08004777 // We allow the system server to take screenshots of secure layers for
4778 // use in situations like the Screen-rotation animation and place
4779 // the impetus on WindowManager to not persist them.
4780 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004781 ALOGW("FB is protected: PERMISSION_DENIED");
4782 return PERMISSION_DENIED;
4783 }
4784
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004785 // this binds the given EGLImage as a framebuffer for the
4786 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004787 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004788 if (bufferBond.getStatus() != NO_ERROR) {
4789 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004790 return INVALID_OPERATION;
4791 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004792
Dan Stozaabcda352017-06-01 14:37:39 -07004793 // this will in fact render into our dequeued buffer
4794 // via an FBO, which means we didn't have to create
4795 // an EGLSurface and therefore we're not
4796 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004797 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004798
Dan Stozaabcda352017-06-01 14:37:39 -07004799 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004800 getRenderEngine().finish();
4801 *outSyncFd = -1;
4802
chaviwa76b2712017-09-20 12:02:26 -07004803 const auto reqWidth = renderArea.getReqWidth();
4804 const auto reqHeight = renderArea.getReqHeight();
4805
Dan Stozaabcda352017-06-01 14:37:39 -07004806 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4807 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004808 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004809 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004810 } else {
4811 base::unique_fd syncFd = getRenderEngine().flush();
4812 if (syncFd < 0) {
4813 getRenderEngine().finish();
4814 }
4815 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004816 }
4817
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004819}
4820
Mathias Agopiand5556842013-09-19 17:08:37 -07004821void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004822 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004823 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004824 for (size_t y = 0; y < h; y++) {
4825 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4826 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004827 if (p[x] != 0xFF000000) return;
4828 }
4829 }
chaviwa76b2712017-09-20 12:02:26 -07004830 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004831
Robert Carr2047fae2016-11-28 14:09:09 -08004832 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004833 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004834 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004835 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4836 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4837 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4838 static_cast<float>(state.color.a));
4839 i++;
4840 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004841 }
4842}
4843
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004844// ---------------------------------------------------------------------------
4845
Dan Stoza412903f2017-04-27 13:42:17 -07004846void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4847 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004848}
4849
Dan Stoza412903f2017-04-27 13:42:17 -07004850void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4851 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004852}
4853
chaviwa76b2712017-09-20 12:02:26 -07004854void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4855 int32_t maxLayerZ,
4856 const LayerVector::Visitor& visitor) {
4857 // We loop through the first level of layers without traversing,
4858 // as we need to interpret min/max layer Z in the top level Z space.
4859 for (const auto& layer : mDrawingState.layersSortedByZ) {
4860 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4861 continue;
4862 }
4863 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004864 // relative layers are traversed in Layer::traverseInZOrder
4865 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004866 continue;
4867 }
4868 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004869 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4870 return;
4871 }
chaviwa76b2712017-09-20 12:02:26 -07004872 if (!layer->isVisible()) {
4873 return;
4874 }
4875 visitor(layer);
4876 });
4877 }
4878}
4879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004881
4882
4883#if defined(__gl_h_)
4884#error "don't include gl/gl.h in this file"
4885#endif
4886
4887#if defined(__gl2_h_)
4888#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004889#endif