blob: babac37d7d71c066d2b47e774b54e6e4ffce99fc [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");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001487 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001488 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001489 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492
1493 mHadClientComposition = false;
1494 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1495 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1496 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001497 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001499
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503void SurfaceFlinger::doDebugFlashRegions()
1504{
1505 // is debugging enabled
1506 if (CC_LIKELY(!mDebugRegion))
1507 return;
1508
1509 const bool repaintEverything = mRepaintEverything;
1510 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1511 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001512 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 // transform the dirty region into this screen's coordinate space
1514 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1515 if (!dirtyRegion.isEmpty()) {
1516 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001517 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518
1519 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001521 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001522 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1523
Mathias Agopianda27af92012-09-13 18:17:13 -07001524 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 }
1526 }
1527 }
1528
1529 postFramebuffer();
1530
1531 if (mDebugRegion > 1) {
1532 usleep(mDebugRegion * 1000);
1533 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001534
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001536 auto& displayDevice = mDisplays[displayId];
1537 if (!displayDevice->isDisplayOn()) {
1538 continue;
1539 }
1540
David Sodman105b7dc2017-11-04 20:28:14 -07001541 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1542 ALOGE_IF(result != NO_ERROR,
1543 "prepareFrame for display %zd failed:"
1544 " %d (%s)",
1545 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001546 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
1548
Adrian Roos1e1a1282017-11-01 19:05:31 +01001549void SurfaceFlinger::doTracing(const char* where) {
1550 ATRACE_CALL();
1551 ATRACE_NAME(where);
1552 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001553 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001554 }
1555}
1556
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001557void SurfaceFlinger::logLayerStats() {
1558 ATRACE_CALL();
1559 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1560 int32_t hwcId = -1;
1561 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1562 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1563 if (displayDevice->isPrimary()) {
1564 hwcId = displayDevice->getHwcDisplayId();
1565 break;
1566 }
1567 }
1568 if (hwcId < 0) {
1569 ALOGE("LayerStats: Hmmm, no primary display?");
1570 return;
1571 }
1572 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1573 }
1574}
1575
Brian Andersond6927fb2016-07-23 23:37:30 -07001576void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001578 ATRACE_CALL();
1579 ALOGV("preComposition");
1580
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
1583 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 needExtraInvalidate = true;
1585 }
Robert Carr2047fae2016-11-28 14:09:09 -08001586 });
1587
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 if (needExtraInvalidate) {
1589 signalLayerUpdate();
1590 }
1591}
1592
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593void SurfaceFlinger::updateCompositorTiming(
1594 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1595 std::shared_ptr<FenceTime>& presentFenceTime) {
1596 // Update queue of past composite+present times and determine the
1597 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001598 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001600 while (!getBE().mCompositePresentTimes.empty()) {
1601 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 // Cached values should have been updated before calling this method,
1603 // which helps avoid duplicate syscalls.
1604 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1605 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1606 break;
1607 }
1608 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001609 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610 }
1611
1612 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001613 while (getBE().mCompositePresentTimes.size() > 16) {
1614 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 }
1616
Brian Andersond0010582017-03-07 13:20:31 -08001617 setCompositorTimingSnapped(
1618 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1619}
1620
1621void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1622 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 // Integer division and modulo round toward 0 not -inf, so we need to
1624 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001625 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1627 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1628
Brian Andersond0010582017-03-07 13:20:31 -08001629 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1630 if (idealLatency <= 0) {
1631 idealLatency = vsyncInterval;
1632 }
1633
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Snap the latency to a value that removes scheduling jitter from the
1635 // composition and present times, which often have >1ms of jitter.
1636 // Reducing jitter is important if an app attempts to extrapolate
1637 // something (such as user input) to an accurate diasplay time.
1638 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1639 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001640 nsecs_t bias = vsyncInterval / 2;
1641 int64_t extraVsyncs =
1642 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1643 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1644 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645
David Sodman99974d22017-11-28 12:04:33 -08001646 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1647 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1648 getBE().mCompositorTiming.interval = vsyncInterval;
1649 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650}
1651
1652void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 ATRACE_CALL();
1655 ALOGV("postComposition");
1656
Brian Anderson3546a3f2016-07-14 11:51:14 -07001657 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001658 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001659 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001660 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001661 }
1662
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001663 // |mStateLock| not needed as we are on the main thread
1664 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001665
David Sodman73beded2017-11-15 11:56:06 -08001666 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001667 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001668 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669 glCompositionDoneFenceTime =
1670 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001671 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001672 } else {
1673 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1674 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675
David Sodman73beded2017-11-15 11:56:06 -08001676 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001677 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001678 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001679 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001680
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1682 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1683
1684 // We use the refreshStartTime which might be sampled a little later than
1685 // when we started doing work for this frame, but that should be okay
1686 // since updateCompositorTiming has snapping logic.
1687 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001688 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001689 CompositorTiming compositorTiming;
1690 {
David Sodman99974d22017-11-28 12:04:33 -08001691 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1692 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001693 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694
Robert Carr2047fae2016-11-28 14:09:09 -08001695 mDrawingState.traverseInZOrder([&](Layer* layer) {
1696 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001697 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001698 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001699 recordBufferingStats(layer->getName().string(),
1700 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001701 }
Robert Carr2047fae2016-11-28 14:09:09 -08001702 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001703
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001704 if (presentFenceTime->isValid()) {
1705 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001706 enableHardwareVsync();
1707 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001708 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001709 }
1710 }
1711
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001712 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001713 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001714 enableHardwareVsync();
1715 }
1716 }
1717
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718 if (mAnimCompositionPending) {
1719 mAnimCompositionPending = false;
1720
Brian Anderson4e606e32017-03-16 15:34:57 -07001721 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001723 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001724 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001725 // The HWC doesn't support present fences, so use the refresh
1726 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001727 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001728 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 mAnimFrameTracker.setActualPresentTime(presentTime);
1730 }
1731 mAnimFrameTracker.advanceFrame();
1732 }
Dan Stozab90cf072015-03-05 11:05:59 -08001733
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001734 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1735 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001736 return;
1737 }
1738
1739 nsecs_t currentTime = systemTime();
1740 if (mHasPoweredOff) {
1741 mHasPoweredOff = false;
1742 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001743 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001745 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1746 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001747 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001748 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001749 }
David Sodman4a36e932017-11-07 14:29:47 -08001750 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001751 }
David Sodman4a36e932017-11-07 14:29:47 -08001752 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753}
1754
1755void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 ATRACE_CALL();
1757 ALOGV("rebuildLayerStacks");
1758
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001761 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 mVisibleRegionsDirty = false;
1763 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001764
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1766 Region opaqueRegion;
1767 Region dirtyRegion;
1768 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001769 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1771 const Transform& tr(displayDevice->getTransform());
1772 const Rect bounds(displayDevice->getBounds());
1773 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001774 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001775
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001777 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001778 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1779 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 Region drawRegion(tr.transform(
1781 layer->visibleNonTransparentRegion));
1782 drawRegion.andSelf(bounds);
1783 if (!drawRegion.isEmpty()) {
1784 layersSortedByZ.add(layer);
1785 } else {
1786 // Clear out the HWC layer if this layer was
1787 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001788 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001789 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001790 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001791 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001792 // WM changes displayDevice->layerStack upon sleep/awake.
1793 // Here we make sure we delete the HWC layers even if
1794 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001795 hwcLayerDestroyed = layer->destroyHwcLayer(
1796 displayDevice->getHwcDisplayId());
1797 }
1798
1799 // If a layer is not going to get a release fence because
1800 // it is invisible, but it is also going to release its
1801 // old buffer, add it to the list of layers needing
1802 // fences.
1803 if (hwcLayerDestroyed) {
1804 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1805 mLayersWithQueuedFrames.cend(), layer);
1806 if (found != mLayersWithQueuedFrames.cend()) {
1807 layersNeedingFences.add(layer);
1808 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001809 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 });
1811 }
1812 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001813 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 displayDevice->undefinedRegion.set(bounds);
1815 displayDevice->undefinedRegion.subtractSelf(
1816 tr.transform(opaqueRegion));
1817 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001821
Romain Guy0147a172017-06-01 13:53:56 -07001822mat4 SurfaceFlinger::computeSaturationMatrix() const {
1823 if (mSaturation == 1.0f) {
1824 return mat4();
1825 }
1826
1827 // Rec.709 luma coefficients
1828 float3 luminance{0.213f, 0.715f, 0.072f};
1829 luminance *= 1.0f - mSaturation;
1830 return mat4(
1831 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1832 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1833 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1834 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1835 );
1836}
1837
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001838// pickColorMode translates a given dataspace into the best available color mode.
1839// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001840ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001841 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001842 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001843 }
1844
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001845 switch (dataSpace) {
1846 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1847 // system expects.
1848 case HAL_DATASPACE_UNKNOWN:
1849 case HAL_DATASPACE_SRGB:
1850 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001851 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001852 break;
1853
1854 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001855 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001856 break;
1857
1858 default:
1859 // TODO (courtneygo): Do we want to assert an error here?
1860 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1861 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001862 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001863 break;
1864 }
1865}
1866
Romain Guy0147a172017-06-01 13:53:56 -07001867android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001868 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869 // Only support sRGB and Display-P3 right now.
1870 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1871 return HAL_DATASPACE_DISPLAY_P3;
1872 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001873 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1874 return HAL_DATASPACE_DISPLAY_P3;
1875 }
1876 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1877 return HAL_DATASPACE_DISPLAY_P3;
1878 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001879 if (!hasHdr) {
1880 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1881 return HAL_DATASPACE_DISPLAY_P3;
1882 }
1883 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1884 return HAL_DATASPACE_DISPLAY_P3;
1885 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001886 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001887
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001888 return HAL_DATASPACE_V0_SRGB;
1889}
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 ATRACE_CALL();
1893 ALOGV("setUpHWComposer");
1894
Jesse Hall028dc8f2013-08-20 16:35:32 -07001895 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001896 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1897 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1898 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1899
1900 // If nothing has changed (!dirty), don't recompose.
1901 // If something changed, but we don't currently have any visible layers,
1902 // and didn't when we last did a composition, then skip it this time.
1903 // The second rule does two things:
1904 // - When all layers are removed from a display, we'll emit one black
1905 // frame, then nothing more until we get new layers.
1906 // - When a display is created with a private layer stack, we won't
1907 // emit any black frames until a layer is added to the layer stack.
1908 bool mustRecompose = dirty && !(empty && wasEmpty);
1909
1910 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1911 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1912 mustRecompose ? "doing" : "skipping",
1913 dirty ? "+" : "-",
1914 empty ? "+" : "-",
1915 wasEmpty ? "+" : "-");
1916
Dan Stoza71433162014-02-04 16:22:36 -08001917 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001918
1919 if (mustRecompose) {
1920 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1921 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001922 }
1923
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 // build the h/w work list
1925 if (CC_UNLIKELY(mGeometryInvalid)) {
1926 mGeometryInvalid = false;
1927 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1928 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1929 const auto hwcId = displayDevice->getHwcDisplayId();
1930 if (hwcId >= 0) {
1931 const Vector<sp<Layer>>& currentLayers(
1932 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001933 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001934 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001936 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001939 }
1940 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001941
Robert Carrae060832016-11-28 10:51:00 -08001942 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001945 }
1946 }
1947 }
1948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 }
Riley Andrews03414a12014-07-01 14:22:59 -07001950
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001951
Romain Guy0147a172017-06-01 13:53:56 -07001952 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001953
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 // Set the per-frame data
1955 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1956 auto& displayDevice = mDisplays[displayId];
1957 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001958
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 if (hwcId < 0) {
1960 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001961 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001962 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001963 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001964 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1965 "display %zd: %d", displayId, result);
1966 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001968 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1969 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001970 !displayDevice->getHdrSupport()) {
1971 layer->forceClientComposition(hwcId);
1972 }
1973
chaviwc9232ed2017-11-14 15:31:15 -08001974 if (layer->getForceClientComposition(hwcId)) {
1975 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1976 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1977 continue;
1978 }
1979
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 layer->setPerFrameData(displayDevice);
1981 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001982
1983 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001984 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001985 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1986
1987 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001988 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1989 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001990 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1991 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1992 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1993 }
1994 newColorMode = pickColorMode(newDataSpace);
1995
Thierry Strudel2924d012017-08-14 15:19:37 -07001996 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001997 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 }
1999
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002000 mPreviousColorMatrix = colorMatrix;
2001
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002003 auto& displayDevice = mDisplays[displayId];
2004 if (!displayDevice->isDisplayOn()) {
2005 continue;
2006 }
2007
David Sodman105b7dc2017-11-04 20:28:14 -07002008 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2010 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002011 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002012}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002013
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014void SurfaceFlinger::doComposition() {
2015 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 ALOGV("doComposition");
2017
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002018 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002019 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002020 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002021 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 // transform the dirty region into this screen's coordinate space
2023 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002024
2025 // repaint the framebuffer (if needed)
2026 doDisplayComposition(hw, dirtyRegion);
2027
Mathias Agopiancd60f992012-08-16 16:28:27 -07002028 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002029 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002030 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002031 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002032 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033}
2034
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035void SurfaceFlinger::postFramebuffer()
2036{
Mathias Agopian841cde52012-03-01 15:44:37 -08002037 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002039
Mathias Agopiana44b0412011-10-16 18:46:35 -07002040 const nsecs_t now = systemTime();
2041 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002042
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2044 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002045 if (!displayDevice->isDisplayOn()) {
2046 continue;
2047 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 const auto hwcId = displayDevice->getHwcDisplayId();
2049 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002050 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002051 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002052 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002053 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002055 // The layer buffer from the previous frame (if any) is released
2056 // by HWC only when the release fence from this frame (if any) is
2057 // signaled. Always get the release fence from HWC first.
2058 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002059 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002060
2061 // If the layer was client composited in the previous frame, we
2062 // need to merge with the previous client target acquire fence.
2063 // Since we do not track that, always merge with the current
2064 // client target acquire fence when it is available, even though
2065 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002067 releaseFence = Fence::merge("LayerRelease", releaseFence,
2068 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002069 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002070
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 layer->onLayerDisplayed(releaseFence);
2072 }
Chia-I Wu83806892017-11-16 10:50:20 -08002073
2074 // We've got a list of layers needing fences, that are disjoint with
2075 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2076 // supply them with the present fence.
2077 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002078 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002079 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2080 layer->onLayerDisplayed(presentFence);
2081 }
2082 }
2083
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002085 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002086 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002087 }
2088
Mathias Agopiana44b0412011-10-16 18:46:35 -07002089 mLastSwapBufferTime = systemTime() - now;
2090 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002091
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002092 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002093 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2094 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2095 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2096 logFrameStats();
2097 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099}
2100
Mathias Agopian87baae12012-07-31 12:38:26 -07002101void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102{
Mathias Agopian841cde52012-03-01 15:44:37 -08002103 ATRACE_CALL();
2104
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002105 // here we keep a copy of the drawing state (that is the state that's
2106 // going to be overwritten by handleTransactionLocked()) outside of
2107 // mStateLock so that the side-effects of the State assignment
2108 // don't happen with mStateLock held (which can cause deadlocks).
2109 State drawingState(mDrawingState);
2110
Mathias Agopianca4d3602011-05-19 15:38:14 -07002111 Mutex::Autolock _l(mStateLock);
2112 const nsecs_t now = systemTime();
2113 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114
Mathias Agopianca4d3602011-05-19 15:38:14 -07002115 // Here we're guaranteed that some transaction flags are set
2116 // so we can call handleTransactionLocked() unconditionally.
2117 // We call getTransactionFlags(), which will also clear the flags,
2118 // with mStateLock held to guarantee that mCurrentState won't change
2119 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002120
Mathias Agopiane57f2922012-08-09 16:29:12 -07002121 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002122 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002123
Mathias Agopianca4d3602011-05-19 15:38:14 -07002124 mLastTransactionTime = systemTime() - now;
2125 mDebugInTransaction = 0;
2126 invalidateHwcGeometry();
2127 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002128}
2129
Lloyd Pique715a2c12017-12-14 17:18:08 -08002130DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002131 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002132 // Figure out whether the event is for the primary display or an
2133 // external display by matching the Hwc display id against one for a
2134 // connected display. If we did not find a match, we then check what
2135 // displays are not already connected to determine the type. If we don't
2136 // have a connected primary display, we assume the new display is meant to
2137 // be the primary display, and then if we don't have an external display,
2138 // we assume it is that.
2139 const auto primaryDisplayId =
2140 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2141 const auto externalDisplayId =
2142 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2143 if (primaryDisplayId && primaryDisplayId == display) {
2144 return DisplayDevice::DISPLAY_PRIMARY;
2145 } else if (externalDisplayId && externalDisplayId == display) {
2146 return DisplayDevice::DISPLAY_EXTERNAL;
2147 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2148 return DisplayDevice::DISPLAY_PRIMARY;
2149 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2150 return DisplayDevice::DISPLAY_EXTERNAL;
2151 }
2152
2153 return DisplayDevice::DISPLAY_ID_INVALID;
2154}
2155
Lloyd Piqueba04e622017-12-14 17:11:26 -08002156void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2157 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002158 auto displayType = determineDisplayType(event.display, event.connection);
2159 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2160 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2161 continue;
2162 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002163
2164 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2165 ALOGE("External displays are not supported by the vr hardware composer.");
2166 continue;
2167 }
2168
Lloyd Pique715a2c12017-12-14 17:18:08 -08002169 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002170
2171 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002172 if (!mBuiltinDisplays[displayType].get()) {
2173 ALOGV("Creating built in display %d", displayType);
2174 mBuiltinDisplays[displayType] = new BBinder();
2175 // All non-virtual displays are currently considered secure.
2176 DisplayDeviceState info(displayType, true);
2177 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2178 "Built-in Screen" : "External Screen";
2179 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002180 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002181 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002182 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002183 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002184
Lloyd Piquefcd86612017-12-14 17:15:36 -08002185 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2186 if (idx >= 0) {
2187 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002188 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002189 mCurrentState.displays.removeItemsAt(idx);
2190 }
2191 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002192 }
2193
2194 processDisplayChangesLocked();
2195 }
2196
2197 mPendingHotplugEvents.clear();
2198}
2199
Lloyd Pique09594832018-01-22 17:48:03 -08002200sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2201 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2202 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2203 bool hasWideColorSupport = false;
2204 if (hasWideColorDisplay) {
2205 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2206 for (ColorMode colorMode : modes) {
2207 switch (colorMode) {
2208 case ColorMode::DISPLAY_P3:
2209 case ColorMode::ADOBE_RGB:
2210 case ColorMode::DCI_P3:
2211 hasWideColorSupport = true;
2212 break;
2213 default:
2214 break;
2215 }
2216 }
2217 }
2218
2219 bool hasHdrSupport = false;
2220 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2221 getHwComposer().getHdrCapabilities(state.type);
2222 if (hdrCapabilities) {
2223 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2224 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2225 hasHdrSupport = iter != types.cend();
2226 }
2227
2228 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2229 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2230
2231 /*
2232 * Create our display's surface
2233 */
2234 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2235 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2236 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2237 renderSurface->setNativeWindow(nativeWindow.get());
2238 const int displayWidth = renderSurface->queryWidth();
2239 const int displayHeight = renderSurface->queryHeight();
2240
2241 // Make sure that composition can never be stalled by a virtual display
2242 // consumer that isn't processing buffers fast enough. We have to do this
2243 // in two places:
2244 // * Here, in case the display is composed entirely by HWC.
2245 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2246 // window's swap interval in eglMakeCurrent, so they'll override the
2247 // interval we set here.
2248 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2249 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2250 }
2251
2252 // virtual displays are always considered enabled
2253 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2254 : HWC_POWER_MODE_OFF;
2255
2256 sp<DisplayDevice> hw =
2257 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2258 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2259 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2260
2261 if (maxFrameBufferAcquiredBuffers >= 3) {
2262 nativeWindowSurface->preallocateBuffers();
2263 }
2264
2265 ColorMode defaultColorMode = ColorMode::NATIVE;
2266 if (hasWideColorSupport) {
2267 defaultColorMode = ColorMode::SRGB;
2268 }
2269 setActiveColorModeInternal(hw, defaultColorMode);
2270 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2271 hw->setLayerStack(state.layerStack);
2272 hw->setProjection(state.orientation, state.viewport, state.frame);
2273 hw->setDisplayName(state.displayName);
2274
2275 return hw;
2276}
2277
Lloyd Pique347200f2017-12-14 17:00:15 -08002278void SurfaceFlinger::processDisplayChangesLocked() {
2279 // here we take advantage of Vector's copy-on-write semantics to
2280 // improve performance by skipping the transaction entirely when
2281 // know that the lists are identical
2282 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2283 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2284 if (!curr.isIdenticalTo(draw)) {
2285 mVisibleRegionsDirty = true;
2286 const size_t cc = curr.size();
2287 size_t dc = draw.size();
2288
2289 // find the displays that were removed
2290 // (ie: in drawing state but not in current state)
2291 // also handle displays that changed
2292 // (ie: displays that are in both lists)
2293 for (size_t i = 0; i < dc;) {
2294 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2295 if (j < 0) {
2296 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002297 // Call makeCurrent() on the primary display so we can
2298 // be sure that nothing associated with this display
2299 // is current.
2300 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2301 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2302 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2303 if (hw != nullptr) hw->disconnect(getHwComposer());
2304 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2305 mEventThread->onHotplugReceived(draw[i].type, false);
2306 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002307 } else {
2308 // this display is in both lists. see if something changed.
2309 const DisplayDeviceState& state(curr[j]);
2310 const wp<IBinder>& display(curr.keyAt(j));
2311 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2312 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2313 if (state_binder != draw_binder) {
2314 // changing the surface is like destroying and
2315 // recreating the DisplayDevice, so we just remove it
2316 // from the drawing state, so that it get re-added
2317 // below.
2318 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2319 if (hw != nullptr) hw->disconnect(getHwComposer());
2320 mDisplays.removeItem(display);
2321 mDrawingState.displays.removeItemsAt(i);
2322 dc--;
2323 // at this point we must loop to the next item
2324 continue;
2325 }
2326
2327 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2328 if (disp != nullptr) {
2329 if (state.layerStack != draw[i].layerStack) {
2330 disp->setLayerStack(state.layerStack);
2331 }
2332 if ((state.orientation != draw[i].orientation) ||
2333 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2334 disp->setProjection(state.orientation, state.viewport, state.frame);
2335 }
2336 if (state.width != draw[i].width || state.height != draw[i].height) {
2337 disp->setDisplaySize(state.width, state.height);
2338 }
2339 }
2340 }
2341 ++i;
2342 }
2343
2344 // find displays that were added
2345 // (ie: in current state but not in drawing state)
2346 for (size_t i = 0; i < cc; i++) {
2347 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2348 const DisplayDeviceState& state(curr[i]);
2349
2350 sp<DisplaySurface> dispSurface;
2351 sp<IGraphicBufferProducer> producer;
2352 sp<IGraphicBufferProducer> bqProducer;
2353 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002354 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002355
2356 int32_t hwcId = -1;
2357 if (state.isVirtualDisplay()) {
2358 // Virtual displays without a surface are dormant:
2359 // they have external state (layer stack, projection,
2360 // etc.) but no internal state (i.e. a DisplayDevice).
2361 if (state.surface != nullptr) {
2362 // Allow VR composer to use virtual displays.
2363 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2364 int width = 0;
2365 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2366 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2367 int height = 0;
2368 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2369 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2370 int intFormat = 0;
2371 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2372 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2373 auto format = static_cast<android_pixel_format_t>(intFormat);
2374
2375 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2376 }
2377
2378 // TODO: Plumb requested format back up to consumer
2379
2380 sp<VirtualDisplaySurface> vds =
2381 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2382 bqProducer, bqConsumer,
2383 state.displayName);
2384
2385 dispSurface = vds;
2386 producer = vds;
2387 }
2388 } else {
2389 ALOGE_IF(state.surface != nullptr,
2390 "adding a supported display, but rendering "
2391 "surface is provided (%p), ignoring it",
2392 state.surface.get());
2393
2394 hwcId = state.type;
2395 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2396 producer = bqProducer;
2397 }
2398
2399 const wp<IBinder>& display(curr.keyAt(i));
2400 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002401 mDisplays.add(display,
2402 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2403 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002404 if (!state.isVirtualDisplay()) {
2405 mEventThread->onHotplugReceived(state.type, true);
2406 }
2407 }
2408 }
2409 }
2410 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002411
2412 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002413}
2414
Mathias Agopian87baae12012-07-31 12:38:26 -07002415void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002416{
Dan Stoza7dde5992015-05-22 09:51:44 -07002417 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002418 mCurrentState.traverseInZOrder([](Layer* layer) {
2419 layer->notifyAvailableFrames();
2420 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422 /*
2423 * Traversal of the children
2424 * (perform the transaction for each of them if needed)
2425 */
2426
Mathias Agopian3559b072012-08-15 13:46:03 -07002427 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002428 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002430 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431
2432 const uint32_t flags = layer->doTransaction(0);
2433 if (flags & Layer::eVisibleRegion)
2434 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002435 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436 }
2437
2438 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002439 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440 */
2441
Mathias Agopiane57f2922012-08-09 16:29:12 -07002442 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002444 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446
Mathias Agopian84300952012-11-21 16:02:13 -08002447 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2448 // The transform hint might have changed for some layers
2449 // (either because a display has changed, or because a layer
2450 // as changed).
2451 //
2452 // Walk through all the layers in currentLayers,
2453 // and update their transform hint.
2454 //
2455 // If a layer is visible only on a single display, then that
2456 // display is used to calculate the hint, otherwise we use the
2457 // default display.
2458 //
2459 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2460 // the hint is set before we acquire a buffer from the surface texture.
2461 //
2462 // NOTE: layer transactions have taken place already, so we use their
2463 // drawing state. However, SurfaceFlinger's own transaction has not
2464 // happened yet, so we must use the current state layer list
2465 // (soon to become the drawing state list).
2466 //
2467 sp<const DisplayDevice> disp;
2468 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002469 bool first = true;
2470 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002471 // NOTE: we rely on the fact that layers are sorted by
2472 // layerStack first (so we don't have to traverse the list
2473 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002474 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002475 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002476 currentlayerStack = layerStack;
2477 // figure out if this layerstack is mirrored
2478 // (more than one display) if so, pick the default display,
2479 // if not, pick the only display it's on.
2480 disp.clear();
2481 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2482 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002483 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002484 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002485 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002486 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002487 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002488 break;
2489 }
2490 }
2491 }
2492 }
Chet Haase91d25932013-04-11 15:24:55 -07002493
Robert Carr56a0b9a2017-12-04 16:06:13 -08002494 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002495 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002496 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2497 // redraw after transform hint changes. See bug 8508397.
2498
2499 // could be null when this layer is using a layerStack
2500 // that is not visible on any display. Also can occur at
2501 // screen off/on times.
2502 disp = getDefaultDisplayDeviceLocked();
2503 }
2504 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002505 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002506 if (disp != nullptr) {
2507 layer->updateTransformHint(disp);
2508 }
Robert Carr2047fae2016-11-28 14:09:09 -08002509
2510 first = false;
2511 });
Mathias Agopian84300952012-11-21 16:02:13 -08002512 }
2513
2514
Mathias Agopian3559b072012-08-15 13:46:03 -07002515 /*
2516 * Perform our own transaction if needed
2517 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002518
2519 if (mLayersAdded) {
2520 mLayersAdded = false;
2521 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002522 mVisibleRegionsDirty = true;
2523 }
2524
2525 // some layers might have been removed, so
2526 // we need to update the regions they're exposing.
2527 if (mLayersRemoved) {
2528 mLayersRemoved = false;
2529 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002530 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002531 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002532 // this layer is not visible anymore
2533 // TODO: we could traverse the tree from front to back and
2534 // compute the actual visible region
2535 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002536 Region visibleReg;
2537 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002538 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002539 }
Robert Carr2047fae2016-11-28 14:09:09 -08002540 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 }
2542
2543 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002544
2545 updateCursorAsync();
2546}
2547
2548void SurfaceFlinger::updateCursorAsync()
2549{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002550 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2551 auto& displayDevice = mDisplays[displayId];
2552 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002553 continue;
2554 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555
2556 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2557 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002558 }
2559 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002560}
2561
2562void SurfaceFlinger::commitTransaction()
2563{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002564 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002565 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002566 for (const auto& l : mLayersPendingRemoval) {
2567 recordBufferingStats(l->getName().string(),
2568 l->getOccupancyHistory(true));
2569 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002570 }
2571 mLayersPendingRemoval.clear();
2572 }
2573
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002574 // If this transaction is part of a window animation then the next frame
2575 // we composite should be considered an animation as well.
2576 mAnimCompositionPending = mAnimTransactionPending;
2577
Mathias Agopian4fec8732012-06-29 14:12:52 -07002578 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002579 mDrawingState.traverseInZOrder([](Layer* layer) {
2580 layer->commitChildList();
2581 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002582 mTransactionPending = false;
2583 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002584 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585}
2586
Chia-I Wuab0c3192017-08-01 11:29:00 -07002587void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002588 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589{
Mathias Agopian841cde52012-03-01 15:44:37 -08002590 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002591 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 Region aboveOpaqueLayers;
2594 Region aboveCoveredLayers;
2595 Region dirty;
2596
Mathias Agopian87baae12012-07-31 12:38:26 -07002597 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598
Robert Carr2047fae2016-11-28 14:09:09 -08002599 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002601 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602
Jesse Hall01e29052013-02-19 16:13:35 -08002603 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002604 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002605 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002606
Mathias Agopianab028732010-03-16 16:41:46 -07002607 /*
2608 * opaqueRegion: area of a surface that is fully opaque.
2609 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002611
2612 /*
2613 * visibleRegion: area of a surface that is visible on screen
2614 * and not fully transparent. This is essentially the layer's
2615 * footprint minus the opaque regions above it.
2616 * Areas covered by a translucent surface are considered visible.
2617 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002619
2620 /*
2621 * coveredRegion: area of a surface that is covered by all
2622 * visible regions above it (which includes the translucent areas).
2623 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002625
Jesse Halla8026d22012-09-25 13:25:04 -07002626 /*
2627 * transparentRegion: area of a surface that is hinted to be completely
2628 * transparent. This is only used to tell when the layer has no visible
2629 * non-transparent regions and can be removed from the layer list. It
2630 * does not affect the visibleRegion of this layer or any layers
2631 * beneath it. The hint may not be correct if apps don't respect the
2632 * SurfaceView restrictions (which, sadly, some don't).
2633 */
2634 Region transparentRegion;
2635
Mathias Agopianab028732010-03-16 16:41:46 -07002636
2637 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002638 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002639 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002643 if (!visibleRegion.isEmpty()) {
2644 // Remove the transparent area from the visible region
2645 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002646 if (tr.preserveRects()) {
2647 // transform the transparent region
2648 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002649 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002650 // transformation too complex, can't do the
2651 // transparent region optimization.
2652 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002653 }
Mathias Agopianab028732010-03-16 16:41:46 -07002654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655
Mathias Agopianab028732010-03-16 16:41:46 -07002656 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002658 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002659 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2660 // the opaque region is the layer's footprint
2661 opaqueRegion = visibleRegion;
2662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 }
2664 }
2665
Robert Carre5f4f692018-01-12 13:12:28 -08002666 if (visibleRegion.isEmpty()) {
2667 layer->clearVisibilityRegions();
2668 return;
2669 }
2670
Mathias Agopianab028732010-03-16 16:41:46 -07002671 // Clip the covered region to the visible region
2672 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2673
2674 // Update aboveCoveredLayers for next (lower) layer
2675 aboveCoveredLayers.orSelf(visibleRegion);
2676
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 // subtract the opaque region covered by the layers above us
2678 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679
2680 // compute this layer's dirty region
2681 if (layer->contentDirty) {
2682 // we need to invalidate the whole region
2683 dirty = visibleRegion;
2684 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002685 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 layer->contentDirty = false;
2687 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002688 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002689 * the exposed region consists of two components:
2690 * 1) what's VISIBLE now and was COVERED before
2691 * 2) what's EXPOSED now less what was EXPOSED before
2692 *
2693 * note that (1) is conservative, we start with the whole
2694 * visible region but only keep what used to be covered by
2695 * something -- which mean it may have been exposed.
2696 *
2697 * (2) handles areas that were not covered by anything but got
2698 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002699 */
Mathias Agopianab028732010-03-16 16:41:46 -07002700 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002701 const Region oldVisibleRegion = layer->visibleRegion;
2702 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002703 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2704 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 }
2706 dirty.subtractSelf(aboveOpaqueLayers);
2707
2708 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002709 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710
Mathias Agopianab028732010-03-16 16:41:46 -07002711 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002713
Jesse Halla8026d22012-09-25 13:25:04 -07002714 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 layer->setVisibleRegion(visibleRegion);
2716 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002717 layer->setVisibleNonTransparentRegion(
2718 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002719 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720
Mathias Agopian87baae12012-07-31 12:38:26 -07002721 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722}
2723
Chia-I Wuab0c3192017-08-01 11:29:00 -07002724void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002725 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002726 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002727 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002728 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002729 }
2730 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002731}
2732
Dan Stoza6b9454d2014-11-07 16:00:59 -08002733bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 ALOGV("handlePageFlip");
2736
Brian Andersond6927fb2016-07-23 23:37:30 -07002737 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002740 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002741 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002742
2743 // Store the set of layers that need updates. This set must not change as
2744 // buffers are being latched, as this could result in a deadlock.
2745 // Example: Two producers share the same command stream and:
2746 // 1.) Layer 0 is latched
2747 // 2.) Layer 0 gets a new frame
2748 // 2.) Layer 1 gets a new frame
2749 // 3.) Layer 1 is latched.
2750 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2751 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002752 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002753 if (layer->hasQueuedFrame()) {
2754 frameQueued = true;
2755 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002756 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002757 } else {
2758 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002759 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002760 } else {
2761 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002762 }
Robert Carr2047fae2016-11-28 14:09:09 -08002763 });
2764
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002766 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002767 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002768 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002769 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002770 newDataLatched = true;
2771 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002772 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002773
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002774 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002775
2776 // If we will need to wake up at some time in the future to deal with a
2777 // queued frame that shouldn't be displayed during this vsync period, wake
2778 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002779 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002780 signalLayerUpdate();
2781 }
2782
2783 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002784 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785}
2786
Mathias Agopianad456f92011-01-13 17:53:01 -08002787void SurfaceFlinger::invalidateHwcGeometry()
2788{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002790}
2791
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002792
Fabien Sanglard830b8472016-11-30 16:35:58 -08002793void SurfaceFlinger::doDisplayComposition(
2794 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002795 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796{
Dan Stoza71433162014-02-04 16:22:36 -08002797 // We only need to actually compose the display if:
2798 // 1) It is being handled by hardware composer, which may need this to
2799 // keep its virtual display state machine in sync, or
2800 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002801 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002802 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002804 return;
2805 }
2806
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002808 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002809
2810 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002811 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812}
2813
Chia-I Wub02087d2017-11-09 10:19:54 -08002814bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002817
Chia-I Wub02087d2017-11-09 10:19:54 -08002818 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002819 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002821
2822 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002823 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2824 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002825 if (applyColorMatrix) {
2826 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2827 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2828 }
2829
David Sodman105b7dc2017-11-04 20:28:14 -07002830 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 if (hasClientComposition) {
2832 ALOGV("hasClientComposition");
2833
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002834 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002835 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002836 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002837 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2838 }
2839 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2840
Chia-I Wu7f402902017-11-09 12:51:10 -08002841 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002842 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002843 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002844 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002845
2846 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002847 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002848 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2849 }
2850 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002851 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002852
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002853 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002854 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002856 // when using overlays, we assume a fully transparent framebuffer
2857 // NOTE: we could reduce how much we need to clear, for instance
2858 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002859 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002860 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002861 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002862 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002863 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002864 // we're left with the letterbox region
2865 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002867
2868 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002870
Mathias Agopianb9494d52012-04-18 02:28:45 -07002871 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002872 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002873 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002875 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002876 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002877
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002879 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002880 // scissor on the main display. It should never be needed
2881 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002882 const Rect& bounds(displayDevice->getBounds());
2883 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002884 if (scissor != bounds) {
2885 // scissor doesn't match the screen's dimensions, so we
2886 // need to clear everything outside of it and enable
2887 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002888
Mathias Agopianf45c5102012-10-24 16:29:17 -07002889 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002890 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002891 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002892 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002893 }
2894 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002895 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002896
Mathias Agopian85d751c2012-08-29 16:59:24 -07002897 /*
2898 * and then, render the layers targeted at the framebuffer
2899 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002900
Dan Stoza9e56aa02015-11-02 13:00:03 -08002901 ALOGV("Rendering client layers");
2902 const Transform& displayTransform = displayDevice->getTransform();
2903 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002904 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002905 bool firstLayer = true;
2906 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002907 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 displayTransform.transform(layer->visibleRegion)));
2909 ALOGV("Layer: %s", layer->getName().string());
2910 ALOGV(" Composition type: %s",
2911 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002912 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002913 switch (layer->getCompositionType(hwcId)) {
2914 case HWC2::Composition::Cursor:
2915 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002916 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002918 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002919 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002920 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002921 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002922 // never clear the very first layer since we're
2923 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002924 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002925 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002926 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002927 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002928 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002929 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002930 break;
2931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002933 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002934 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 } else {
2936 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002939 }
2940 } else {
2941 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002943 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002945 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002946 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002947 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002948 }
2949 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002950
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002951 if (applyColorMatrix) {
2952 getRenderEngine().setupColorTransform(oldColorMatrix);
2953 }
2954
Mathias Agopianf45c5102012-10-24 16:29:17 -07002955 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002956 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002957 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958}
2959
Fabien Sanglard830b8472016-11-30 16:35:58 -08002960void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2961 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002962 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002963 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964}
2965
Dan Stoza7d89d062015-04-30 13:29:25 -07002966status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002967 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002968 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002969 const sp<Layer>& lbc,
2970 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002971{
Dan Stoza7d89d062015-04-30 13:29:25 -07002972 // add this layer to the current state list
2973 {
2974 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002975 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002976 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2977 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002978 return NO_MEMORY;
2979 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002980 if (parent == nullptr) {
2981 mCurrentState.layersSortedByZ.add(lbc);
2982 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002983 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002984 ALOGE("addClientLayer called with a removed parent");
2985 return NAME_NOT_FOUND;
2986 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002987 parent->addChild(lbc);
2988 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002989
Dan Stoza101d8dc2018-02-27 15:42:25 -08002990 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002991 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2992 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2993 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2994 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2995 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 mLayersAdded = true;
2997 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002998 }
2999
Mathias Agopian96f08192010-06-02 23:28:45 -07003000 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003001 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003002
Dan Stoza7d89d062015-04-30 13:29:25 -07003003 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003004}
3005
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003006status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003007 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003008 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3009}
Robert Carr7f9b8992017-03-10 11:08:39 -08003010
chaviwca27f252018-02-06 16:46:39 -08003011status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3012 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003013 if (layer->isPendingRemoval()) {
3014 return NO_ERROR;
3015 }
3016
Robert Carr1f0a16a2016-10-24 16:27:39 -07003017 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003018 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003019 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003020 if (topLevelOnly) {
3021 return NO_ERROR;
3022 }
3023
Chia-I Wu98f1c102017-05-30 14:54:08 -07003024 sp<Layer> ancestor = p;
3025 while (ancestor->getParent() != nullptr) {
3026 ancestor = ancestor->getParent();
3027 }
3028 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3029 ALOGE("removeLayer called with a layer whose parent has been removed");
3030 return NAME_NOT_FOUND;
3031 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003032
3033 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003034 } else {
3035 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003036 }
3037
Robert Carr136e2f62017-02-08 17:54:29 -08003038 // As a matter of normal operation, the LayerCleaner will produce a second
3039 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3040 // so we will succeed in promoting it, but it's already been removed
3041 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3042 // otherwise something has gone wrong and we are leaking the layer.
3043 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003044 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3045 layer->getName().string(),
3046 (p != nullptr) ? p->getName().string() : "no-parent");
3047 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003048 } else if (index < 0) {
3049 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003050 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003051
Chia-I Wuc6657022017-08-15 11:18:17 -07003052 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003053 mLayersPendingRemoval.add(layer);
3054 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003055 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003056 setTransactionFlags(eTransactionNeeded);
3057 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058}
3059
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003060uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003061 return android_atomic_release_load(&mTransactionFlags);
3062}
3063
Mathias Agopian3f844832013-08-07 21:24:32 -07003064uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3066}
3067
Mathias Agopian3f844832013-08-07 21:24:32 -07003068uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3070 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003071 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 }
3073 return old;
3074}
3075
chaviwca27f252018-02-06 16:46:39 -08003076bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3077 for (const ComposerState& state : states) {
3078 // Here we need to check that the interface we're given is indeed
3079 // one of our own. A malicious client could give us a nullptr
3080 // IInterface, or one of its own or even one of our own but a
3081 // different type. All these situations would cause us to crash.
3082 if (state.client == nullptr) {
3083 return true;
3084 }
3085
3086 sp<IBinder> binder = IInterface::asBinder(state.client);
3087 if (binder == nullptr) {
3088 return true;
3089 }
3090
3091 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3092 return true;
3093 }
3094 }
3095 return false;
3096}
3097
Mathias Agopian8b33f032012-07-24 20:43:54 -07003098void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003099 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003100 const Vector<DisplayState>& displays,
3101 uint32_t flags)
3102{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003103 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003104 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003105 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003106
chaviwca27f252018-02-06 16:46:39 -08003107 if (containsAnyInvalidClientState(states)) {
3108 return;
3109 }
3110
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003111 if (flags & eAnimation) {
3112 // For window updates that are part of an animation we must wait for
3113 // previous animation "frames" to be handled.
3114 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003115 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003116 if (CC_UNLIKELY(err != NO_ERROR)) {
3117 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003118 // caller after a few seconds.
3119 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3120 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003121 mAnimTransactionPending = false;
3122 break;
3123 }
3124 }
3125 }
3126
chaviwca27f252018-02-06 16:46:39 -08003127 for (const DisplayState& display : displays) {
3128 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003129 }
3130
chaviwca27f252018-02-06 16:46:39 -08003131 for (const ComposerState& state : states) {
3132 transactionFlags |= setClientStateLocked(state);
3133 }
3134
3135 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3136 // as destroyed should only occur after setting all other states. This is to allow for a
3137 // child re-parent to happen before marking its original parent as destroyed (which would
3138 // then mark the child as destroyed).
3139 for (const ComposerState& state : states) {
3140 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003141 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003142
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003143 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3144 // anyway. This can be used as a flush mechanism for previous async transactions.
3145 // Empty animation transaction can be used to simulate back-pressure, so also force a
3146 // transaction for empty animation transactions.
3147 if (transactionFlags == 0 &&
3148 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003149 transactionFlags = eTransactionNeeded;
3150 }
3151
Mathias Agopian386aa982011-11-07 21:58:03 -08003152 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003153 if (mInterceptor->isEnabled()) {
3154 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003155 }
Irvel468051e2016-06-13 16:44:44 -07003156
Mathias Agopian386aa982011-11-07 21:58:03 -08003157 // this triggers the transaction
3158 setTransactionFlags(transactionFlags);
3159
3160 // if this is a synchronous transaction, wait for it to take effect
3161 // before returning.
3162 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003163 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003164 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003165 if (flags & eAnimation) {
3166 mAnimTransactionPending = true;
3167 }
3168 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003169 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3170 if (CC_UNLIKELY(err != NO_ERROR)) {
3171 // just in case something goes wrong in SF, return to the
3172 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003173 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3174 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003175 break;
3176 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 }
3179}
3180
Mathias Agopiane57f2922012-08-09 16:29:12 -07003181uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3182{
Jesse Hall9a143922012-10-04 16:29:19 -07003183 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3184 if (dpyIdx < 0)
3185 return 0;
3186
Mathias Agopiane57f2922012-08-09 16:29:12 -07003187 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003188 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003189 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003190 const uint32_t what = s.what;
3191 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003192 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003193 disp.surface = s.surface;
3194 flags |= eDisplayTransactionNeeded;
3195 }
3196 }
3197 if (what & DisplayState::eLayerStackChanged) {
3198 if (disp.layerStack != s.layerStack) {
3199 disp.layerStack = s.layerStack;
3200 flags |= eDisplayTransactionNeeded;
3201 }
3202 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003203 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003204 if (disp.orientation != s.orientation) {
3205 disp.orientation = s.orientation;
3206 flags |= eDisplayTransactionNeeded;
3207 }
3208 if (disp.frame != s.frame) {
3209 disp.frame = s.frame;
3210 flags |= eDisplayTransactionNeeded;
3211 }
3212 if (disp.viewport != s.viewport) {
3213 disp.viewport = s.viewport;
3214 flags |= eDisplayTransactionNeeded;
3215 }
3216 }
Michael Lentine47e45402014-07-18 15:34:25 -07003217 if (what & DisplayState::eDisplaySizeChanged) {
3218 if (disp.width != s.width) {
3219 disp.width = s.width;
3220 flags |= eDisplayTransactionNeeded;
3221 }
3222 if (disp.height != s.height) {
3223 disp.height = s.height;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003227 }
3228 return flags;
3229}
3230
chaviwca27f252018-02-06 16:46:39 -08003231uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3232 const layer_state_t& s = composerState.state;
3233 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3234
Mathias Agopian13127d82013-03-05 17:47:11 -08003235 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003236 if (layer == nullptr) {
3237 return 0;
3238 }
3239
3240 if (layer->isPendingRemoval()) {
3241 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3242 return 0;
3243 }
3244
3245 uint32_t flags = 0;
3246
3247 const uint32_t what = s.what;
3248 bool geometryAppliesWithResize =
3249 what & layer_state_t::eGeometryAppliesWithResize;
3250 if (what & layer_state_t::ePositionChanged) {
3251 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3252 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003253 }
chaviw8b3871a2017-11-01 17:41:01 -07003254 }
3255 if (what & layer_state_t::eLayerChanged) {
3256 // NOTE: index needs to be calculated before we update the state
3257 const auto& p = layer->getParent();
3258 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003259 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003260 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003261 mCurrentState.layersSortedByZ.removeAt(idx);
3262 mCurrentState.layersSortedByZ.add(layer);
3263 // we need traversal (state changed)
3264 // AND transaction (list changed)
3265 flags |= eTransactionNeeded|eTraversalNeeded;
3266 }
chaviw8b3871a2017-11-01 17:41:01 -07003267 } else {
3268 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003269 flags |= eTransactionNeeded|eTraversalNeeded;
3270 }
3271 }
chaviw8b3871a2017-11-01 17:41:01 -07003272 }
3273 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003274 // NOTE: index needs to be calculated before we update the state
3275 const auto& p = layer->getParent();
3276 if (p == nullptr) {
3277 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3278 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3279 mCurrentState.layersSortedByZ.removeAt(idx);
3280 mCurrentState.layersSortedByZ.add(layer);
3281 // we need traversal (state changed)
3282 // AND transaction (list changed)
3283 flags |= eTransactionNeeded|eTraversalNeeded;
3284 }
3285 } else {
3286 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3287 flags |= eTransactionNeeded|eTraversalNeeded;
3288 }
chaviw8b3871a2017-11-01 17:41:01 -07003289 }
3290 }
3291 if (what & layer_state_t::eSizeChanged) {
3292 if (layer->setSize(s.w, s.h)) {
3293 flags |= eTraversalNeeded;
3294 }
3295 }
3296 if (what & layer_state_t::eAlphaChanged) {
3297 if (layer->setAlpha(s.alpha))
3298 flags |= eTraversalNeeded;
3299 }
3300 if (what & layer_state_t::eColorChanged) {
3301 if (layer->setColor(s.color))
3302 flags |= eTraversalNeeded;
3303 }
3304 if (what & layer_state_t::eMatrixChanged) {
3305 if (layer->setMatrix(s.matrix))
3306 flags |= eTraversalNeeded;
3307 }
3308 if (what & layer_state_t::eTransparentRegionChanged) {
3309 if (layer->setTransparentRegionHint(s.transparentRegion))
3310 flags |= eTraversalNeeded;
3311 }
3312 if (what & layer_state_t::eFlagsChanged) {
3313 if (layer->setFlags(s.flags, s.mask))
3314 flags |= eTraversalNeeded;
3315 }
3316 if (what & layer_state_t::eCropChanged) {
3317 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3318 flags |= eTraversalNeeded;
3319 }
3320 if (what & layer_state_t::eFinalCropChanged) {
3321 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3322 flags |= eTraversalNeeded;
3323 }
3324 if (what & layer_state_t::eLayerStackChanged) {
3325 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3326 // We only allow setting layer stacks for top level layers,
3327 // everything else inherits layer stack from its parent.
3328 if (layer->hasParent()) {
3329 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3330 layer->getName().string());
3331 } else if (idx < 0) {
3332 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3333 "that also does not appear in the top level layer list. Something"
3334 " has gone wrong.", layer->getName().string());
3335 } else if (layer->setLayerStack(s.layerStack)) {
3336 mCurrentState.layersSortedByZ.removeAt(idx);
3337 mCurrentState.layersSortedByZ.add(layer);
3338 // we need traversal (state changed)
3339 // AND transaction (list changed)
3340 flags |= eTransactionNeeded|eTraversalNeeded;
3341 }
3342 }
3343 if (what & layer_state_t::eDeferTransaction) {
3344 if (s.barrierHandle != nullptr) {
3345 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3346 } else if (s.barrierGbp != nullptr) {
3347 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3348 if (authenticateSurfaceTextureLocked(gbp)) {
3349 const auto& otherLayer =
3350 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3351 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3352 } else {
3353 ALOGE("Attempt to defer transaction to to an"
3354 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003355 }
3356 }
chaviw8b3871a2017-11-01 17:41:01 -07003357 // We don't trigger a traversal here because if no other state is
3358 // changed, we don't want this to cause any more work
3359 }
3360 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003361 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003362 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003363 if (!hadParent) {
3364 mCurrentState.layersSortedByZ.remove(layer);
3365 }
chaviw8b3871a2017-11-01 17:41:01 -07003366 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003367 }
chaviw8b3871a2017-11-01 17:41:01 -07003368 }
3369 if (what & layer_state_t::eReparentChildren) {
3370 if (layer->reparentChildren(s.reparentHandle)) {
3371 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003372 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 }
chaviw8b3871a2017-11-01 17:41:01 -07003374 if (what & layer_state_t::eDetachChildren) {
3375 layer->detachChildren();
3376 }
3377 if (what & layer_state_t::eOverrideScalingModeChanged) {
3378 layer->setOverrideScalingMode(s.overrideScalingMode);
3379 // We don't trigger a traversal here because if no other state is
3380 // changed, we don't want this to cause any more work
3381 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382 return flags;
3383}
3384
chaviwca27f252018-02-06 16:46:39 -08003385void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3386 const layer_state_t& state = composerState.state;
3387 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3388
3389 sp<Layer> layer(client->getLayerUser(state.surface));
3390 if (layer == nullptr) {
3391 return;
3392 }
3393
3394 if (layer->isPendingRemoval()) {
3395 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3396 return;
3397 }
3398
3399 if (state.what & layer_state_t::eDestroySurface) {
3400 removeLayerLocked(mStateLock, layer);
3401 }
3402}
3403
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003404status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003405 const String8& name,
3406 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003407 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003408 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003409 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003410{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003411 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003412 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003413 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003414 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003415 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003416
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003417 status_t result = NO_ERROR;
3418
3419 sp<Layer> layer;
3420
Cody Northropbc755282017-03-31 12:00:08 -06003421 String8 uniqueName = getUniqueLayerName(name);
3422
Mathias Agopian3165cc22012-08-08 19:42:09 -07003423 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3424 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003425 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003426 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003427 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003429 break;
chaviw13fdc492017-06-27 12:40:18 -07003430 case ISurfaceComposerClient::eFXSurfaceColor:
3431 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003432 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003433 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003434 break;
3435 default:
3436 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437 break;
3438 }
3439
Dan Stoza7d89d062015-04-30 13:29:25 -07003440 if (result != NO_ERROR) {
3441 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003443
Chia-I Wuab0c3192017-08-01 11:29:00 -07003444 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3445 // TODO b/64227542
3446 if (windowType == 441731) {
3447 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3448 layer->setPrimaryDisplayOnly();
3449 }
3450
Albert Chaulk479c60c2017-01-27 14:21:34 -05003451 layer->setInfo(windowType, ownerUid);
3452
Robert Carr1f0a16a2016-10-24 16:27:39 -07003453 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003454 if (result != NO_ERROR) {
3455 return result;
3456 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003457 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003458
3459 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003460 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461}
3462
Cody Northropbc755282017-03-31 12:00:08 -06003463String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3464{
3465 bool matchFound = true;
3466 uint32_t dupeCounter = 0;
3467
3468 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3469 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3470
3471 // Loop over layers until we're sure there is no matching name
3472 while (matchFound) {
3473 matchFound = false;
3474 mDrawingState.traverseInZOrder([&](Layer* layer) {
3475 if (layer->getName() == uniqueName) {
3476 matchFound = true;
3477 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3478 }
3479 });
3480 }
3481
3482 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3483
3484 return uniqueName;
3485}
3486
David Sodman0c69cad2017-08-21 12:12:51 -07003487status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003488 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3489 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490{
3491 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003492 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493 case PIXEL_FORMAT_TRANSPARENT:
3494 case PIXEL_FORMAT_TRANSLUCENT:
3495 format = PIXEL_FORMAT_RGBA_8888;
3496 break;
3497 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003498 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499 break;
3500 }
3501
David Sodman0c69cad2017-08-21 12:12:51 -07003502 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3503 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003504 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003505 *handle = layer->getHandle();
3506 *gbp = layer->getProducer();
3507 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003509
David Sodman0c69cad2017-08-21 12:12:51 -07003510 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512}
3513
chaviw13fdc492017-06-27 12:40:18 -07003514status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003515 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003516 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517{
chaviw13fdc492017-06-27 12:40:18 -07003518 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003521}
3522
Mathias Agopianac9fa422013-02-11 16:40:36 -08003523status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524{
Robert Carr9524cb32017-02-13 11:32:32 -08003525 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003526 status_t err = NO_ERROR;
3527 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003528 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003529 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003530 err = removeLayer(l);
3531 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3532 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003533 }
3534 return err;
3535}
3536
Mathias Agopian13127d82013-03-05 17:47:11 -08003537status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003538{
Mathias Agopian67106042013-03-14 19:18:13 -07003539 // called by ~LayerCleaner() when all references to the IBinder (handle)
3540 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003541 sp<Layer> l = layer.promote();
3542 if (l == nullptr) {
3543 // The layer has already been removed, carry on
3544 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003545 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003546 // If we have a parent, then we can continue to live as long as it does.
3547 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548}
3549
Mathias Agopianb60314a2012-04-10 22:09:54 -07003550// ---------------------------------------------------------------------------
3551
Andy McFadden13a082e2012-08-24 10:16:42 -07003552void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003553 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003554 Vector<ComposerState> state;
3555 Vector<DisplayState> displays;
3556 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003557 d.what = DisplayState::eDisplayProjectionChanged |
3558 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003559 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003560 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003561 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003562 d.frame.makeInvalid();
3563 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003564 d.width = 0;
3565 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003566 displays.add(d);
3567 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003568 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3569 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003570
David Sodman105b7dc2017-11-04 20:28:14 -07003571 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003572 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003573 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003574
Brian Andersond0010582017-03-07 13:20:31 -08003575 // Use phase of 0 since phase is not known.
3576 // Use latency of 0, which will snap to the ideal latency.
3577 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003578}
3579
3580void SurfaceFlinger::initializeDisplays() {
3581 class MessageScreenInitialized : public MessageBase {
3582 SurfaceFlinger* flinger;
3583 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003584 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003585 virtual bool handler() {
3586 flinger->onInitializeDisplays();
3587 return true;
3588 }
3589 };
3590 sp<MessageBase> msg = new MessageScreenInitialized(this);
3591 postMessageAsync(msg); // we may be called from main thread, use async message
3592}
3593
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003594void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003595 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003596 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3597 this);
3598 int32_t type = hw->getDisplayType();
3599 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003600
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003601 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003602 return;
3603 }
3604
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003605 hw->setPowerMode(mode);
3606 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3607 ALOGW("Trying to set power mode for virtual display");
3608 return;
3609 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003610
Lloyd Pique4d234852018-01-22 17:21:36 -08003611 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003612 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003613 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3614 if (idx < 0) {
3615 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3616 return;
3617 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003618 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003619 }
3620
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003621 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003622 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003623 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003624 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3625 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003626 // FIXME: eventthread only knows about the main display right now
3627 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003628 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003629 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003631 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003632 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003633 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003634
3635 struct sched_param param = {0};
3636 param.sched_priority = 1;
3637 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3638 ALOGW("Couldn't set SCHED_FIFO on display on");
3639 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003640 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003641 // Turn off the display
3642 struct sched_param param = {0};
3643 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3644 ALOGW("Couldn't set SCHED_OTHER on display off");
3645 }
3646
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003647 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3648 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003649 disableHardwareVsync(true); // also cancels any in-progress resync
3650
Mathias Agopiancde87a32012-09-13 14:09:01 -07003651 // FIXME: eventthread only knows about the main display right now
3652 mEventThread->onScreenReleased();
3653 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003654
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003655 getHwComposer().setPowerMode(type, mode);
3656 mVisibleRegionsDirty = true;
3657 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003658 } else if (mode == HWC_POWER_MODE_DOZE ||
3659 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003660 // Update display while dozing
3661 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003662 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3663 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003664 // FIXME: eventthread only knows about the main display right now
3665 mEventThread->onScreenAcquired();
3666 resyncToHardwareVsync(true);
3667 }
3668 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3669 // Leave display going to doze
3670 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3671 disableHardwareVsync(true); // also cancels any in-progress resync
3672 // FIXME: eventthread only knows about the main display right now
3673 mEventThread->onScreenReleased();
3674 }
3675 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003676 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003677 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003678 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003679 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003680 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003681}
3682
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003683void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3684 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003685 SurfaceFlinger& mFlinger;
3686 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003687 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003688 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003689 MessageSetPowerMode(SurfaceFlinger& flinger,
3690 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3691 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003692 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003693 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003694 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003696 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003697 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003698 ALOGW("Attempt to set power mode = %d for virtual display",
3699 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003700 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003701 mFlinger.setPowerModeInternal(
3702 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003703 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003704 return true;
3705 }
3706 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003708 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003709}
3710
3711// ---------------------------------------------------------------------------
3712
Lloyd Pique755e3192018-01-31 16:46:15 -08003713status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3714 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003716
Mathias Agopianbd115332013-04-18 16:41:04 -07003717 IPCThreadState* ipc = IPCThreadState::self();
3718 const int pid = ipc->getCallingPid();
3719 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003720
Mathias Agopianbd115332013-04-18 16:41:04 -07003721 if ((uid != AID_SHELL) &&
3722 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003723 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003724 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003726 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003727 // (this would indicate SF is stuck, but we want to be able to
3728 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003729 status_t err = mStateLock.timedLock(s2ns(1));
3730 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003731 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003732 result.appendFormat(
3733 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3734 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003735 }
3736
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003737 bool dumpAll = true;
3738 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003739 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003740
3741 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003742 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003743 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3744 dumpAll = false;
3745 }
3746
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003747 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003748 if ((index < numArgs) &&
3749 (args[index] == String16("--list"))) {
3750 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003751 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003752 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003753 }
3754
3755 if ((index < numArgs) &&
3756 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003758 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003759 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003760 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003761
3762 if ((index < numArgs) &&
3763 (args[index] == String16("--latency-clear"))) {
3764 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003765 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003766 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003767 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003768
3769 if ((index < numArgs) &&
3770 (args[index] == String16("--dispsync"))) {
3771 index++;
3772 mPrimaryDispSync.dump(result);
3773 dumpAll = false;
3774 }
Dan Stozab90cf072015-03-05 11:05:59 -08003775
3776 if ((index < numArgs) &&
3777 (args[index] == String16("--static-screen"))) {
3778 index++;
3779 dumpStaticScreenStats(result);
3780 dumpAll = false;
3781 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003782
3783 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003784 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003785 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003786 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003787 dumpAll = false;
3788 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003789
3790 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3791 index++;
3792 dumpWideColorInfo(result);
3793 dumpAll = false;
3794 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003795
3796 if ((index < numArgs) &&
3797 (args[index] == String16("--enable-layer-stats"))) {
3798 index++;
3799 mLayerStats.enable();
3800 dumpAll = false;
3801 }
3802
3803 if ((index < numArgs) &&
3804 (args[index] == String16("--disable-layer-stats"))) {
3805 index++;
3806 mLayerStats.disable();
3807 dumpAll = false;
3808 }
3809
3810 if ((index < numArgs) &&
3811 (args[index] == String16("--clear-layer-stats"))) {
3812 index++;
3813 mLayerStats.clear();
3814 dumpAll = false;
3815 }
3816
3817 if ((index < numArgs) &&
3818 (args[index] == String16("--dump-layer-stats"))) {
3819 index++;
3820 mLayerStats.dump(result);
3821 dumpAll = false;
3822 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003824
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003825 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003827 }
3828
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 if (locked) {
3830 mStateLock.unlock();
3831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832 }
3833 write(fd, result.string(), result.size());
3834 return NO_ERROR;
3835}
3836
Dan Stozac7014012014-02-14 15:03:43 -08003837void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3838 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003839{
Robert Carr2047fae2016-11-28 14:09:09 -08003840 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003841 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003842 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843}
3844
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003846 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847{
3848 String8 name;
3849 if (index < args.size()) {
3850 name = String8(args[index]);
3851 index++;
3852 }
3853
David Sodman105b7dc2017-11-04 20:28:14 -07003854 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003855 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003856 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003857
3858 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003859 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003860 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003861 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003862 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003863 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003864 }
Robert Carr2047fae2016-11-28 14:09:09 -08003865 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003866 }
3867}
3868
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003869void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003870 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003871{
3872 String8 name;
3873 if (index < args.size()) {
3874 name = String8(args[index]);
3875 index++;
3876 }
3877
Robert Carr2047fae2016-11-28 14:09:09 -08003878 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003879 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003880 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003881 }
Robert Carr2047fae2016-11-28 14:09:09 -08003882 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003883
Svetoslavd85084b2014-03-20 10:28:31 -07003884 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003885}
3886
Jamie Gennis6547ff42013-07-16 20:12:42 -07003887// This should only be called from the main thread. Otherwise it would need
3888// the lock and should use mCurrentState rather than mDrawingState.
3889void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003890 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003891 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003892 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003893
3894 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3895}
3896
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003897void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003898{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003899 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003900
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003901 if (isLayerTripleBufferingDisabled())
3902 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003903
3904 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003905 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003906 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003907 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003908 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3909 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003910 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003911}
3912
Dan Stozab90cf072015-03-05 11:05:59 -08003913void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3914{
3915 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003916 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3917 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003918 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003919 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003920 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3921 b + 1, bucketTimeSec, percent);
3922 }
David Sodman4a36e932017-11-07 14:29:47 -08003923 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003924 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003925 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003926 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003927 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003928}
3929
Dan Stozae77c7662016-05-13 11:37:28 -07003930void SurfaceFlinger::recordBufferingStats(const char* layerName,
3931 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003932 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3933 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003934 for (const auto& segment : history) {
3935 if (!segment.usedThirdBuffer) {
3936 stats.twoBufferTime += segment.totalTime;
3937 }
3938 if (segment.occupancyAverage < 1.0f) {
3939 stats.doubleBufferedTime += segment.totalTime;
3940 } else if (segment.occupancyAverage < 2.0f) {
3941 stats.tripleBufferedTime += segment.totalTime;
3942 }
3943 ++stats.numSegments;
3944 stats.totalTime += segment.totalTime;
3945 }
3946}
3947
Brian Andersond6927fb2016-07-23 23:37:30 -07003948void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3949 result.appendFormat("Layer frame timestamps:\n");
3950
3951 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3952 const size_t count = currentLayers.size();
3953 for (size_t i=0 ; i<count ; i++) {
3954 currentLayers[i]->dumpFrameEvents(result);
3955 }
3956}
3957
Dan Stozae77c7662016-05-13 11:37:28 -07003958void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3959 result.append("Buffering stats:\n");
3960 result.append(" [Layer name] <Active time> <Two buffer> "
3961 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003962 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003963 typedef std::tuple<std::string, float, float, float> BufferTuple;
3964 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003965 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003966 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003967 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003968 if (stats.numSegments == 0) {
3969 continue;
3970 }
3971 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3972 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3973 stats.totalTime;
3974 float doubleBufferRatio = static_cast<float>(
3975 stats.doubleBufferedTime) / stats.totalTime;
3976 float tripleBufferRatio = static_cast<float>(
3977 stats.tripleBufferedTime) / stats.totalTime;
3978 sorted.insert({activeTime, {name, twoBufferRatio,
3979 doubleBufferRatio, tripleBufferRatio}});
3980 }
3981 for (const auto& sortedPair : sorted) {
3982 float activeTime = sortedPair.first;
3983 const BufferTuple& values = sortedPair.second;
3984 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3985 std::get<0>(values).c_str(), activeTime,
3986 std::get<1>(values), std::get<2>(values),
3987 std::get<3>(values));
3988 }
3989 result.append("\n");
3990}
3991
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003992void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3993 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003994 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003995
3996 // TODO: print out if wide-color mode is active or not
3997
3998 for (size_t d = 0; d < mDisplays.size(); d++) {
3999 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4000 int32_t hwcId = displayDevice->getHwcDisplayId();
4001 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4002 continue;
4003 }
4004
4005 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004006 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004007 for (auto&& mode : modes) {
4008 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4009 }
4010
Peiyong Lina52f0292018-03-14 17:26:31 -07004011 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004012 result.appendFormat(" Current color mode: %s (%d)\n",
4013 decodeColorMode(currentMode).c_str(), currentMode);
4014 }
4015 result.append("\n");
4016}
4017
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004018LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004019 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004020 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4021 const State& state = useDrawing ? mDrawingState : mCurrentState;
4022 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004023 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004024 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004025 });
4026
4027 return layersProto;
4028}
4029
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004030LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4031 LayersProto layersProto;
4032
4033 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
4034 SizeProto* resolution = layersProto.mutable_resolution();
4035 resolution->set_w(displayDevice->getWidth());
4036 resolution->set_h(displayDevice->getHeight());
4037
4038 mDrawingState.traverseInZOrder([&](Layer* layer) {
4039 if (!layer->visibleRegion.isEmpty() &&
4040 layer->getBE().mHwcLayers.count(hwcId)) {
4041 LayerProto* layerProto = layersProto.add_layers();
4042 layer->writeToProto(layerProto, hwcId);
4043 }
4044 });
4045
4046 return layersProto;
4047}
4048
Mathias Agopian74d211a2013-04-22 16:55:35 +02004049void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4050 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004051{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004052 bool colorize = false;
4053 if (index < args.size()
4054 && (args[index] == String16("--color"))) {
4055 colorize = true;
4056 index++;
4057 }
4058
4059 Colorizer colorizer(colorize);
4060
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004061 // figure out if we're stuck somewhere
4062 const nsecs_t now = systemTime();
4063 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4064 const nsecs_t inTransaction(mDebugInTransaction);
4065 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4066 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4067
4068 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004069 * Dump library configuration.
4070 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004071
4072 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004073 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004074 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004075 appendSfConfigString(result);
4076 appendUiConfigString(result);
4077 appendGuiConfigString(result);
4078 result.append("\n");
4079
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004080 result.append("\nWide-Color information:\n");
4081 dumpWideColorInfo(result);
4082
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004083 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004084 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004085 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004086 result.append(SyncFeatures::getInstance().toString());
4087 result.append("\n");
4088
David Sodman105b7dc2017-11-04 20:28:14 -07004089 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004090
Andy McFadden41d67d72014-04-25 16:58:34 -07004091 colorizer.bold(result);
4092 result.append("DispSync configuration: ");
4093 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004094 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004095 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004096 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004097 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004098 result.append("\n");
4099
Dan Stozab90cf072015-03-05 11:05:59 -08004100 // Dump static screen stats
4101 result.append("\n");
4102 dumpStaticScreenStats(result);
4103 result.append("\n");
4104
Dan Stozae77c7662016-05-13 11:37:28 -07004105 dumpBufferingStats(result);
4106
Andy McFadden4803b742012-09-24 19:07:20 -07004107 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004108 * Dump the visible layer list
4109 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004110 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004111 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004112 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4113 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004114 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004115
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004116 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004117 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004118 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004119 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004120
4121 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004122 * Dump Display state
4123 */
4124
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004125 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004126 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004127 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004128 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4129 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004130 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004131 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004132 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004133
4134 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004135 * Dump SurfaceFlinger global state
4136 */
4137
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004138 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004140 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141
Mathias Agopian888c8222012-08-04 21:10:38 -07004142 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004143 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004144
David Sodmanbc815282017-11-05 18:57:52 -08004145 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004147 if (hw) {
4148 hw->undefinedRegion.dump(result, "undefinedRegion");
4149 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4150 hw->getOrientation(), hw->isDisplayOn());
4151 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004152 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004153 " last eglSwapBuffers() time: %f us\n"
4154 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004155 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156 " refresh-rate : %f fps\n"
4157 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004158 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004159 " gpu_to_cpu_unsupported : %d\n"
4160 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004161 mLastSwapBufferTime/1000.0,
4162 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004163 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004164 1e9 / activeConfig->getVsyncPeriod(),
4165 activeConfig->getDpiX(),
4166 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004167 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004168
Mathias Agopian74d211a2013-04-22 16:55:35 +02004169 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004170 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004171
Mathias Agopian74d211a2013-04-22 16:55:35 +02004172 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004173 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004174
4175 /*
4176 * VSYNC state
4177 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004178 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004179 result.append("\n");
4180
4181 /*
4182 * HWC layer minidump
4183 */
4184 for (size_t d = 0; d < mDisplays.size(); d++) {
4185 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4186 int32_t hwcId = displayDevice->getHwcDisplayId();
4187 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4188 continue;
4189 }
4190
4191 result.appendFormat("Display %d HWC layers:\n", hwcId);
4192 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004194 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004195 });
Dan Stozae22aec72016-08-01 13:20:59 -07004196 result.append("\n");
4197 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198
4199 /*
4200 * Dump HWComposer state
4201 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004203 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004204 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004205 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004206 result.appendFormat(" h/w composer %s\n",
4207 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004208 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004209
4210 /*
4211 * Dump gralloc state
4212 */
4213 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4214 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004215
4216 /*
4217 * Dump VrFlinger state if in use.
4218 */
4219 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4220 result.append("VrFlinger state:\n");
4221 result.append(mVrFlinger->Dump().c_str());
4222 result.append("\n");
4223 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224}
4225
Mathias Agopian13127d82013-03-05 17:47:11 -08004226const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004227SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004228 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004229 wp<IBinder> dpy;
4230 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4231 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4232 dpy = mDisplays.keyAt(i);
4233 break;
4234 }
4235 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004236 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004237 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4238 // Just use the primary display so we have something to return
4239 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4240 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004241 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004242}
4243
Keun young Park63f165f2012-08-31 10:53:36 -07004244bool SurfaceFlinger::startDdmConnection()
4245{
4246 void* libddmconnection_dso =
4247 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4248 if (!libddmconnection_dso) {
4249 return false;
4250 }
4251 void (*DdmConnection_start)(const char* name);
4252 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004253 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004254 if (!DdmConnection_start) {
4255 dlclose(libddmconnection_dso);
4256 return false;
4257 }
4258 (*DdmConnection_start)(getServiceName());
4259 return true;
4260}
4261
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004262status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004263 switch (code) {
4264 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004265 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004266 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004267 case CLEAR_ANIMATION_FRAME_STATS:
4268 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004269 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004270 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004271 case ENABLE_VSYNC_INJECTIONS:
4272 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 {
4274 // codes that require permission check
4275 IPCThreadState* ipc = IPCThreadState::self();
4276 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004277 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004278 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004279 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004280 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004281 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004282 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004283 break;
4284 }
Robert Carr1db73f62016-12-21 12:58:51 -08004285 /*
4286 * Calling setTransactionState is safe, because you need to have been
4287 * granted a reference to Client* and Handle* to do anything with it.
4288 *
4289 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4290 */
4291 case SET_TRANSACTION_STATE:
4292 case CREATE_SCOPED_CONNECTION:
4293 {
4294 return OK;
4295 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004296 case CAPTURE_SCREEN:
4297 {
4298 // codes that require permission check
4299 IPCThreadState* ipc = IPCThreadState::self();
4300 const int pid = ipc->getCallingPid();
4301 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004302 if ((uid != AID_GRAPHICS) &&
4303 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004304 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004305 return PERMISSION_DENIED;
4306 }
4307 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 }
chaviwa76b2712017-09-20 12:02:26 -07004309 case CAPTURE_LAYERS: {
4310 IPCThreadState* ipc = IPCThreadState::self();
4311 const int pid = ipc->getCallingPid();
4312 const int uid = ipc->getCallingUid();
4313 if ((uid != AID_GRAPHICS) &&
4314 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4315 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4316 return PERMISSION_DENIED;
4317 }
4318 break;
4319 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004320 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004321 return OK;
4322}
4323
4324status_t SurfaceFlinger::onTransact(
4325 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4326{
4327 status_t credentialCheck = CheckTransactCodeCredentials(code);
4328 if (credentialCheck != OK) {
4329 return credentialCheck;
4330 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004331
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004332 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4333 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004334 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004335 IPCThreadState* ipc = IPCThreadState::self();
4336 const int uid = ipc->getCallingUid();
4337 if (CC_UNLIKELY(uid != AID_SYSTEM
4338 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004339 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004340 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004341 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004342 return PERMISSION_DENIED;
4343 }
4344 int n;
4345 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004346 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004347 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004348 return NO_ERROR;
4349 case 1002: // SHOW_UPDATES
4350 n = data.readInt32();
4351 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004352 invalidateHwcGeometry();
4353 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004354 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004355 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004356 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004357 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004358 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004359 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004360 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004361 setTransactionFlags(
4362 eTransactionNeeded|
4363 eDisplayTransactionNeeded|
4364 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004365 return NO_ERROR;
4366 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004367 case 1006:{ // send empty update
4368 signalRefresh();
4369 return NO_ERROR;
4370 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004371 case 1008: // toggle use of hw composer
4372 n = data.readInt32();
4373 mDebugDisableHWC = n ? 1 : 0;
4374 invalidateHwcGeometry();
4375 repaintEverything();
4376 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004377 case 1009: // toggle use of transform hint
4378 n = data.readInt32();
4379 mDebugDisableTransformHint = n ? 1 : 0;
4380 invalidateHwcGeometry();
4381 repaintEverything();
4382 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004383 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004384 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004385 reply->writeInt32(0);
4386 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004387 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004388 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004389 return NO_ERROR;
4390 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004391 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004392 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004393 return NO_ERROR;
4394 }
4395 case 1014: {
4396 // daltonize
4397 n = data.readInt32();
4398 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004399 case 1:
4400 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4401 break;
4402 case 2:
4403 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4404 break;
4405 case 3:
4406 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4407 break;
4408 default:
4409 mDaltonizer.setType(ColorBlindnessType::None);
4410 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004411 }
4412 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004413 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004414 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004415 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004416 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004417 invalidateHwcGeometry();
4418 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004419 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004420 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004421 case 1015: {
4422 // apply a color matrix
4423 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004424 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004425 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004426 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004427 for (size_t j = 0; j < 4; j++) {
4428 mColorMatrix[i][j] = data.readFloat();
4429 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004430 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004431 } else {
4432 mColorMatrix = mat4();
4433 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004434
4435 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4436 // the division by w in the fragment shader
4437 float4 lastRow(transpose(mColorMatrix)[3]);
4438 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4439 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4440 }
4441
Alan Viverette9c5a3332013-09-12 20:04:35 -07004442 invalidateHwcGeometry();
4443 repaintEverything();
4444 return NO_ERROR;
4445 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004446 // This is an experimental interface
4447 // Needs to be shifted to proper binder interface when we productize
4448 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004449 n = data.readInt32();
4450 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004451 return NO_ERROR;
4452 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004453 case 1017: {
4454 n = data.readInt32();
4455 mForceFullDamage = static_cast<bool>(n);
4456 return NO_ERROR;
4457 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004458 case 1018: { // Modify Choreographer's phase offset
4459 n = data.readInt32();
4460 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4461 return NO_ERROR;
4462 }
4463 case 1019: { // Modify SurfaceFlinger's phase offset
4464 n = data.readInt32();
4465 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4466 return NO_ERROR;
4467 }
Irvel468051e2016-06-13 16:44:44 -07004468 case 1020: { // Layer updates interceptor
4469 n = data.readInt32();
4470 if (n) {
4471 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004472 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004473 }
4474 else{
4475 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004476 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004477 }
4478 return NO_ERROR;
4479 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004480 case 1021: { // Disable HWC virtual displays
4481 n = data.readInt32();
4482 mUseHwcVirtualDisplays = !n;
4483 return NO_ERROR;
4484 }
Romain Guy0147a172017-06-01 13:53:56 -07004485 case 1022: { // Set saturation boost
4486 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4487
4488 invalidateHwcGeometry();
4489 repaintEverything();
4490 return NO_ERROR;
4491 }
Romain Guy54f154a2017-10-24 21:40:32 +01004492 case 1023: { // Set native mode
4493 mForceNativeColorMode = data.readInt32() == 1;
4494
4495 invalidateHwcGeometry();
4496 repaintEverything();
4497 return NO_ERROR;
4498 }
4499 case 1024: { // Is wide color gamut rendering/color management supported?
4500 reply->writeBool(hasWideColorDisplay);
4501 return NO_ERROR;
4502 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004503 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004504 n = data.readInt32();
4505 if (n) {
4506 ALOGV("LayerTracing enabled");
4507 mTracing.enable();
4508 doTracing("tracing.enable");
4509 reply->writeInt32(NO_ERROR);
4510 } else {
4511 ALOGV("LayerTracing disabled");
4512 status_t err = mTracing.disable();
4513 reply->writeInt32(err);
4514 }
4515 return NO_ERROR;
4516 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004517 case 1026: { // Get layer tracing status
4518 reply->writeBool(mTracing.isEnabled());
4519 return NO_ERROR;
4520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004521 }
4522 }
4523 return err;
4524}
4525
Steven Thomas6d8110b2017-08-31 18:24:21 -07004526void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004527 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004528 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004529}
4530
Steven Thomas6d8110b2017-08-31 18:24:21 -07004531void SurfaceFlinger::repaintEverything() {
4532 ConditionalLock _l(mStateLock,
4533 std::this_thread::get_id() != mMainThreadId);
4534 repaintEverythingLocked();
4535}
4536
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004537// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4538class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004539public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004540 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4541 ~WindowDisconnector() {
4542 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004543 }
4544
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004545private:
4546 ANativeWindow* mWindow;
4547 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004548};
4549
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004550status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4551 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4552 int32_t minLayerZ, int32_t maxLayerZ,
4553 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004554 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004555 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004556
chaviwa76b2712017-09-20 12:02:26 -07004557 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4558
4559 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004560 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4561
chaviwa76b2712017-09-20 12:02:26 -07004562 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4563
4564 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4565 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004566 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004567}
4568
4569status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004570 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004571 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004572 ATRACE_CALL();
4573
4574 class LayerRenderArea : public RenderArea {
4575 public:
Robert Carr578038f2018-03-09 12:25:24 -08004576 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4577 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4578 : RenderArea(reqHeight, reqWidth),
4579 mLayer(layer),
4580 mCrop(crop),
4581 mFlinger(flinger),
4582 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004583 Rect getBounds() const override {
4584 const Layer::State& layerState(mLayer->getDrawingState());
4585 return Rect(layerState.active.w, layerState.active.h);
4586 }
4587 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4588 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4589 bool isSecure() const override { return false; }
4590 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004591 const Transform& getTransform() const { return mTransform; }
4592
4593 class ReparentForDrawing {
4594 public:
4595 const sp<Layer>& oldParent;
4596 const sp<Layer>& newParent;
4597
4598 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4599 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004600 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004601 }
Robert Carr15eae092018-03-23 13:43:53 -07004602 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004603 };
4604
4605 void render(std::function<void()> drawLayers) override {
4606 if (!mChildrenOnly) {
4607 mTransform = mLayer->getTransform().inverse();
4608 drawLayers();
4609 } else {
4610 Rect bounds = getBounds();
4611 screenshotParentLayer =
4612 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4613 bounds.getWidth(), bounds.getHeight(), 0);
4614
4615 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4616 drawLayers();
4617 }
4618 }
chaviwa76b2712017-09-20 12:02:26 -07004619
chaviw7206d492017-11-10 16:16:12 -08004620 Rect getSourceCrop() const override {
4621 if (mCrop.isEmpty()) {
4622 return getBounds();
4623 } else {
4624 return mCrop;
4625 }
4626 }
chaviwa76b2712017-09-20 12:02:26 -07004627 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004628 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004629
4630 private:
chaviw7206d492017-11-10 16:16:12 -08004631 const sp<Layer> mLayer;
4632 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004633
4634 // In the "childrenOnly" case we reparent the children to a screenshot
4635 // layer which has no properties set and which does not draw.
4636 sp<ContainerLayer> screenshotParentLayer;
4637 Transform mTransform;
4638
4639 SurfaceFlinger* mFlinger;
4640 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004641 };
4642
4643 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4644 auto parent = layerHandle->owner.promote();
4645
chaviw7206d492017-11-10 16:16:12 -08004646 if (parent == nullptr || parent->isPendingRemoval()) {
4647 ALOGE("captureLayers called with a removed parent");
4648 return NAME_NOT_FOUND;
4649 }
4650
Robert Carr578038f2018-03-09 12:25:24 -08004651 const int uid = IPCThreadState::self()->getCallingUid();
4652 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4653 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4654 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4655 return PERMISSION_DENIED;
4656 }
4657
chaviw7206d492017-11-10 16:16:12 -08004658 Rect crop(sourceCrop);
4659 if (sourceCrop.width() <= 0) {
4660 crop.left = 0;
4661 crop.right = parent->getCurrentState().active.w;
4662 }
4663
4664 if (sourceCrop.height() <= 0) {
4665 crop.top = 0;
4666 crop.bottom = parent->getCurrentState().active.h;
4667 }
4668
4669 int32_t reqWidth = crop.width() * frameScale;
4670 int32_t reqHeight = crop.height() * frameScale;
4671
Robert Carr578038f2018-03-09 12:25:24 -08004672 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004673
Robert Carr578038f2018-03-09 12:25:24 -08004674 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004675 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4676 if (!layer->isVisible()) {
4677 return;
Robert Carr578038f2018-03-09 12:25:24 -08004678 } else if (childrenOnly && layer == parent.get()) {
4679 return;
chaviwa76b2712017-09-20 12:02:26 -07004680 }
4681 visitor(layer);
4682 });
4683 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004684 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004685}
4686
4687status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4688 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004689 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004690 bool useIdentityTransform) {
4691 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004692
chaviwa76b2712017-09-20 12:02:26 -07004693 renderArea.updateDimensions();
4694
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004695 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4696 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4697 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4698 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004699
4700 // This mutex protects syncFd and captureResult for communication of the return values from the
4701 // main thread back to this Binder thread
4702 std::mutex captureMutex;
4703 std::condition_variable captureCondition;
4704 std::unique_lock<std::mutex> captureLock(captureMutex);
4705 int syncFd = -1;
4706 std::optional<status_t> captureResult;
4707
Robert Carr03480e22018-01-04 16:02:06 -08004708 const int uid = IPCThreadState::self()->getCallingUid();
4709 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4710
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004711 sp<LambdaMessage> message = new LambdaMessage([&]() {
4712 // If there is a refresh pending, bug out early and tell the binder thread to try again
4713 // after the refresh.
4714 if (mRefreshPending) {
4715 ATRACE_NAME("Skipping screenshot for now");
4716 std::unique_lock<std::mutex> captureLock(captureMutex);
4717 captureResult = std::make_optional<status_t>(EAGAIN);
4718 captureCondition.notify_one();
4719 return;
4720 }
4721
4722 status_t result = NO_ERROR;
4723 int fd = -1;
4724 {
4725 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004726 renderArea.render([&]() {
4727 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4728 useIdentityTransform, forSystem, &fd);
4729 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004730 }
4731
4732 {
4733 std::unique_lock<std::mutex> captureLock(captureMutex);
4734 syncFd = fd;
4735 captureResult = std::make_optional<status_t>(result);
4736 captureCondition.notify_one();
4737 }
4738 });
4739
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004740 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004741 if (result == NO_ERROR) {
4742 captureCondition.wait(captureLock, [&]() { return captureResult; });
4743 while (*captureResult == EAGAIN) {
4744 captureResult.reset();
4745 result = postMessageAsync(message);
4746 if (result != NO_ERROR) {
4747 return result;
4748 }
4749 captureCondition.wait(captureLock, [&]() { return captureResult; });
4750 }
4751 result = *captureResult;
4752 }
4753
4754 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004755 sync_wait(syncFd, -1);
4756 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004757 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004758
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004759 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004760}
4761
chaviwa76b2712017-09-20 12:02:26 -07004762void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4763 TraverseLayersFunction traverseLayers, bool yswap,
4764 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004765 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004766
Lloyd Pique144e1162017-12-20 16:44:52 -08004767 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004768
4769 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004770 const auto raWidth = renderArea.getWidth();
4771 const auto raHeight = renderArea.getHeight();
4772
4773 const auto reqWidth = renderArea.getReqWidth();
4774 const auto reqHeight = renderArea.getReqHeight();
4775 Rect sourceCrop = renderArea.getSourceCrop();
4776
4777 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4778 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004779
Dan Stozac1879002014-05-22 15:59:05 -07004780 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004781 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004782 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004783 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004784 }
4785
4786 // ensure that sourceCrop is inside screen
4787 if (sourceCrop.left < 0) {
4788 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4789 }
chaviwa76b2712017-09-20 12:02:26 -07004790 if (sourceCrop.right > raWidth) {
4791 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004792 }
4793 if (sourceCrop.top < 0) {
4794 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4795 }
chaviwa76b2712017-09-20 12:02:26 -07004796 if (sourceCrop.bottom > raHeight) {
4797 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004798 }
4799
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004800 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004801 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004802 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004803 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4804 }
4805 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004806
Mathias Agopian180f10d2013-04-10 22:55:41 -07004807 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004808 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004809
4810 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004811 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4812 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004813 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004814
4815 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004816 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004817
chaviwa76b2712017-09-20 12:02:26 -07004818 traverseLayers([&](Layer* layer) {
4819 if (filtering) layer->setFiltering(true);
4820 layer->draw(renderArea, useIdentityTransform);
4821 if (filtering) layer->setFiltering(false);
4822 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004823}
4824
chaviwa76b2712017-09-20 12:02:26 -07004825status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4826 TraverseLayersFunction traverseLayers,
4827 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004828 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004829 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004830 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004831 ATRACE_CALL();
4832
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004833 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004834
4835 traverseLayers([&](Layer* layer) {
4836 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4837 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004838
Robert Carr03480e22018-01-04 16:02:06 -08004839 // We allow the system server to take screenshots of secure layers for
4840 // use in situations like the Screen-rotation animation and place
4841 // the impetus on WindowManager to not persist them.
4842 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004843 ALOGW("FB is protected: PERMISSION_DENIED");
4844 return PERMISSION_DENIED;
4845 }
4846
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004847 // this binds the given EGLImage as a framebuffer for the
4848 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004849 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004850 if (bufferBond.getStatus() != NO_ERROR) {
4851 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004852 return INVALID_OPERATION;
4853 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004854
Dan Stozaabcda352017-06-01 14:37:39 -07004855 // this will in fact render into our dequeued buffer
4856 // via an FBO, which means we didn't have to create
4857 // an EGLSurface and therefore we're not
4858 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004859 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004860
Dan Stozaabcda352017-06-01 14:37:39 -07004861 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004862 getRenderEngine().finish();
4863 *outSyncFd = -1;
4864
chaviwa76b2712017-09-20 12:02:26 -07004865 const auto reqWidth = renderArea.getReqWidth();
4866 const auto reqHeight = renderArea.getReqHeight();
4867
Dan Stozaabcda352017-06-01 14:37:39 -07004868 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4869 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004870 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004871 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004872 } else {
4873 base::unique_fd syncFd = getRenderEngine().flush();
4874 if (syncFd < 0) {
4875 getRenderEngine().finish();
4876 }
4877 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004878 }
4879
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004880 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004881}
4882
Mathias Agopiand5556842013-09-19 17:08:37 -07004883void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004884 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004885 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004886 for (size_t y = 0; y < h; y++) {
4887 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4888 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004889 if (p[x] != 0xFF000000) return;
4890 }
4891 }
chaviwa76b2712017-09-20 12:02:26 -07004892 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004893
Robert Carr2047fae2016-11-28 14:09:09 -08004894 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004895 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004896 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004897 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4898 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4899 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4900 static_cast<float>(state.color.a));
4901 i++;
4902 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004903 }
4904}
4905
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004906// ---------------------------------------------------------------------------
4907
Dan Stoza412903f2017-04-27 13:42:17 -07004908void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4909 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004910}
4911
Dan Stoza412903f2017-04-27 13:42:17 -07004912void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4913 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004914}
4915
chaviwa76b2712017-09-20 12:02:26 -07004916void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4917 int32_t maxLayerZ,
4918 const LayerVector::Visitor& visitor) {
4919 // We loop through the first level of layers without traversing,
4920 // as we need to interpret min/max layer Z in the top level Z space.
4921 for (const auto& layer : mDrawingState.layersSortedByZ) {
4922 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4923 continue;
4924 }
4925 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004926 // relative layers are traversed in Layer::traverseInZOrder
4927 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004928 continue;
4929 }
4930 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004931 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4932 return;
4933 }
chaviwa76b2712017-09-20 12:02:26 -07004934 if (!layer->isVisible()) {
4935 return;
4936 }
4937 visitor(layer);
4938 });
4939 }
4940}
4941
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004942}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004943
4944
4945#if defined(__gl_h_)
4946#error "don't include gl/gl.h in this file"
4947#endif
4948
4949#if defined(__gl2_h_)
4950#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004951#endif