blob: 43899e06353cde383a3a0df6ad6b379459c3f144 [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
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.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"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700128 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700144ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
145 switch (rotation) {
146 case ISurfaceComposer::eRotateNone:
147 return ui::Transform::ROT_0;
148 case ISurfaceComposer::eRotate90:
149 return ui::Transform::ROT_90;
150 case ISurfaceComposer::eRotate180:
151 return ui::Transform::ROT_180;
152 case ISurfaceComposer::eRotate270:
153 return ui::Transform::ROT_270;
154 }
155 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
156 return ui::Transform::ROT_0;
157}
158
Peiyong Linfca547f2018-07-09 13:03:33 -0700159#pragma clang diagnostic pop
160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161class ConditionalLock {
162public:
163 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
164 if (lock) {
165 mMutex.lock();
166 }
167 }
168 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
169private:
170 Mutex& mMutex;
171 bool mLocked;
172};
Peiyong Linfca547f2018-07-09 13:03:33 -0700173
Peiyong Lin9d846a52018-11-05 13:18:20 -0800174// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
175bool validateCompositionDataspace(Dataspace dataspace) {
176 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
177}
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179} // namespace anonymous
180
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181// ---------------------------------------------------------------------------
182
Mathias Agopian99b49842011-06-27 16:05:52 -0700183const String16 sHardwareTest("android.permission.HARDWARE_TEST");
184const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
185const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
186const String16 sDump("android.permission.DUMP");
187
188// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800189int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
190int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700191int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700192bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800193uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800194bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800195bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800196int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600197bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700198int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700199bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700200bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700201Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
202ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
203Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
204ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700205
Kalle Raitaa099a242017-01-11 11:17:29 -0800206std::string getHwcServiceName() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.hwc_service_name", value, "default");
209 ALOGI("Using HWComposer service: '%s'", value);
210 return std::string(value);
211}
212
213bool useTrebleTestingOverride() {
214 char value[PROPERTY_VALUE_MAX] = {};
215 property_get("debug.sf.treble_testing_override", value, "false");
216 ALOGI("Treble testing override: '%s'", value);
217 return std::string(value) == "true";
218}
219
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
221 switch(displayColorSetting) {
222 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Enhanced");
228 default:
229 return std::string("Unknown ") +
230 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800232}
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Pique90c115d2018-09-18 21:39:42 -0700243SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
244 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700246 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800253 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800254 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800255 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700257 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700258 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700259 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700260 mDebugInTransaction(0),
261 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700262 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700263 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700264 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800265 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800266 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700268 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700269 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800270
Lloyd Pique90c115d2018-09-18 21:39:42 -0700271SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
272 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
275 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
276 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
277
278 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
280
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800281 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700284 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
286
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700287 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
289
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800290 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
292
Steven Thomas050b2c82017-03-06 11:45:16 -0800293 // Vr flinger is only enabled on Daydream ready devices.
294 useVrFlinger = getBool< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::useVrFlinger>(false);
296
Fabien Sanglard1971b632017-03-10 14:50:03 -0800297 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
299
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600300 hasWideColorDisplay =
301 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700302 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700303 getBool<V1_2::ISurfaceFlingerConfigs,
304 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
305
306 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
307 if (surfaceFlingerConfigsServiceV1_2) {
308 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700309 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
310 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
311 defaultCompositionDataspace = tmpDefaultDataspace;
312 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
313 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
314 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
315 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700316 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800317 mDefaultCompositionDataspace = defaultCompositionDataspace;
318 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600319
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320 useContextPriority = getBool<ISurfaceFlingerConfigs,
321 &ISurfaceFlingerConfigs::useContextPriority>(true);
322
Iris Chang7501ed62018-04-30 14:45:42 +0800323 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700324 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
325 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation::ORIENTATION_0);
327
328 switch (primaryDisplayOrientation) {
329 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800343
Lloyd Pique90c115d2018-09-18 21:39:42 -0700344 mPrimaryDispSync =
345 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
346 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 // debugging stuff...
349 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopianb4b17302013-03-20 18:36:41 -0700351 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700352 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 property_get("debug.sf.showupdates", value, "0");
355 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700357 property_get("debug.sf.ddms", value, "0");
358 mDebugDDMS = atoi(value);
359 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700360 if (!startDdmConnection()) {
361 // start failed, and DDMS debugging not enabled
362 mDebugDDMS = 0;
363 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700365 ALOGI_IF(mDebugRegion, "showupdates enabled");
366 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700367
368 property_get("debug.sf.disable_backpressure", value, "0");
369 mPropagateBackpressure = !atoi(value);
370 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700371
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800372 property_get("debug.sf.enable_hwc_vds", value, "0");
373 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800374 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 property_get("ro.sf.disable_triple_buffer", value, "1");
377 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700379
Yiwei Zhang243b3782018-05-15 17:40:04 -0700380 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700381 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
382 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
383
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200384 property_get("debug.sf.early_phase_offset_ns", value, "-1");
385 const int earlySfOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
388 const int earlyGlSfOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
391 const int earlyAppOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
394 const int earlyGlAppOffsetNs = atoi(value);
395
Ana Krulec98b5b242018-08-10 15:03:23 -0700396 property_get("debug.sf.use_scheduler", value, "0");
397 mUseScheduler = atoi(value);
398
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200399 const VSyncModulator::Offsets earlyOffsets =
400 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
401 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
402 const VSyncModulator::Offsets earlyGlOffsets =
403 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
405 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
406 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700407
Romain Guy11d63f42017-07-20 12:47:14 -0700408 // We should be reading 'persist.sys.sf.color_saturation' here
409 // but since /data may be encrypted, we need to wait until after vold
410 // comes online to attempt to read the property. The property is
411 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800412
413 if (useTrebleTestingOverride()) {
414 // Without the override SurfaceFlinger cannot connect to HIDL
415 // services that are not listed in the manifests. Considered
416 // deriving the setting from the set service name, but it
417 // would be brittle if the name that's not 'default' is used
418 // for production purposes later on.
419 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423void SurfaceFlinger::onFirstRef()
424{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800425 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428SurfaceFlinger::~SurfaceFlinger()
429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Dan Stozac7014012014-02-14 15:03:43 -0800432void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433{
434 // the window manager died on us. prepare its eulogy.
435
Andy McFadden13a082e2012-08-24 10:16:42 -0700436 // restore initial conditions (default device unblank, etc)
437 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438
439 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441}
442
Robert Carr1db73f62016-12-21 12:58:51 -0800443static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700444 status_t err = client->initCheck();
445 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return nullptr;
449}
450
451sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
452 return initClient(new Client(this));
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
456 const sp<IGraphicBufferProducer>& gbp) {
457 if (authenticateSurfaceTexture(gbp) == false) {
458 return nullptr;
459 }
460 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
461 if (layer == nullptr) {
462 return nullptr;
463 }
464
465 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800466}
467
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700468sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
469 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470{
471 class DisplayToken : public BBinder {
472 sp<SurfaceFlinger> flinger;
473 virtual ~DisplayToken() {
474 // no more references, this display must be terminated
475 Mutex::Autolock _l(flinger->mStateLock);
476 flinger->mCurrentState.displays.removeItem(this);
477 flinger->setTransactionFlags(eDisplayTransactionNeeded);
478 }
479 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700480 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 : flinger(flinger) {
482 }
483 };
484
485 sp<BBinder> token = new DisplayToken(this);
486
487 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 // Display ID is assigned when virtual display is allocated by HWC.
489 DisplayDeviceState state;
490 state.isSecure = secure;
491 state.displayName = displayName;
492 mCurrentState.displays.add(token, state);
493 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494 return token;
495}
496
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 Mutex::Autolock _l(mStateLock);
499
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
501 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700502 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 return;
504 }
505
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
507 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700508 ALOGE("destroyDisplay called for non-virtual display");
509 return;
510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 mInterceptor->saveDisplayDeletion(state.sequenceId);
512 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700513 setTransactionFlags(eDisplayTransactionNeeded);
514}
515
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 std::optional<DisplayId> displayId;
518
519 if (id == HWC_DISPLAY_PRIMARY) {
520 displayId = getInternalDisplayId();
521 } else if (id == HWC_DISPLAY_EXTERNAL) {
522 displayId = getExternalDisplayId();
523 }
524
525 if (!displayId) {
526 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800527 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700528 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700529
530 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700531}
532
Ady Abraham37965d42018-11-01 13:43:32 -0700533status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
534 if (!outGetColorManagement) {
535 return BAD_VALUE;
536 }
537 *outGetColorManagement = useColorManagement;
538 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700539}
540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541void SurfaceFlinger::bootFinished()
542{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700543 if (mStartPropertySetThread->join() != NO_ERROR) {
544 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 const nsecs_t now = systemTime();
547 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000548 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
550 // wait patiently for the window manager death
551 const String16 name("window");
552 sp<IBinder> window(defaultServiceManager()->getService(name));
553 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700554 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 }
556
Steven Thomas050b2c82017-03-06 11:45:16 -0800557 if (mVrFlinger) {
558 mVrFlinger->OnBootFinished();
559 }
560
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700562 // formerly we would just kill the process, but we now ask it to exit so it
563 // can choose where to stop the animation.
564 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700565
566 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
567 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
568 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700569
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 postMessageAsync(new LambdaMessage([this] {
571 readPersistentProperties();
572 mBootStage = BootStage::FINISHED;
573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700598 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -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
Ana Krulec98b5b242018-08-10 15:03:23 -0700612 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 mScheduler = getFactory().createScheduler([this](bool enabled) {
614 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
615 });
616
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700618 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 [this] { resyncWithRateLimit(); },
620 impl::EventThread::InterceptVSyncsCallback());
621 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700622 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700623 [this] { resyncWithRateLimit(); },
624 [this](nsecs_t timestamp) {
625 mInterceptor->saveVSyncEvent(timestamp);
626 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800627
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700629 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
630 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 } else {
632 mEventThreadSource =
633 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
634 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
635 mEventThread =
636 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
637 [this] { resyncWithRateLimit(); },
638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 [this](nsecs_t timestamp) {
648 mInterceptor->saveVSyncEvent(timestamp);
649 },
650 "sfEventThread");
651 mEventQueue->setEventThread(mSFEventThread.get());
652 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
Steven Thomasb02664d2017-07-26 18:48:28 -0700655 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700656 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700657 renderEngineFeature |= (useColorManagement ?
658 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700659 renderEngineFeature |= (useContextPriority ?
660 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700661
662 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
663 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700664 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
665 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800666 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700670 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700671 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Alec Mouri8d4f90a2018-11-14 22:33:24 +0000679 // make the default display GLContext current so that we can create textures
680 // when creating Layers (which may happens before we render something)
681 display->makeCurrent();
682
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 // This callback is called from the vr flinger dispatch thread. We
686 // need to call signalTransaction(), which requires holding
687 // mStateLock when we're not on the main thread. Acquiring
688 // mStateLock from the vr flinger dispatch thread might trigger a
689 // deadlock in surface flinger (see b/66916578), so post a message
690 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700692 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
693 mVrFlingerRequestsDisplay = requestDisplay;
694 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
698 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700699 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700700 .value_or(0),
701 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800702 if (!mVrFlinger) {
703 ALOGE("Failed to start vrflinger");
704 }
705 }
706
Lloyd Pique90c115d2018-09-18 21:39:42 -0700707 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700709
Mathias Agopian92a979a2012-08-02 18:32:23 -0700710 // initialize our drawing state
711 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700712
Andy McFadden13a082e2012-08-24 10:16:42 -0700713 // set initial conditions (e.g. unblank default device)
714 initializeDisplays();
715
David Sodmanbc815282017-11-05 18:57:52 -0800716 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700717
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700719
720 const bool presentFenceReliable =
721 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
722 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723
724 if (mStartPropertySetThread->Start() != NO_ERROR) {
725 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727
Chia-I Wud49d6692018-06-27 07:17:41 +0800728 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
729 // is used to saturate legacy sRGB content. However, to make sure the same color under
730 // Display P3 will be saturated to the same color, we intentionally break the API spec
731 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
732 // such saturation matrix on Display P3 is understood fully, the API should always return
733 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700734 mEnhancedSaturationMatrix =
735 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800736
737 // we will apply this on Display P3.
738 if (mEnhancedSaturationMatrix != mat4()) {
739 ColorSpace srgb(ColorSpace::sRGB());
740 ColorSpace displayP3(ColorSpace::DisplayP3());
741 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
742 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
743 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
744 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800745
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700747}
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 Mutex::Autolock _l(mStateLock);
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752 char value[PROPERTY_VALUE_MAX];
753
754 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700756 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800757 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100758
759 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700760 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700761}
762
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Start boot animation service by setting a property mailbox
765 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700768 if (mStartPropertySetThread->join() != NO_ERROR) {
769 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800770 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700771}
772
Mathias Agopian875d8e12013-06-07 15:35:48 -0700773size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800774 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700775}
776
Mathias Agopian875d8e12013-06-07 15:35:48 -0700777size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800778 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700779}
780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800781// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800782
Jamie Gennis582270d2011-08-17 18:19:00 -0700783bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800785 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800786 return authenticateSurfaceTextureLocked(bufferProducer);
787}
788
789bool SurfaceFlinger::authenticateSurfaceTextureLocked(
790 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800791 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800792 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800793}
794
Brian Anderson6b376712017-04-04 10:51:39 -0700795status_t SurfaceFlinger::getSupportedFrameTimestamps(
796 std::vector<FrameEvent>* outSupported) const {
797 *outSupported = {
798 FrameEvent::REQUESTED_PRESENT,
799 FrameEvent::ACQUIRE,
800 FrameEvent::LATCH,
801 FrameEvent::FIRST_REFRESH_START,
802 FrameEvent::LAST_REFRESH_START,
803 FrameEvent::GPU_COMPOSITION_DONE,
804 FrameEvent::DEQUEUE_READY,
805 FrameEvent::RELEASE,
806 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700807 ConditionalLock _l(mStateLock,
808 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700809 if (!getHwComposer().hasCapability(
810 HWC2::Capability::PresentFenceIsNotReliable)) {
811 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
812 }
813 return NO_ERROR;
814}
815
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700816status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
817 Vector<DisplayInfo>* configs) {
818 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 return BAD_VALUE;
820 }
821
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 const auto displayId = getPhysicalDisplayId(displayToken);
823 if (!displayId) {
824 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700825 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 // TODO: Not sure if display density should handled by SF any longer
828 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700831 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800832 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700833 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 }
835 return density;
836 }
837 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700840 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 return getDensityFromProperty("ro.sf.lcd_density"); }
842 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700848 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 DisplayInfo info = DisplayInfo();
850
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 float xdpi = hwConfig->getDpiX();
852 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700854 info.w = hwConfig->getWidth();
855 info.h = hwConfig->getHeight();
856 // Default display viewport to display width and height
857 info.viewportW = info.w;
858 info.viewportH = info.h;
859
Dominik Laskowski075d3172018-05-24 15:50:06 -0700860 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 // The density of the device is provided by a build property
862 float density = Density::getBuildDensity() / 160.0f;
863 if (density == 0) {
864 // the build doesn't provide a density -- this is wrong!
865 // use xdpi instead
866 ALOGE("ro.sf.lcd_density must be defined as a build property");
867 density = xdpi / 160.0f;
868 }
869 if (Density::getEmuDensity()) {
870 // if "qemu.sf.lcd_density" is specified, it overrides everything
871 xdpi = ydpi = density = Density::getEmuDensity();
872 density /= 160.0f;
873 }
874 info.density = density;
875
876 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877 const auto display = getDefaultDisplayDeviceLocked();
878 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700879
880 // This is for screenrecord
881 const Rect viewport = display->getViewport();
882 if (viewport.isValid()) {
883 info.viewportW = uint32_t(viewport.getWidth());
884 info.viewportH = uint32_t(viewport.getHeight());
885 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 } else {
887 // TODO: where should this value come from?
888 static const int TV_DENSITY = 213;
889 info.density = TV_DENSITY / 160.0f;
890 info.orientation = 0;
891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 info.xdpi = xdpi;
894 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900896 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897
Andy McFadden91b2ca82014-06-13 14:04:23 -0700898 // This is how far in advance a buffer must be queued for
899 // presentation at a given time. If you want a buffer to appear
900 // on the screen at time N, you must submit the buffer before
901 // (N - presentationDeadline).
902 //
903 // Normally it's one full refresh period (to give SF a chance to
904 // latch the buffer), but this can be reduced by configuring a
905 // DispSync offset. Any additional delays introduced by the hardware
906 // composer or panel must be accounted for here.
907 //
908 // We add an additional 1ms to allow for processing time and
909 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800911 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700912
913 // All non-virtual displays are currently considered secure.
914 info.secure = true;
915
Dominik Laskowski075d3172018-05-24 15:50:06 -0700916 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700917 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800918 std::swap(info.w, info.h);
919 }
920
Michael Wright28f24d02016-07-12 13:30:53 -0700921 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700922 }
923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 return NO_ERROR;
925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
928 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return BAD_VALUE;
930 }
931
Ana Krulece588e312018-09-18 12:32:24 -0700932 if (mUseScheduler) {
933 mScheduler->getDisplayStatInfo(stats);
934 } else {
935 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
936 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
937 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return NO_ERROR;
939}
940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
942 const auto display = getDisplayDevice(displayToken);
943 if (!display) {
944 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800945 return BAD_VALUE;
946 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700949}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700952 if (display->isVirtual()) {
953 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
954 return;
955 }
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 return;
960 }
961
Dominik Laskowski075d3172018-05-24 15:50:06 -0700962 const auto displayId = display->getId();
963 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700966 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967}
968
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700970 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 Vector<DisplayInfo> configs;
972 getDisplayConfigs(displayToken, &configs);
973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
975 configs.size());
976 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700977 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 const auto display = getDisplayDevice(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
981 displayToken.get());
982 } else if (display->isVirtual()) {
983 ALOGW("Attempt to set active config %d for virtual display", mode);
984 } else {
985 setActiveConfigInternal(display, mode);
986 }
987 }));
988
Mathias Agopian888c8222012-08-04 21:10:38 -0700989 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700990}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
993 Vector<ColorMode>* outColorModes) {
994 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700995 return BAD_VALUE;
996 }
997
Dominik Laskowski075d3172018-05-24 15:50:06 -0700998 const auto displayId = getPhysicalDisplayId(displayToken);
999 if (!displayId) {
1000 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001001 }
1002
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001004 {
1005 ConditionalLock _l(mStateLock,
1006 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001008 }
Michael Wright28f24d02016-07-12 13:30:53 -07001009 outColorModes->clear();
1010 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1011
1012 return NO_ERROR;
1013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1016 if (const auto display = getDisplayDevice(displayToken)) {
1017 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001018 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1023 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001024 if (display->isVirtual()) {
1025 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 ColorMode currentMode = display->getActiveColorMode();
1030 Dataspace currentDataSpace = display->getCompositionDataSpace();
1031 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001032
Peiyong Lin38e9a562018-04-10 16:24:20 -07001033 if (mode == currentMode && dataSpace == currentDataSpace &&
1034 renderIntent == currentRenderIntent) {
1035 return;
1036 }
1037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 display->setActiveColorMode(mode);
1039 display->setCompositionDataSpace(dataSpace);
1040 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001041
Dominik Laskowski075d3172018-05-24 15:50:06 -07001042 const auto displayId = display->getId();
1043 LOG_ALWAYS_FATAL_IF(!displayId);
1044 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1045
Dominik Laskowski34157762018-10-31 13:07:19 -07001046 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001048 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001052 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 Vector<ColorMode> modes;
1054 getDisplayColorModes(displayToken, &modes);
1055 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1056 if (mode < ColorMode::NATIVE || !exists) {
1057 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001060 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 const auto display = getDisplayDevice(displayToken);
1062 if (!display) {
1063 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1064 decodeColorMode(mode).c_str(), mode, displayToken.get());
1065 } else if (display->isVirtual()) {
1066 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1067 decodeColorMode(mode).c_str(), mode);
1068 } else {
1069 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1070 RenderIntent::COLORIMETRIC);
1071 }
1072 }));
1073
Michael Wright28f24d02016-07-12 13:30:53 -07001074 return NO_ERROR;
1075}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001076
Svetoslavd85084b2014-03-20 10:28:31 -07001077status_t SurfaceFlinger::clearAnimationFrameStats() {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.clearStats();
1080 return NO_ERROR;
1081}
1082
1083status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1084 Mutex::Autolock _l(mStateLock);
1085 mAnimFrameTracker.getStats(outStats);
1086 return NO_ERROR;
1087}
1088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001089status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1090 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001091 Mutex::Autolock _l(mStateLock);
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093 const auto display = getDisplayDeviceLocked(displayToken);
1094 if (!display) {
1095 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001096 return BAD_VALUE;
1097 }
1098
Peiyong Linfb069302018-04-25 14:34:31 -07001099 // At this point the DisplayDeivce should already be set up,
1100 // meaning the luminance information is already queried from
1101 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001103 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1104 capabilities.getDesiredMaxLuminance(),
1105 capabilities.getDesiredMaxAverageLuminance(),
1106 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001107
1108 return NO_ERROR;
1109}
1110
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001112 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001114
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (mInjectVSyncs == enable) {
1116 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118
Ana Krulec98b5b242018-08-10 15:03:23 -07001119 // TODO(akrulec): Part of the Injector should be refactored, so that it
1120 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 if (enable) {
1122 ALOGV("VSync Injections enabled");
1123 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001124 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001125 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001127 impl::EventThread::InterceptVSyncsCallback(),
1128 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001130 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 } else {
1132 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001133 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 }
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001137 }));
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 return NO_ERROR;
1140}
1141
1142status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 Mutex::Autolock _l(mStateLock);
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 if (!mInjectVSyncs) {
1146 ALOGE("VSync Injections not enabled");
1147 return BAD_VALUE;
1148 }
1149 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1150 ALOGV("Injecting VSync inside SurfaceFlinger");
1151 mVSyncInjector->onInjectSyncEvent(when);
1152 }
1153 return NO_ERROR;
1154}
1155
Lloyd Pique755e3192018-01-31 16:46:15 -08001156status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1157 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001158 // Try to acquire a lock for 1s, fail gracefully
1159 const status_t err = mStateLock.timedLock(s2ns(1));
1160 const bool locked = (err == NO_ERROR);
1161 if (!locked) {
1162 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1163 return TIMED_OUT;
1164 }
1165
1166 outLayers->clear();
1167 mCurrentState.traverseInZOrder([&](Layer* layer) {
1168 outLayers->push_back(layer->getLayerDebugInfo());
1169 });
1170
1171 mStateLock.unlock();
1172 return NO_ERROR;
1173}
1174
Peiyong Linc6780972018-10-28 15:24:08 -07001175status_t SurfaceFlinger::getCompositionPreference(
1176 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1177 Dataspace* outWideColorGamutDataspace,
1178 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001179 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001180 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001181 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001182 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001183 return NO_ERROR;
1184}
1185
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001186// ----------------------------------------------------------------------------
1187
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001188sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1189 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001190 if (mUseScheduler) {
1191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1193 } else {
1194 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001197 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1198 return mSFEventThread->createEventConnection();
1199 } else {
1200 return mEventThread->createEventConnection();
1201 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001202 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001203}
1204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206
1207void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209}
1210
1211void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213}
1214
1215void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001220 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001221 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001222}
1223
1224status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001225 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001230 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232 if (res == NO_ERROR) {
1233 msg->wait();
1234 }
1235 return res;
1236}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001238void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001239 do {
1240 waitForEvent();
1241 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242}
1243
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244void SurfaceFlinger::enableHardwareVsync() {
1245 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001246 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001247 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001250 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251}
1252
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 Mutex::Autolock _l(mHWVsyncLock);
1255
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (makeAvailable) {
1257 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001258 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1259 if (mUseScheduler) {
1260 mScheduler->makeHWSyncAvailable(true);
1261 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001262 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001263 // Hardware vsync is not currently available, so abort the resync
1264 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 return;
1266 }
1267
Dominik Laskowski075d3172018-05-24 15:50:06 -07001268 const auto displayId = getInternalDisplayId();
1269 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001270 return;
1271 }
1272
Dominik Laskowski075d3172018-05-24 15:50:06 -07001273 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275
Ana Krulece588e312018-09-18 12:32:24 -07001276 if (mUseScheduler) {
1277 mScheduler->setVsyncPeriod(period);
1278 } else {
1279 mPrimaryDispSync->reset();
1280 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281
Ana Krulece588e312018-09-18 12:32:24 -07001282 if (!mPrimaryHWVsyncEnabled) {
1283 mPrimaryDispSync->beginResync();
1284 mEventControlThread->setVsyncEnabled(true);
1285 mPrimaryHWVsyncEnabled = true;
1286 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 }
1288}
1289
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 Mutex::Autolock _l(mHWVsyncLock);
1292 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001294 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 mPrimaryHWVsyncEnabled = false;
1296 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (makeUnavailable) {
1298 mHWVsyncAvailable = false;
1299 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300}
1301
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302void SurfaceFlinger::resyncWithRateLimit() {
1303 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001304
1305 // No explicit locking is needed here since EventThread holds a lock while calling this method
1306 static nsecs_t sLastResyncAttempted = 0;
1307 const nsecs_t now = systemTime();
1308 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001310 }
Dan Stoza57164302017-05-08 14:03:54 -07001311 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312}
1313
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001314void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1315 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001316 ATRACE_NAME("SF onVsync");
1317
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 return;
1322 }
1323
Dominik Laskowski075d3172018-05-24 15:50:06 -07001324 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001325 return;
1326 }
1327
Dominik Laskowski075d3172018-05-24 15:50:06 -07001328 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001329 // For now, we don't do anything with external display vsyncs.
1330 return;
1331 }
1332
Ana Krulece588e312018-09-18 12:32:24 -07001333 if (mUseScheduler) {
1334 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001336 bool needsHwVsync = false;
1337 { // Scope for the lock
1338 Mutex::Autolock _l(mHWVsyncLock);
1339 if (mPrimaryHWVsyncEnabled) {
1340 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1341 }
1342 }
1343
1344 if (needsHwVsync) {
1345 enableHardwareVsync();
1346 } else {
1347 disableHardwareVsync(false);
1348 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001349 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001350}
1351
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001353 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1354 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001355}
1356
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001357void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001358 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001360 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 // Ignore events that do not have the right sequenceId.
1363 if (sequenceId != getBE().mComposerSequenceId) {
1364 return;
1365 }
1366
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Only lock if we're not on the main thread. This function is normally
1368 // called on a hwbinder thread, but for the primary display it's called on
1369 // the main thread with the state lock already held, so don't attempt to
1370 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001372
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001374
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001375 if (std::this_thread::get_id() == mMainThreadId) {
1376 // Process all pending hot plug events immediately if we are on the main thread.
1377 processDisplayHotplugEventsLocked();
1378 }
1379
Lloyd Piqueba04e622017-12-14 17:11:26 -08001380 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001384 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001388 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001389}
1390
Dominik Laskowski075d3172018-05-24 15:50:06 -07001391void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001394 if (const auto displayId = getInternalDisplayId()) {
1395 getHwComposer().setVsyncEnabled(*displayId,
1396 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1397 }
Mathias Agopian86303202012-07-24 22:46:10 -07001398}
1399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001401void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001402 if (mUseScheduler) {
1403 mScheduler->disableHardwareVsync(true);
1404 } else {
1405 disableHardwareVsync(true);
1406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 // Clear the drawing state so that the logic inside of
1408 // handleTransactionLocked will fire. It will determine the delta between
1409 // mCurrentState and mDrawingState and re-apply all changes when we make the
1410 // transition.
1411 mDrawingState.displays.clear();
Alec Mouri8d4f90a2018-11-14 22:33:24 +00001412 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413 mDisplays.clear();
1414}
1415
Steven Thomas050b2c82017-03-06 11:45:16 -08001416void SurfaceFlinger::updateVrFlinger() {
1417 if (!mVrFlinger)
1418 return;
1419 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001421 return;
1422 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
David Sodman105b7dc2017-11-04 20:28:14 -07001424 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 ALOGE("Vr flinger is only supported for remote hardware composer"
1426 " service connections. Ignoring request to transition to vr"
1427 " flinger.");
1428 mVrFlingerRequestsDisplay = false;
1429 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001430 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomas0123ac62018-07-12 11:32:34 -07001434 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001435 LOG_ALWAYS_FATAL_IF(!display);
1436 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001437 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1438 // called below. Clear the reference now so we don't accidentally use it
1439 // later.
1440 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001447 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001448 getBE().mHwc = getFactory().createHWComposer(
1449 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001450 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451
David Sodman105b7dc2017-11-04 20:28:14 -07001452 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1453 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001454
1455 if (vrFlingerRequestsDisplay) {
1456 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
1459 mVisibleRegionsDirty = true;
1460 invalidateHwcGeometry();
1461
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001463 display = getDefaultDisplayDeviceLocked();
1464 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001465 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001468 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 const nsecs_t period = activeConfig->getVsyncPeriod();
1470 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001471
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001472 // The present fences returned from vr_hwc are not an accurate
1473 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001474 if (mUseScheduler) {
1475 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1476 } else {
1477 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1478 !hasSyncFramework);
1479 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001480
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 // Use phase of 0 since phase is not known.
1482 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001483 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1484 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001485
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001486 resyncToHardwareVsync(false);
1487
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001488 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001489 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001490}
1491
Mathias Agopian4fec8732012-06-29 14:12:52 -07001492void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001493 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001494 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001496 bool frameMissed = !mHadClientComposition &&
1497 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001498 (mPreviousPresentFence->getSignalTime() ==
1499 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001500 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001501 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001502 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001503 mTimeStats.incrementMissedFrames();
1504 if (mPropagateBackpressure) {
1505 signalLayerUpdate();
1506 break;
1507 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001508 }
Dan Stoza50182882016-07-08 12:02:20 -07001509
Steven Thomas050b2c82017-03-06 11:45:16 -08001510 // Now that we're going to make it to the handleMessageTransaction()
1511 // call below it's safe to call updateVrFlinger(), which will
1512 // potentially trigger a display handoff.
1513 updateVrFlinger();
1514
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 bool refreshNeeded = handleMessageTransaction();
1516 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001517 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001518 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001519 // Signal a refresh if a transaction modified the window state,
1520 // a new buffer was latched, or if HWC has requested a full
1521 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522 signalRefresh();
1523 }
1524 break;
1525 }
1526 case MessageQueue::REFRESH: {
1527 handleMessageRefresh();
1528 break;
1529 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001530 }
1531}
1532
Dan Stoza6b9454d2014-11-07 16:00:59 -08001533bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001534 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001536 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001537 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001538 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001539 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001540}
1541
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001544
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001545 mRefreshPending = false;
1546
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001547 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001548 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001549 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001550 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001551 for (const auto& [token, display] : mDisplays) {
1552 beginFrame(display);
1553 prepareFrame(display);
1554 doDebugFlashRegions(display, repaintEverything);
1555 doComposition(display, repaintEverything);
1556 }
1557
Adrian Roos1e1a1282017-11-01 19:05:31 +01001558 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001559 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001560
1561 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001562 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001563
Dan Stozabfbffeb2016-07-21 14:49:33 -07001564 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001565 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001566 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001567 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001568 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001569
Alec Mouri86770e52018-09-24 22:40:58 +00001570 // Setup RenderEngine sync fences if native sync is supported.
1571 if (getBE().mRenderEngine->useNativeFenceSync()) {
1572 if (mHadClientComposition) {
1573 base::unique_fd flushFence(getRenderEngine().flush());
1574 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1575 getBE().flushFence = new Fence(std::move(flushFence));
1576 } else {
1577 // Cleanup for hygiene.
1578 getBE().flushFence = Fence::NO_FENCE;
1579 }
1580 }
1581
Jorim Jaggi90535212018-05-23 23:44:06 +02001582 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001583
David Sodman7e4ae112018-02-09 15:02:28 -08001584 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001585 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001586 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001587 compositionInfo.hwc.hwcLayer = nullptr;
1588 }
David Sodmanba340492018-08-05 21:51:33 -07001589 }
David Sodman7e4ae112018-02-09 15:02:28 -08001590
1591 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001593
David Sodmanfa9b2af2017-12-24 13:28:59 -08001594
1595bool SurfaceFlinger::handleMessageInvalidate() {
1596 ATRACE_CALL();
1597 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001598}
1599
David Sodman79bba0e2018-08-05 18:07:49 -07001600void SurfaceFlinger::calculateWorkingSet() {
1601 ATRACE_CALL();
1602 ALOGV(__FUNCTION__);
1603
David Sodman79bba0e2018-08-05 18:07:49 -07001604 // build the h/w work list
1605 if (CC_UNLIKELY(mGeometryInvalid)) {
1606 mGeometryInvalid = false;
1607 for (const auto& [token, display] : mDisplays) {
1608 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001609 if (!displayId) {
1610 continue;
1611 }
David Sodman79bba0e2018-08-05 18:07:49 -07001612
Dominik Laskowski075d3172018-05-24 15:50:06 -07001613 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1614 for (size_t i = 0; i < currentLayers.size(); i++) {
1615 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001616
Dominik Laskowski075d3172018-05-24 15:50:06 -07001617 if (!layer->hasHwcLayer(*displayId)) {
1618 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1619 layer->forceClientComposition(*displayId);
1620 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001621 }
1622 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001623
1624 layer->setGeometry(display, i);
1625 if (mDebugDisableHWC || mDebugRegion) {
1626 layer->forceClientComposition(*displayId);
1627 }
David Sodman79bba0e2018-08-05 18:07:49 -07001628 }
1629 }
1630 }
1631
1632 // Set the per-frame data
1633 for (const auto& [token, display] : mDisplays) {
1634 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001635 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001636 continue;
1637 }
1638
1639 if (mDrawingState.colorMatrixChanged) {
1640 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001641 status_t result =
1642 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001643 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1644 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001645 }
1646 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1647 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001648 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001649 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1650 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1651 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001652 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001653 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1654 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1655 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001656 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001657 }
1658
Peiyong Lind3788632018-09-18 16:01:31 -07001659 // TODO(b/111562338) remove when composer 2.3 is shipped.
1660 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001661 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001662 }
1663
Dominik Laskowski075d3172018-05-24 15:50:06 -07001664 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001665 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001666 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001667 continue;
1668 }
1669
Dominik Laskowski075d3172018-05-24 15:50:06 -07001670 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1671 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001672 }
1673
Peiyong Lin13effd12018-07-24 17:01:47 -07001674 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001675 ColorMode colorMode;
1676 Dataspace dataSpace;
1677 RenderIntent renderIntent;
1678 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1679 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1680 }
1681 }
1682
1683 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001684
1685 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001686 getBE().mCompositionInfo[token].clear();
1687
David Sodmanba340492018-08-05 21:51:33 -07001688 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001689 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001690 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001691
1692 if (displayId) {
1693 if (!layer->setHwcLayer(*displayId)) {
1694 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1695 }
1696 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001697 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001698
Dominik Laskowski05275f12018-11-01 15:03:24 -07001699 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001700 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1701 }
1702 }
David Sodman79bba0e2018-08-05 18:07:49 -07001703}
1704
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001706{
1707 // is debugging enabled
1708 if (CC_LIKELY(!mDebugRegion))
1709 return;
1710
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711 if (display->isPoweredOn()) {
1712 // transform the dirty region into this screen's coordinate space
1713 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1714 if (!dirtyRegion.isEmpty()) {
1715 // redraw the whole screen
1716 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717
David Sodmanfa9b2af2017-12-24 13:28:59 -08001718 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001719 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001720 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001721
Alec Mouri8d4f90a2018-11-14 22:33:24 +00001722 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001723 }
1724 }
1725
David Sodmanfa9b2af2017-12-24 13:28:59 -08001726 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727
1728 if (mDebugRegion > 1) {
1729 usleep(mDebugRegion * 1000);
1730 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001731
Dominik Laskowski05275f12018-11-01 15:03:24 -07001732 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001733}
1734
Adrian Roos1e1a1282017-11-01 19:05:31 +01001735void SurfaceFlinger::doTracing(const char* where) {
1736 ATRACE_CALL();
1737 ATRACE_NAME(where);
1738 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001739 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001740 }
1741}
1742
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001743void SurfaceFlinger::logLayerStats() {
1744 ATRACE_CALL();
1745 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001746 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001747 if (display->isPrimary()) {
1748 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001749 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001750 }
1751 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001752
1753 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001754 }
1755}
1756
David Sodman2b406362017-12-15 13:33:47 -08001757void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 ATRACE_CALL();
1760 ALOGV("preComposition");
1761
David Sodman2b406362017-12-15 13:33:47 -08001762 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1763
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001765 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001766 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767 needExtraInvalidate = true;
1768 }
Robert Carr2047fae2016-11-28 14:09:09 -08001769 });
1770
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771 if (needExtraInvalidate) {
1772 signalLayerUpdate();
1773 }
1774}
1775
Ana Krulece588e312018-09-18 12:32:24 -07001776void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1777 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001778 // Update queue of past composite+present times and determine the
1779 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001780 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001782 while (!getBE().mCompositePresentTimes.empty()) {
1783 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784 // Cached values should have been updated before calling this method,
1785 // which helps avoid duplicate syscalls.
1786 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1787 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1788 break;
1789 }
1790 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001791 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 }
1793
1794 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001795 while (getBE().mCompositePresentTimes.size() > 16) {
1796 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 }
1798
Ana Krulece588e312018-09-18 12:32:24 -07001799 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001800}
1801
Ana Krulece588e312018-09-18 12:32:24 -07001802void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1803 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001804 // Integer division and modulo round toward 0 not -inf, so we need to
1805 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001806 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1807 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1808 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809
Brian Andersond0010582017-03-07 13:20:31 -08001810 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1811 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001812 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001813 }
1814
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815 // Snap the latency to a value that removes scheduling jitter from the
1816 // composition and present times, which often have >1ms of jitter.
1817 // Reducing jitter is important if an app attempts to extrapolate
1818 // something (such as user input) to an accurate diasplay time.
1819 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1820 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001821 nsecs_t bias = stats.vsyncPeriod / 2;
1822 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1823 nsecs_t snappedCompositeToPresentLatency =
1824 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825
David Sodman99974d22017-11-28 12:04:33 -08001826 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001827 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1828 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001829 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830}
1831
David Sodman2b406362017-12-15 13:33:47 -08001832void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 ATRACE_CALL();
1835 ALOGV("postComposition");
1836
Brian Anderson3546a3f2016-07-14 11:51:14 -07001837 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001838 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001839 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001840 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001841 }
1842
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001843 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001844 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001845
David Sodman73beded2017-11-15 11:56:06 -08001846 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001847 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001848 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001849 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001850 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001851 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001852 } else {
1853 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1854 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001855
David Sodman73beded2017-11-15 11:56:06 -08001856 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001857 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001858 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001859 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001860 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001861
Ana Krulece588e312018-09-18 12:32:24 -07001862 DisplayStatInfo stats;
1863 if (mUseScheduler) {
1864 mScheduler->getDisplayStatInfo(&stats);
1865 } else {
1866 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1867 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1868 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001869
David Sodman2b406362017-12-15 13:33:47 -08001870 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871 // when we started doing work for this frame, but that should be okay
1872 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001873 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001874 CompositorTiming compositorTiming;
1875 {
David Sodman99974d22017-11-28 12:04:33 -08001876 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1877 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001878 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001879
Robert Carr2047fae2016-11-28 14:09:09 -08001880 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001881 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1882 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001883 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001884 recordBufferingStats(layer->getName().string(),
1885 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001886 }
Robert Carr2047fae2016-11-28 14:09:09 -08001887 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001888
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001889 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001890 if (mUseScheduler) {
1891 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001892 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001893 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1894 enableHardwareVsync();
1895 } else {
1896 disableHardwareVsync(false);
1897 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001898 }
1899 }
1900
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001901 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001902 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001903 if (mUseScheduler) {
1904 mScheduler->enableHardwareVsync();
1905 } else {
1906 enableHardwareVsync();
1907 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001908 }
1909 }
1910
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001911 if (mAnimCompositionPending) {
1912 mAnimCompositionPending = false;
1913
Brian Anderson4e606e32017-03-16 15:34:57 -07001914 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001915 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001916 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001917 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001918 // The HWC doesn't support present fences, so use the refresh
1919 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001920 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001921 mAnimFrameTracker.setActualPresentTime(presentTime);
1922 }
1923 mAnimFrameTracker.advanceFrame();
1924 }
Dan Stozab90cf072015-03-05 11:05:59 -08001925
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001926 mTimeStats.incrementTotalFrames();
1927 if (mHadClientComposition) {
1928 mTimeStats.incrementClientCompositionFrames();
1929 }
1930
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001931 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1932
Dominik Laskowski075d3172018-05-24 15:50:06 -07001933 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001934 return;
1935 }
1936
1937 nsecs_t currentTime = systemTime();
1938 if (mHasPoweredOff) {
1939 mHasPoweredOff = false;
1940 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001941 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001942 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001943 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1944 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001945 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001946 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001947 }
David Sodman4a36e932017-11-07 14:29:47 -08001948 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001949 }
David Sodman4a36e932017-11-07 14:29:47 -08001950 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001951
1952 {
1953 std::lock_guard lock(mTexturePoolMutex);
1954 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1955 if (refillCount > 0) {
1956 const size_t offset = mTexturePool.size();
1957 mTexturePool.resize(mTexturePoolSize);
1958 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1959 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1960 }
1961 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001962
Marissa Wallfda30bb2018-10-12 11:34:28 -07001963 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07001964 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965}
1966
1967void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 ATRACE_CALL();
1969 ALOGV("rebuildLayerStacks");
1970
Mathias Agopiancd60f992012-08-16 16:28:27 -07001971 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001972 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001973 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001974 mVisibleRegionsDirty = false;
1975 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001976
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001977 for (const auto& pair : mDisplays) {
1978 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001979 Region opaqueRegion;
1980 Region dirtyRegion;
1981 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001982 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001983 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001984 const Rect bounds = display->getBounds();
1985 if (display->isPoweredOn()) {
1986 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001987
Jeff Sharkey76488112017-02-27 14:15:18 -07001988 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001989 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07001990 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001991 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001992 Region drawRegion(tr.transform(
1993 layer->visibleNonTransparentRegion));
1994 drawRegion.andSelf(bounds);
1995 if (!drawRegion.isEmpty()) {
1996 layersSortedByZ.add(layer);
1997 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001998 // Clear out the HWC layer if this layer was
1999 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002000 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002001 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002002 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002003 // WM changes display->layerStack upon sleep/awake.
2004 // Here we make sure we delete the HWC layers even if
2005 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002006 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002007 }
2008
2009 // If a layer is not going to get a release fence because
2010 // it is invisible, but it is also going to release its
2011 // old buffer, add it to the list of layers needing
2012 // fences.
2013 if (hwcLayerDestroyed) {
2014 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2015 mLayersWithQueuedFrames.cend(), layer);
2016 if (found != mLayersWithQueuedFrames.cend()) {
2017 layersNeedingFences.add(layer);
2018 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002019 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002020 });
2021 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 display->setVisibleLayersSortedByZ(layersSortedByZ);
2023 display->setLayersNeedingFences(layersNeedingFences);
2024 display->undefinedRegion.set(bounds);
2025 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2026 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002027 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002028 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002030
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002033// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002034// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002035// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002036// The returned HDR data space is one of
2037// - Dataspace::UNKNOWN
2038// - Dataspace::BT2020_HLG
2039// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002040Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2041 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002042 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002043 *outHdrDataSpace = Dataspace::UNKNOWN;
2044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002045 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002046 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047 case Dataspace::V0_SCRGB:
2048 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002049 case Dataspace::BT2020:
2050 case Dataspace::BT2020_ITU:
2051 case Dataspace::BT2020_LINEAR:
2052 case Dataspace::DISPLAY_BT2020:
2053 bestDataSpace = Dataspace::DISPLAY_BT2020;
2054 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002055 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002056 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002057 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 case Dataspace::BT2020_PQ:
2059 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002060 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002061 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002062 case Dataspace::BT2020_HLG:
2063 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002064 // When there's mixed PQ content and HLG content, we set the HDR
2065 // data space to be BT2020_PQ and convert HLG to PQ.
2066 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2067 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002068 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002069 break;
2070 default:
2071 break;
2072 }
Romain Guy54f154a2017-10-24 21:40:32 +01002073 }
2074
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002075 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002076}
2077
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002078// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002079void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2080 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002081 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2082 *outMode = ColorMode::NATIVE;
2083 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002084 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002085 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002086 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002087
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002088 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002089 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002090
Peiyong Lindfde5112018-06-05 10:58:41 -07002091 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002092 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002093 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002094 if (isHdr) {
2095 bestDataSpace = hdrDataSpace;
2096 }
2097
Chia-I Wu0d711262018-05-21 15:19:35 -07002098 RenderIntent intent;
2099 switch (mDisplayColorSetting) {
2100 case DisplayColorSetting::MANAGED:
2101 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002102 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002103 break;
2104 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002105 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002106 break;
2107 default: // vendor display color setting
2108 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2109 break;
2110 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002112 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002113}
2114
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002116{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117 bool dirty = !display->getDirtyRegion(false).isEmpty();
2118 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2119 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002120
David Sodmanfa9b2af2017-12-24 13:28:59 -08002121 // If nothing has changed (!dirty), don't recompose.
2122 // If something changed, but we don't currently have any visible layers,
2123 // and didn't when we last did a composition, then skip it this time.
2124 // The second rule does two things:
2125 // - When all layers are removed from a display, we'll emit one black
2126 // frame, then nothing more until we get new layers.
2127 // - When a display is created with a private layer stack, we won't
2128 // emit any black frames until a layer is added to the layer stack.
2129 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002130
Dominik Laskowski075d3172018-05-24 15:50:06 -07002131 const char flagPrefix[] = {'-', '+'};
2132 static_cast<void>(flagPrefix);
2133 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2134 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2135 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002136
David Sodmanfa9b2af2017-12-24 13:28:59 -08002137 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 if (mustRecompose) {
2140 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002141 }
2142}
2143
David Sodmanfa9b2af2017-12-24 13:28:59 -08002144void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002145{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002146 if (!display->isPoweredOn()) {
2147 return;
David Sodman2b406362017-12-15 13:33:47 -08002148 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149
Dominik Laskowski05275f12018-11-01 15:03:24 -07002150 status_t result = display->prepareFrame(getHwComposer(),
2151 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002152 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2153 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002154}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002155
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002157 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002158 ALOGV("doComposition");
2159
David Sodmanfa9b2af2017-12-24 13:28:59 -08002160 if (display->isPoweredOn()) {
2161 // transform the dirty region into this screen's coordinate space
2162 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002163
David Sodmanfa9b2af2017-12-24 13:28:59 -08002164 // repaint the framebuffer (if needed)
2165 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002166
David Sodmanfa9b2af2017-12-24 13:28:59 -08002167 display->dirtyRegion.clear();
2168 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002169 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002171}
2172
David Sodmanfa9b2af2017-12-24 13:28:59 -08002173void SurfaceFlinger::postFrame()
2174{
2175 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002176 const auto display = getDefaultDisplayDeviceLocked();
2177 if (display && getHwComposer().isConnected(*display->getId())) {
2178 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002179 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2180 logFrameStats();
2181 }
2182 }
2183}
2184
2185void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186{
Mathias Agopian841cde52012-03-01 15:44:37 -08002187 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002188 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002189
David Sodmanfa9b2af2017-12-24 13:28:59 -08002190 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002191
David Sodmanfa9b2af2017-12-24 13:28:59 -08002192 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002193 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002194 if (displayId) {
2195 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002196 }
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002197 display->onSwapBuffersCompleted();
2198 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002199 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002200 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002201
Chia-I Wu7b549592017-11-15 09:14:57 -08002202 // The layer buffer from the previous frame (if any) is released
2203 // by HWC only when the release fence from this frame (if any) is
2204 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002205 if (displayId && layer->hasHwcLayer(*displayId)) {
2206 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2207 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002208 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002209
2210 // If the layer was client composited in the previous frame, we
2211 // need to merge with the previous client target acquire fence.
2212 // Since we do not track that, always merge with the current
2213 // client target acquire fence when it is available, even though
2214 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002215 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002216 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002218 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002219
David Sodman15094112018-10-11 09:39:37 -07002220 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002221 }
Chia-I Wu83806892017-11-16 10:50:20 -08002222
2223 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002224 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002225 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 sp<Fence> presentFence =
2228 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002230 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002231 }
2232 }
2233
Dominik Laskowski075d3172018-05-24 15:50:06 -07002234 if (displayId) {
2235 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002236 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002237 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238}
2239
Mathias Agopian87baae12012-07-31 12:38:26 -07002240void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241{
Mathias Agopian841cde52012-03-01 15:44:37 -08002242 ATRACE_CALL();
2243
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002244 // here we keep a copy of the drawing state (that is the state that's
2245 // going to be overwritten by handleTransactionLocked()) outside of
2246 // mStateLock so that the side-effects of the State assignment
2247 // don't happen with mStateLock held (which can cause deadlocks).
2248 State drawingState(mDrawingState);
2249
Mathias Agopianca4d3602011-05-19 15:38:14 -07002250 Mutex::Autolock _l(mStateLock);
2251 const nsecs_t now = systemTime();
2252 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253
Mathias Agopianca4d3602011-05-19 15:38:14 -07002254 // Here we're guaranteed that some transaction flags are set
2255 // so we can call handleTransactionLocked() unconditionally.
2256 // We call getTransactionFlags(), which will also clear the flags,
2257 // with mStateLock held to guarantee that mCurrentState won't change
2258 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002259
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002260 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002261 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002262 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002263
Mathias Agopianca4d3602011-05-19 15:38:14 -07002264 mLastTransactionTime = systemTime() - now;
2265 mDebugInTransaction = 0;
2266 invalidateHwcGeometry();
2267 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002268}
2269
Lloyd Piqueba04e622017-12-14 17:11:26 -08002270void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2271 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002272 const std::optional<DisplayIdentificationInfo> info =
2273 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002274
Dominik Laskowski075d3172018-05-24 15:50:06 -07002275 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002276 continue;
2277 }
2278
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002281 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002282 mPhysicalDisplayTokens[info->id] = new BBinder();
2283 DisplayDeviceState state;
2284 state.displayId = info->id;
2285 state.isSecure = true; // All physical displays are currently considered secure.
2286 state.displayName = info->name;
2287 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2288 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002289 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002290 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002291 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002292
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2294 if (index >= 0) {
2295 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2296 mInterceptor->saveDisplayDeletion(state.sequenceId);
2297 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002298 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002299 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002300 }
2301
2302 processDisplayChangesLocked();
2303 }
2304
2305 mPendingHotplugEvents.clear();
2306}
2307
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002309 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2310 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2311 const sp<IGraphicBufferProducer>& producer) {
2312 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2313 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002314 creationArgs.isSecure = state.isSecure;
2315 creationArgs.displaySurface = dispSurface;
2316 creationArgs.hasWideColorGamut = false;
2317 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318
Dominik Laskowski075d3172018-05-24 15:50:06 -07002319 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2320 creationArgs.isPrimary = isInternalDisplay;
2321
2322 if (useColorManagement && displayId) {
2323 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002325 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002326 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328
Dominik Laskowski7e045462018-05-30 13:02:02 -07002329 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002331 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332 }
tangrobin6753a022018-08-10 10:58:54 +08002333 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 if (displayId) {
2336 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002337 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002339 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340
Lloyd Pique90c115d2018-09-18 21:39:42 -07002341 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002343 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344
Alec Mouri05874642018-11-14 22:34:02 +00002345 /*
2346 * Create our display's surface
2347 */
2348 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
2349 renderSurface->setCritical(isInternalDisplay);
2350 renderSurface->setAsync(state.isVirtual());
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002351 renderSurface->setNativeWindow(nativeWindow.get());
Alec Mouri05874642018-11-14 22:34:02 +00002352 creationArgs.renderSurface = std::move(renderSurface);
2353
Lloyd Pique99d3da52018-01-22 17:48:03 -08002354 // Make sure that composition can never be stalled by a virtual display
2355 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002356 // in two places:
2357 // * Here, in case the display is composed entirely by HWC.
2358 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2359 // window's swap interval in eglMakeCurrent, so they'll override the
2360 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002361 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2363 }
2364
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 creationArgs.displayInstallOrientation =
2366 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002367
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370
Lloyd Pique90c115d2018-09-18 21:39:42 -07002371 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372
2373 if (maxFrameBufferAcquiredBuffers >= 3) {
2374 nativeWindowSurface->preallocateBuffers();
2375 }
2376
2377 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002381 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 if (!state.isVirtual()) {
2386 LOG_ALWAYS_FATAL_IF(!displayId);
2387 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002388 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002390 display->setLayerStack(state.layerStack);
2391 display->setProjection(state.orientation, state.viewport, state.frame);
2392 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002394 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002395}
2396
Lloyd Pique347200f2017-12-14 17:00:15 -08002397void SurfaceFlinger::processDisplayChangesLocked() {
2398 // here we take advantage of Vector's copy-on-write semantics to
2399 // improve performance by skipping the transaction entirely when
2400 // know that the lists are identical
2401 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2402 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2403 if (!curr.isIdenticalTo(draw)) {
2404 mVisibleRegionsDirty = true;
2405 const size_t cc = curr.size();
2406 size_t dc = draw.size();
2407
2408 // find the displays that were removed
2409 // (ie: in drawing state but not in current state)
2410 // also handle displays that changed
2411 // (ie: displays that are in both lists)
2412 for (size_t i = 0; i < dc;) {
2413 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2414 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 // Save display IDs before disconnecting.
2416 const auto internalDisplayId = getInternalDisplayId();
2417 const auto externalDisplayId = getExternalDisplayId();
2418
Lloyd Pique347200f2017-12-14 17:00:15 -08002419 // in drawing state but not in current state
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002420 // Call makeCurrent() on the primary display so we can
2421 // be sure that nothing associated with this display
2422 // is current.
2423 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2424 defaultDisplay->makeCurrent();
2425 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002426 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2427 display->disconnect(getHwComposer());
2428 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002430 if (mUseScheduler) {
2431 mScheduler->hotplugReceived(mAppConnectionHandle,
2432 EventThread::DisplayType::Primary, false);
2433 } else {
2434 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2435 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002437 if (mUseScheduler) {
2438 mScheduler->hotplugReceived(mAppConnectionHandle,
2439 EventThread::DisplayType::External, false);
2440 } else {
2441 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2442 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002443 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002444 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 } else {
2446 // this display is in both lists. see if something changed.
2447 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2450 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2451 if (state_binder != draw_binder) {
2452 // changing the surface is like destroying and
2453 // recreating the DisplayDevice, so we just remove it
2454 // from the drawing state, so that it get re-added
2455 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002456 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2457 display->disconnect(getHwComposer());
2458 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002459 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002460 mDrawingState.displays.removeItemsAt(i);
2461 dc--;
2462 // at this point we must loop to the next item
2463 continue;
2464 }
2465
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002469 }
2470 if ((state.orientation != draw[i].orientation) ||
2471 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002472 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002473 }
2474 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002476 }
2477 }
2478 }
2479 ++i;
2480 }
2481
2482 // find displays that were added
2483 // (ie: in current state but not in drawing state)
2484 for (size_t i = 0; i < cc; i++) {
2485 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2486 const DisplayDeviceState& state(curr[i]);
2487
2488 sp<DisplaySurface> dispSurface;
2489 sp<IGraphicBufferProducer> producer;
2490 sp<IGraphicBufferProducer> bqProducer;
2491 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002492 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002495 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 // Virtual displays without a surface are dormant:
2497 // they have external state (layer stack, projection,
2498 // etc.) but no internal state (i.e. a DisplayDevice).
2499 if (state.surface != nullptr) {
2500 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 int width = 0;
2503 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2504 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2505 int height = 0;
2506 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2507 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2508 int intFormat = 0;
2509 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2510 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002511 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002512
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 displayId =
2514 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 }
2516
2517 // TODO: Plumb requested format back up to consumer
2518
2519 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 bqProducer, bqConsumer,
2522 state.displayName);
2523
2524 dispSurface = vds;
2525 producer = vds;
2526 }
2527 } else {
2528 ALOGE_IF(state.surface != nullptr,
2529 "adding a supported display, but rendering "
2530 "surface is provided (%p), ignoring it",
2531 state.surface.get());
2532
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 displayId = state.displayId;
2534 LOG_ALWAYS_FATAL_IF(!displayId);
2535 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002536 producer = bqProducer;
2537 }
2538
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002542 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002543 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002544 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 LOG_ALWAYS_FATAL_IF(!displayId);
2546
2547 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002548 if (mUseScheduler) {
2549 mScheduler->hotplugReceived(mAppConnectionHandle,
2550 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002551 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002552 } else {
2553 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2554 true);
2555 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002557 if (mUseScheduler) {
2558 mScheduler->hotplugReceived(mAppConnectionHandle,
2559 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002560 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002561 } else {
2562 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2563 true);
2564 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002565 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002566 }
2567 }
2568 }
2569 }
2570 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002571
2572 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002573}
2574
Mathias Agopian87baae12012-07-31 12:38:26 -07002575void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002576{
Dan Stoza7dde5992015-05-22 09:51:44 -07002577 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002578 mCurrentState.traverseInZOrder([](Layer* layer) {
2579 layer->notifyAvailableFrames();
2580 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002581
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 /*
2583 * Traversal of the children
2584 * (perform the transaction for each of them if needed)
2585 */
2586
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002588 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002590 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591
2592 const uint32_t flags = layer->doTransaction(0);
2593 if (flags & Layer::eVisibleRegion)
2594 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002595 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 }
2597
2598 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002599 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 */
2601
Mathias Agopiane57f2922012-08-09 16:29:12 -07002602 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002603 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002604 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002605 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002607 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002608 // The transform hint might have changed for some layers
2609 // (either because a display has changed, or because a layer
2610 // as changed).
2611 //
2612 // Walk through all the layers in currentLayers,
2613 // and update their transform hint.
2614 //
2615 // If a layer is visible only on a single display, then that
2616 // display is used to calculate the hint, otherwise we use the
2617 // default display.
2618 //
2619 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2620 // the hint is set before we acquire a buffer from the surface texture.
2621 //
2622 // NOTE: layer transactions have taken place already, so we use their
2623 // drawing state. However, SurfaceFlinger's own transaction has not
2624 // happened yet, so we must use the current state layer list
2625 // (soon to become the drawing state list).
2626 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002627 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002628 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002629 bool first = true;
2630 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002631 // NOTE: we rely on the fact that layers are sorted by
2632 // layerStack first (so we don't have to traverse the list
2633 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002635 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002636 currentlayerStack = layerStack;
2637 // figure out if this layerstack is mirrored
2638 // (more than one display) if so, pick the default display,
2639 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002640 hintDisplay = nullptr;
2641 for (const auto& [token, display] : mDisplays) {
2642 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2643 if (hintDisplay) {
2644 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002645 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002646 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002647 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002648 }
2649 }
2650 }
2651 }
Chet Haase91d25932013-04-11 15:24:55 -07002652
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002653 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002654 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2655 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002656
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002657 // could be null when this layer is using a layerStack
2658 // that is not visible on any display. Also can occur at
2659 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002660 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002661 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002662
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002663 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002664 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 if (hintDisplay) {
2666 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002667 }
Robert Carr2047fae2016-11-28 14:09:09 -08002668
2669 first = false;
2670 });
Mathias Agopian84300952012-11-21 16:02:13 -08002671 }
2672
2673
Mathias Agopian3559b072012-08-15 13:46:03 -07002674 /*
2675 * Perform our own transaction if needed
2676 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677
2678 if (mLayersAdded) {
2679 mLayersAdded = false;
2680 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002681 mVisibleRegionsDirty = true;
2682 }
2683
2684 // some layers might have been removed, so
2685 // we need to update the regions they're exposing.
2686 if (mLayersRemoved) {
2687 mLayersRemoved = false;
2688 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002689 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002691 // this layer is not visible anymore
2692 // TODO: we could traverse the tree from front to back and
2693 // compute the actual visible region
2694 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 Region visibleReg;
2696 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002697 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002698 }
Robert Carr2047fae2016-11-28 14:09:09 -08002699 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 }
2701
2702 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002703
2704 updateCursorAsync();
2705}
2706
2707void SurfaceFlinger::updateCursorAsync()
2708{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002710 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002711 continue;
2712 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2715 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002716 }
2717 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718}
2719
chaviw61626f22018-11-15 16:26:27 -08002720void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2721 if (layer->hasReadyFrame()) {
2722 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2723 if (layer->shouldPresentNow(expectedPresentTime)) {
2724 bool ignored = false;
2725 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2726 }
2727 }
2728 layer->releasePendingBuffer(systemTime());
2729}
2730
Mathias Agopian4fec8732012-06-29 14:12:52 -07002731void SurfaceFlinger::commitTransaction()
2732{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002733 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 for (const auto& l : mLayersPendingRemoval) {
2736 recordBufferingStats(l->getName().string(),
2737 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002738
2739 // We need to release the HWC layers when the Layer is removed
2740 // from the current state otherwise the HWC layer just continues
2741 // showing at its last configured state until we eventually
2742 // abandon the buffer queue.
2743 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002744 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002745 child->destroyHwcLayersForAllDisplays();
2746 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002747 });
Robert Carr2e102c92018-10-23 12:11:15 -07002748 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002749 }
2750 mLayersPendingRemoval.clear();
2751 }
2752
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002753 // If this transaction is part of a window animation then the next frame
2754 // we composite should be considered an animation as well.
2755 mAnimCompositionPending = mAnimTransactionPending;
2756
Mathias Agopian4fec8732012-06-29 14:12:52 -07002757 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002758 // clear the "changed" flags in current state
2759 mCurrentState.colorMatrixChanged = false;
2760
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 mDrawingState.traverseInZOrder([](Layer* layer) {
2762 layer->commitChildList();
2763 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002764 mTransactionPending = false;
2765 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002766 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767}
2768
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002769void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2770 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002771 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 Region aboveOpaqueLayers;
2775 Region aboveCoveredLayers;
2776 Region dirty;
2777
Mathias Agopian87baae12012-07-31 12:38:26 -07002778 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779
Robert Carr2047fae2016-11-28 14:09:09 -08002780 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002782 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783
Jesse Hall01e29052013-02-19 16:13:35 -08002784 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002785 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002786 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002787 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002788
Mathias Agopianab028732010-03-16 16:41:46 -07002789 /*
2790 * opaqueRegion: area of a surface that is fully opaque.
2791 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002793
2794 /*
2795 * visibleRegion: area of a surface that is visible on screen
2796 * and not fully transparent. This is essentially the layer's
2797 * footprint minus the opaque regions above it.
2798 * Areas covered by a translucent surface are considered visible.
2799 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002801
2802 /*
2803 * coveredRegion: area of a surface that is covered by all
2804 * visible regions above it (which includes the translucent areas).
2805 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002807
Jesse Halla8026d22012-09-25 13:25:04 -07002808 /*
2809 * transparentRegion: area of a surface that is hinted to be completely
2810 * transparent. This is only used to tell when the layer has no visible
2811 * non-transparent regions and can be removed from the layer list. It
2812 * does not affect the visibleRegion of this layer or any layers
2813 * beneath it. The hint may not be correct if apps don't respect the
2814 * SurfaceView restrictions (which, sadly, some don't).
2815 */
2816 Region transparentRegion;
2817
Mathias Agopianab028732010-03-16 16:41:46 -07002818
2819 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002820 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002821 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002822 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002824 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002825 if (!visibleRegion.isEmpty()) {
2826 // Remove the transparent area from the visible region
2827 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002828 if (tr.preserveRects()) {
2829 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002830 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002832 // transformation too complex, can't do the
2833 // transparent region optimization.
2834 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002835 }
Mathias Agopianab028732010-03-16 16:41:46 -07002836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837
Mathias Agopianab028732010-03-16 16:41:46 -07002838 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002840 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002841 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002842 // the opaque region is the layer's footprint
2843 opaqueRegion = visibleRegion;
2844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 }
2846 }
2847
Robert Carre5f4f692018-01-12 13:12:28 -08002848 if (visibleRegion.isEmpty()) {
2849 layer->clearVisibilityRegions();
2850 return;
2851 }
2852
Mathias Agopianab028732010-03-16 16:41:46 -07002853 // Clip the covered region to the visible region
2854 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2855
2856 // Update aboveCoveredLayers for next (lower) layer
2857 aboveCoveredLayers.orSelf(visibleRegion);
2858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 // subtract the opaque region covered by the layers above us
2860 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861
2862 // compute this layer's dirty region
2863 if (layer->contentDirty) {
2864 // we need to invalidate the whole region
2865 dirty = visibleRegion;
2866 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002867 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 layer->contentDirty = false;
2869 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002870 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002871 * the exposed region consists of two components:
2872 * 1) what's VISIBLE now and was COVERED before
2873 * 2) what's EXPOSED now less what was EXPOSED before
2874 *
2875 * note that (1) is conservative, we start with the whole
2876 * visible region but only keep what used to be covered by
2877 * something -- which mean it may have been exposed.
2878 *
2879 * (2) handles areas that were not covered by anything but got
2880 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002881 */
Mathias Agopianab028732010-03-16 16:41:46 -07002882 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002883 const Region oldVisibleRegion = layer->visibleRegion;
2884 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002885 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2886 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 }
2888 dirty.subtractSelf(aboveOpaqueLayers);
2889
2890 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002891 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892
Mathias Agopianab028732010-03-16 16:41:46 -07002893 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002895
Jesse Halla8026d22012-09-25 13:25:04 -07002896 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 layer->setVisibleRegion(visibleRegion);
2898 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002899 layer->setVisibleNonTransparentRegion(
2900 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002901 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902
Mathias Agopian87baae12012-07-31 12:38:26 -07002903 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904}
2905
Chia-I Wuab0c3192017-08-01 11:29:00 -07002906void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002907 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002908 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2909 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002910 }
2911 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002912}
2913
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 ALOGV("handlePageFlip");
2917
Brian Andersond6927fb2016-07-23 23:37:30 -07002918 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919
Mathias Agopian4fec8732012-06-29 14:12:52 -07002920 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002922 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002923
2924 // Store the set of layers that need updates. This set must not change as
2925 // buffers are being latched, as this could result in a deadlock.
2926 // Example: Two producers share the same command stream and:
2927 // 1.) Layer 0 is latched
2928 // 2.) Layer 0 gets a new frame
2929 // 2.) Layer 1 gets a new frame
2930 // 3.) Layer 1 is latched.
2931 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2932 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002933 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002934 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002936 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2937 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002938 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002939 } else {
2940 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002941 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002942 } else {
2943 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002944 }
Robert Carr2047fae2016-11-28 14:09:09 -08002945 });
2946
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002948 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002949 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002950 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002951 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002952 newDataLatched = true;
2953 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002954 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002955
Alec Mouri86770e52018-09-24 22:40:58 +00002956 // Clear the renderengine fence here...
2957 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2958 // clear instead of sp::clear.
2959 getBE().flushFence = Fence::NO_FENCE;
2960
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002961 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002962
2963 // If we will need to wake up at some time in the future to deal with a
2964 // queued frame that shouldn't be displayed during this vsync period, wake
2965 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002966 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002967 signalLayerUpdate();
2968 }
2969
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002970 // enter boot animation on first buffer latch
2971 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2972 ALOGI("Enter boot animation");
2973 mBootStage = BootStage::BOOTANIMATION;
2974 }
2975
Dan Stoza6b9454d2014-11-07 16:00:59 -08002976 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002977 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978}
2979
Mathias Agopianad456f92011-01-13 17:53:01 -08002980void SurfaceFlinger::invalidateHwcGeometry()
2981{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002983}
2984
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002985void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002986 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002987 // We only need to actually compose the display if:
2988 // 1) It is being handled by hardware composer, which may need this to
2989 // keep its virtual display state machine in sync, or
2990 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07002991 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002993 return;
2994 }
2995
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002997 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002998
2999 // swap buffers (presentation)
Alec Mouri8d4f90a2018-11-14 22:33:24 +00003000 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001}
3002
Alec Mouri8d4f90a2018-11-14 22:33:24 +00003003bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003004 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 const Region bounds(display->bounds());
3007 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003008 const auto displayId = display->getId();
3009 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003010 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003011
Peiyong Lind3788632018-09-18 16:01:31 -07003012 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003013 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003014 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003015
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 if (hasClientComposition) {
3017 ALOGV("hasClientComposition");
3018
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003019 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 if (display->hasWideColorGamut()) {
3021 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003022 }
3023 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003024 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003025 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003026
Dominik Laskowski7e045462018-05-30 13:02:02 -07003027 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003028 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3029 HWC2::Capability::SkipClientColorTransform);
3030
Peiyong Lind3788632018-09-18 16:01:31 -07003031 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003032 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3033 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003034 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003035 }
3036
Chia-I Wud49d6692018-06-27 07:17:41 +08003037 // The current enhanced saturation matrix is designed to enhance Display P3,
3038 // thus we only apply this matrix when the render intent is not colorimetric
3039 // and the output color space is Display P3.
3040 needsEnhancedColorMatrix =
3041 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3042 outputDataspace == Dataspace::DISPLAY_P3);
3043 if (needsEnhancedColorMatrix) {
3044 colorMatrix *= mEnhancedSaturationMatrix;
3045 }
3046
Alec Mouri8d4f90a2018-11-14 22:33:24 +00003047 if (!display->makeCurrent()) {
3048 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
3049 display->getDisplayName().c_str());
3050 getRenderEngine().resetCurrentSurface();
3051
3052 // |mStateLock| not needed as we are on the main thread
3053 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3054 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3055 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3056 }
3057 return false;
3058 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003059
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003060 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003062 // when using overlays, we assume a fully transparent framebuffer
3063 // NOTE: we could reduce how much we need to clear, for instance
3064 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003065 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003066 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003067 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003068 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003069 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003070 // we're left with the letterbox region
3071 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003072 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003073
3074 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003075 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003076
Mathias Agopianb9494d52012-04-18 02:28:45 -07003077 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003078 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003079 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003080 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003081 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003082 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003083
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003084 const Rect& bounds = display->getBounds();
3085 const Rect& scissor = display->getScissor();
3086 if (scissor != bounds) {
3087 // scissor doesn't match the screen's dimensions, so we
3088 // need to clear everything outside of it and enable
3089 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003090
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003091 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003092 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003093 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003094 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003095
Mathias Agopian85d751c2012-08-29 16:59:24 -07003096 /*
3097 * and then, render the layers targeted at the framebuffer
3098 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003099
Dan Stoza9e56aa02015-11-02 13:00:03 -08003100 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003101 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003102 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003103 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003104 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003105 displayTransform.transform(layer->visibleRegion)));
3106 ALOGV("Layer: %s", layer->getName().string());
3107 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003108 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003109 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003110 case HWC2::Composition::Cursor:
3111 case HWC2::Composition::Device:
3112 case HWC2::Composition::Sideband:
3113 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003114 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003115 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003116 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003117 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3118 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003119 // never clear the very first layer since we're
3120 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003121 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003122 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003123 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003124 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003126 if (layer->hasColorTransform()) {
3127 mat4 tmpMatrix;
3128 if (applyColorMatrix) {
3129 tmpMatrix = mDrawingState.colorMatrix;
3130 }
3131 tmpMatrix *= layer->getColorTransform();
3132 if (needsEnhancedColorMatrix) {
3133 tmpMatrix *= mEnhancedSaturationMatrix;
3134 }
3135 getRenderEngine().setColorTransform(tmpMatrix);
3136 } else {
3137 getRenderEngine().setColorTransform(colorMatrix);
3138 }
David Sodmanc1498e62018-09-12 14:36:26 -07003139 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003140 break;
3141 }
3142 default:
3143 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003144 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003145 } else {
3146 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003147 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003148 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003149 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003150
Alec Mouri8d4f90a2018-11-14 22:33:24 +00003151 // Clear color transform matrix at the end of the frame.
3152 getRenderEngine().setColorTransform(mat4());
3153
3154 // disable scissor at the end of the frame
3155 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003156 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Chia-I Wu28e3a252018-09-07 12:05:02 -07003159void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003160 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003161 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162}
3163
Dan Stoza7d89d062015-04-30 13:29:25 -07003164status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003165 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003166 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 const sp<Layer>& lbc,
3168 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003169{
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 // add this layer to the current state list
3171 {
3172 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003174 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3175 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003176 return NO_MEMORY;
3177 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003178 if (parent == nullptr) {
3179 mCurrentState.layersSortedByZ.add(lbc);
3180 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003181 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003182 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003183 lbc->onRemovedFromCurrentState();
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003184 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003185 parent->addChild(lbc);
3186 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003187
Yiwei Zhang243b3782018-05-15 17:40:04 -07003188 if (gbc != nullptr) {
3189 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3190 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3191 mMaxGraphicBufferProducerListSize,
3192 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3193 mGraphicBufferProducerList.size(),
3194 mMaxGraphicBufferProducerListSize, mNumLayers);
3195 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003196 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003197 }
3198
Mathias Agopian96f08192010-06-02 23:28:45 -07003199 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003200 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003201
Dan Stoza7d89d062015-04-30 13:29:25 -07003202 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003203}
3204
Robert Carr8d2711b2018-11-14 16:36:18 -08003205status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003206 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003207 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003208}
Robert Carr7f9b8992017-03-10 11:08:39 -08003209
Robert Carr8d2711b2018-11-14 16:36:18 -08003210status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003212 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003214 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003215 } else {
3216 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003217 }
3218
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003219 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003220
3221 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003222 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223}
3224
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003225uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003226 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003227}
3228
Mathias Agopian3f844832013-08-07 21:24:32 -07003229uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003230 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231}
3232
Mathias Agopian3f844832013-08-07 21:24:32 -07003233uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003234 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003235}
3236
3237uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003238 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003239 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003240 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003242 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 }
3244 return old;
3245}
3246
chaviwca27f252018-02-06 16:46:39 -08003247bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3248 for (const ComposerState& state : states) {
3249 // Here we need to check that the interface we're given is indeed
3250 // one of our own. A malicious client could give us a nullptr
3251 // IInterface, or one of its own or even one of our own but a
3252 // different type. All these situations would cause us to crash.
3253 if (state.client == nullptr) {
3254 return true;
3255 }
3256
3257 sp<IBinder> binder = IInterface::asBinder(state.client);
3258 if (binder == nullptr) {
3259 return true;
3260 }
3261
3262 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3263 return true;
3264 }
3265 }
3266 return false;
3267}
3268
Mathias Agopian8b33f032012-07-24 20:43:54 -07003269void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003270 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003271 const Vector<DisplayState>& displays,
3272 uint32_t flags)
3273{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003274 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003275 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003276 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003277
chaviwca27f252018-02-06 16:46:39 -08003278 if (containsAnyInvalidClientState(states)) {
3279 return;
3280 }
3281
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003282 if (flags & eAnimation) {
3283 // For window updates that are part of an animation we must wait for
3284 // previous animation "frames" to be handled.
3285 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003286 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003287 if (CC_UNLIKELY(err != NO_ERROR)) {
3288 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003289 // caller after a few seconds.
3290 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3291 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003292 mAnimTransactionPending = false;
3293 break;
3294 }
3295 }
3296 }
3297
chaviwca27f252018-02-06 16:46:39 -08003298 for (const DisplayState& display : displays) {
3299 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003300 }
3301
Marissa Walle2ffb422018-10-12 11:33:52 -07003302 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003303 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003304 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003305 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003306 // If the state doesn't require a traversal and there are callbacks, send them now
3307 if (!(clientStateFlags & eTraversalNeeded)) {
3308 mTransactionCompletedThread.sendCallbacks();
3309 }
3310 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003311
3312 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3313 // as destroyed should only occur after setting all other states. This is to allow for a
3314 // child re-parent to happen before marking its original parent as destroyed (which would
3315 // then mark the child as destroyed).
3316 for (const ComposerState& state : states) {
3317 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003318 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003319
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003320 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3321 // anyway. This can be used as a flush mechanism for previous async transactions.
3322 // Empty animation transaction can be used to simulate back-pressure, so also force a
3323 // transaction for empty animation transactions.
3324 if (transactionFlags == 0 &&
3325 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003326 transactionFlags = eTransactionNeeded;
3327 }
3328
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003330 if (mInterceptor->isEnabled()) {
3331 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003332 }
Irvel468051e2016-06-13 16:44:44 -07003333
Mathias Agopian386aa982011-11-07 21:58:03 -08003334 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003335 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3336 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003337 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003338
3339 // if this is a synchronous transaction, wait for it to take effect
3340 // before returning.
3341 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003342 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003343 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003344 if (flags & eAnimation) {
3345 mAnimTransactionPending = true;
3346 }
3347 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003348 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3349 if (CC_UNLIKELY(err != NO_ERROR)) {
3350 // just in case something goes wrong in SF, return to the
3351 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003352 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3353 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003354 break;
3355 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003356 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 }
3358}
3359
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003360uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3361 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3362 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003363
Mathias Agopiane57f2922012-08-09 16:29:12 -07003364 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003365 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3366
3367 const uint32_t what = s.what;
3368 if (what & DisplayState::eSurfaceChanged) {
3369 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3370 state.surface = s.surface;
3371 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003372 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003374 if (what & DisplayState::eLayerStackChanged) {
3375 if (state.layerStack != s.layerStack) {
3376 state.layerStack = s.layerStack;
3377 flags |= eDisplayTransactionNeeded;
3378 }
3379 }
3380 if (what & DisplayState::eDisplayProjectionChanged) {
3381 if (state.orientation != s.orientation) {
3382 state.orientation = s.orientation;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 if (state.frame != s.frame) {
3386 state.frame = s.frame;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 if (state.viewport != s.viewport) {
3390 state.viewport = s.viewport;
3391 flags |= eDisplayTransactionNeeded;
3392 }
3393 }
3394 if (what & DisplayState::eDisplaySizeChanged) {
3395 if (state.width != s.width) {
3396 state.width = s.width;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 if (state.height != s.height) {
3400 state.height = s.height;
3401 flags |= eDisplayTransactionNeeded;
3402 }
3403 }
3404
Mathias Agopiane57f2922012-08-09 16:29:12 -07003405 return flags;
3406}
3407
Robert Carrd4ae7f32018-06-07 16:10:57 -07003408bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3409 IPCThreadState* ipc = IPCThreadState::self();
3410 const int pid = ipc->getCallingPid();
3411 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003412 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003413 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003414 return false;
3415 }
3416 return true;
3417}
3418
chaviwca27f252018-02-06 16:46:39 -08003419uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3420 const layer_state_t& s = composerState.state;
3421 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3422
Mathias Agopian13127d82013-03-05 17:47:11 -08003423 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003424 if (layer == nullptr) {
3425 return 0;
3426 }
3427
chaviw8b3871a2017-11-01 17:41:01 -07003428 uint32_t flags = 0;
3429
3430 const uint32_t what = s.what;
3431 bool geometryAppliesWithResize =
3432 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003433
3434 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3435 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003436 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003437 layer->pushPendingState();
3438 }
3439
chaviw8b3871a2017-11-01 17:41:01 -07003440 if (what & layer_state_t::ePositionChanged) {
3441 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3442 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003443 }
chaviw8b3871a2017-11-01 17:41:01 -07003444 }
3445 if (what & layer_state_t::eLayerChanged) {
3446 // NOTE: index needs to be calculated before we update the state
3447 const auto& p = layer->getParent();
3448 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003449 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003450 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 mCurrentState.layersSortedByZ.removeAt(idx);
3452 mCurrentState.layersSortedByZ.add(layer);
3453 // we need traversal (state changed)
3454 // AND transaction (list changed)
3455 flags |= eTransactionNeeded|eTraversalNeeded;
3456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 } else {
3458 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003459 flags |= eTransactionNeeded|eTraversalNeeded;
3460 }
3461 }
chaviw8b3871a2017-11-01 17:41:01 -07003462 }
3463 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003464 // NOTE: index needs to be calculated before we update the state
3465 const auto& p = layer->getParent();
3466 if (p == nullptr) {
3467 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3468 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3469 mCurrentState.layersSortedByZ.removeAt(idx);
3470 mCurrentState.layersSortedByZ.add(layer);
3471 // we need traversal (state changed)
3472 // AND transaction (list changed)
3473 flags |= eTransactionNeeded|eTraversalNeeded;
3474 }
3475 } else {
3476 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3477 flags |= eTransactionNeeded|eTraversalNeeded;
3478 }
chaviw8b3871a2017-11-01 17:41:01 -07003479 }
3480 }
3481 if (what & layer_state_t::eSizeChanged) {
3482 if (layer->setSize(s.w, s.h)) {
3483 flags |= eTraversalNeeded;
3484 }
3485 }
3486 if (what & layer_state_t::eAlphaChanged) {
3487 if (layer->setAlpha(s.alpha))
3488 flags |= eTraversalNeeded;
3489 }
3490 if (what & layer_state_t::eColorChanged) {
3491 if (layer->setColor(s.color))
3492 flags |= eTraversalNeeded;
3493 }
Peiyong Lind3788632018-09-18 16:01:31 -07003494 if (what & layer_state_t::eColorTransformChanged) {
3495 if (layer->setColorTransform(s.colorTransform)) {
3496 flags |= eTraversalNeeded;
3497 }
3498 }
chaviw8b3871a2017-11-01 17:41:01 -07003499 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003500 // TODO: b/109894387
3501 //
3502 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3503 // rotation. To see the problem observe that if we have a square parent, and a child
3504 // of the same size, then we rotate the child 45 degrees around it's center, the child
3505 // must now be cropped to a non rectangular 8 sided region.
3506 //
3507 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3508 // private API, and the WindowManager only uses rotation in one case, which is on a top
3509 // level layer in which cropping is not an issue.
3510 //
3511 // However given that abuse of rotation matrices could lead to surfaces extending outside
3512 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3513 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3514 // transformations.
3515 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003516 flags |= eTraversalNeeded;
3517 }
3518 if (what & layer_state_t::eTransparentRegionChanged) {
3519 if (layer->setTransparentRegionHint(s.transparentRegion))
3520 flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eFlagsChanged) {
3523 if (layer->setFlags(s.flags, s.mask))
3524 flags |= eTraversalNeeded;
3525 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003526 if (what & layer_state_t::eCropChanged_legacy) {
3527 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003528 flags |= eTraversalNeeded;
3529 }
chaviw8b3871a2017-11-01 17:41:01 -07003530 if (what & layer_state_t::eLayerStackChanged) {
3531 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3532 // We only allow setting layer stacks for top level layers,
3533 // everything else inherits layer stack from its parent.
3534 if (layer->hasParent()) {
3535 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3536 layer->getName().string());
3537 } else if (idx < 0) {
3538 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3539 "that also does not appear in the top level layer list. Something"
3540 " has gone wrong.", layer->getName().string());
3541 } else if (layer->setLayerStack(s.layerStack)) {
3542 mCurrentState.layersSortedByZ.removeAt(idx);
3543 mCurrentState.layersSortedByZ.add(layer);
3544 // we need traversal (state changed)
3545 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003546 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003547 }
3548 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003549 if (what & layer_state_t::eDeferTransaction_legacy) {
3550 if (s.barrierHandle_legacy != nullptr) {
3551 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3552 } else if (s.barrierGbp_legacy != nullptr) {
3553 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003554 if (authenticateSurfaceTextureLocked(gbp)) {
3555 const auto& otherLayer =
3556 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003557 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003558 } else {
3559 ALOGE("Attempt to defer transaction to to an"
3560 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003561 }
3562 }
chaviw8b3871a2017-11-01 17:41:01 -07003563 // We don't trigger a traversal here because if no other state is
3564 // changed, we don't want this to cause any more work
3565 }
3566 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003567 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003568 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003569 if (!hadParent) {
3570 mCurrentState.layersSortedByZ.remove(layer);
3571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 }
3575 if (what & layer_state_t::eReparentChildren) {
3576 if (layer->reparentChildren(s.reparentHandle)) {
3577 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003578 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003579 }
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (what & layer_state_t::eDetachChildren) {
3581 layer->detachChildren();
3582 }
3583 if (what & layer_state_t::eOverrideScalingModeChanged) {
3584 layer->setOverrideScalingMode(s.overrideScalingMode);
3585 // We don't trigger a traversal here because if no other state is
3586 // changed, we don't want this to cause any more work
3587 }
Marissa Wall61c58622018-07-18 10:12:20 -07003588 if (what & layer_state_t::eTransformChanged) {
3589 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3592 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3593 flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eCropChanged) {
3596 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3597 }
3598 if (what & layer_state_t::eBufferChanged) {
3599 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3600 }
3601 if (what & layer_state_t::eAcquireFenceChanged) {
3602 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3603 }
3604 if (what & layer_state_t::eDataspaceChanged) {
3605 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3606 }
3607 if (what & layer_state_t::eHdrMetadataChanged) {
3608 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3609 }
3610 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3611 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3612 }
3613 if (what & layer_state_t::eApiChanged) {
3614 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3615 }
3616 if (what & layer_state_t::eSidebandStreamChanged) {
3617 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3618 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003619
3620 std::vector<sp<CallbackHandle>> callbackHandles;
3621 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3622 mTransactionCompletedThread.run();
3623 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3624 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3625 }
3626 }
3627 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3628 // Do not put anything that updates layer state or modifies flags after
3629 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003630 return flags;
3631}
3632
chaviwca27f252018-02-06 16:46:39 -08003633void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3634 const layer_state_t& state = composerState.state;
3635 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3636
3637 sp<Layer> layer(client->getLayerUser(state.surface));
3638 if (layer == nullptr) {
3639 return;
3640 }
3641
chaviwca27f252018-02-06 16:46:39 -08003642 if (state.what & layer_state_t::eDestroySurface) {
3643 removeLayerLocked(mStateLock, layer);
3644 }
3645}
3646
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003647status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003648 const String8& name,
3649 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003650 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003651 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003652 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003654 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003655 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003656 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003657 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003658 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003659
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660 status_t result = NO_ERROR;
3661
3662 sp<Layer> layer;
3663
Cody Northropbc755282017-03-31 12:00:08 -06003664 String8 uniqueName = getUniqueLayerName(name);
3665
Mathias Agopian3165cc22012-08-08 19:42:09 -07003666 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003667 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003668 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3669 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003670
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003672 case ISurfaceComposerClient::eFXSurfaceBufferState:
3673 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3674 break;
chaviw13fdc492017-06-27 12:40:18 -07003675 case ISurfaceComposerClient::eFXSurfaceColor:
3676 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003677 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003678 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003679 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003680 case ISurfaceComposerClient::eFXSurfaceContainer:
3681 result = createContainerLayer(client,
3682 uniqueName, w, h, flags,
3683 handle, &layer);
3684 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685 default:
3686 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003687 break;
3688 }
3689
Dan Stoza7d89d062015-04-30 13:29:25 -07003690 if (result != NO_ERROR) {
3691 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003693
Chia-I Wuab0c3192017-08-01 11:29:00 -07003694 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3695 // TODO b/64227542
3696 if (windowType == 441731) {
3697 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3698 layer->setPrimaryDisplayOnly();
3699 }
3700
Albert Chaulk479c60c2017-01-27 14:21:34 -05003701 layer->setInfo(windowType, ownerUid);
3702
Robert Carr1f0a16a2016-10-24 16:27:39 -07003703 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003704 if (result != NO_ERROR) {
3705 return result;
3706 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003707 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003708
3709 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003710 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711}
3712
Cody Northropbc755282017-03-31 12:00:08 -06003713String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3714{
3715 bool matchFound = true;
3716 uint32_t dupeCounter = 0;
3717
3718 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3719 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3720
Dan Stoza436ccf32018-06-21 12:10:12 -07003721 // Grab the state lock since we're accessing mCurrentState
3722 Mutex::Autolock lock(mStateLock);
3723
Cody Northropbc755282017-03-31 12:00:08 -06003724 // Loop over layers until we're sure there is no matching name
3725 while (matchFound) {
3726 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003727 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003728 if (layer->getName() == uniqueName) {
3729 matchFound = true;
3730 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3731 }
3732 });
3733 }
3734
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003735 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3736 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003737
3738 return uniqueName;
3739}
3740
Marissa Wallfd668622018-05-10 10:21:13 -07003741status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3742 uint32_t w, uint32_t h, uint32_t flags,
3743 PixelFormat& format, sp<IBinder>* handle,
3744 sp<IGraphicBufferProducer>* gbp,
3745 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003747 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 case PIXEL_FORMAT_TRANSPARENT:
3749 case PIXEL_FORMAT_TRANSLUCENT:
3750 format = PIXEL_FORMAT_RGBA_8888;
3751 break;
3752 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003753 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003754 break;
3755 }
3756
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003757 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003758 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003759 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003760 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003761 *handle = layer->getHandle();
3762 *gbp = layer->getProducer();
3763 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003764 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765
Marissa Wallfd668622018-05-10 10:21:13 -07003766 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003767 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003768}
3769
Marissa Wall61c58622018-07-18 10:12:20 -07003770status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3771 uint32_t w, uint32_t h, uint32_t flags,
3772 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003773 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003774 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003775 *handle = layer->getHandle();
3776 *outLayer = layer;
3777
3778 return NO_ERROR;
3779}
3780
chaviw13fdc492017-06-27 12:40:18 -07003781status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003782 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003783 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003784{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003785 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003787 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003788}
3789
Robert Carr6b3f6c52018-08-13 13:05:17 -07003790status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3791 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3792 sp<IBinder>* handle, sp<Layer>* outLayer)
3793{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003794 *outLayer =
3795 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003796 *handle = (*outLayer)->getHandle();
3797 return NO_ERROR;
3798}
3799
3800
Mathias Agopianac9fa422013-02-11 16:40:36 -08003801status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802{
Robert Carr9524cb32017-02-13 11:32:32 -08003803 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003804 status_t err = NO_ERROR;
3805 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003806 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003807 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003808 err = removeLayer(l);
3809 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3810 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003811 }
3812 return err;
3813}
3814
Robert Carr2e102c92018-10-23 12:11:15 -07003815void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3816 mLayersPendingRemoval.add(layer);
3817 mLayersRemoved = true;
3818 setTransactionFlags(eTransactionNeeded);
3819}
3820
3821void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003822{
Robert Carr2e102c92018-10-23 12:11:15 -07003823 Mutex::Autolock lock(mStateLock);
3824 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003825}
3826
Mathias Agopianb60314a2012-04-10 22:09:54 -07003827// ---------------------------------------------------------------------------
3828
Andy McFadden13a082e2012-08-24 10:16:42 -07003829void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003830 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003831 if (!displayToken) return;
3832
Jesse Hall01e29052013-02-19 16:13:35 -08003833 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003834 Vector<ComposerState> state;
3835 Vector<DisplayState> displays;
3836 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003837 d.what = DisplayState::eDisplayProjectionChanged |
3838 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003839 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003840 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003841 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003842 d.frame.makeInvalid();
3843 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003844 d.width = 0;
3845 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003846 displays.add(d);
3847 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003848
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003849 const auto display = getDisplayDevice(displayToken);
3850 if (!display) return;
3851
3852 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3853
Dominik Laskowski075d3172018-05-24 15:50:06 -07003854 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003855 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003856 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003857
Brian Andersond0010582017-03-07 13:20:31 -08003858 // Use phase of 0 since phase is not known.
3859 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003860 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3861 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003862}
3863
3864void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003865 // Async since we may be called from the main thread.
3866 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003867}
3868
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003869void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3870 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003871 if (display->isVirtual()) {
3872 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003873 return;
3874 }
3875
Dominik Laskowski075d3172018-05-24 15:50:06 -07003876 const auto displayId = display->getId();
3877 LOG_ALWAYS_FATAL_IF(!displayId);
3878
Dominik Laskowski34157762018-10-31 13:07:19 -07003879 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003880
3881 int currentMode = display->getPowerMode();
3882 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003883 return;
3884 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003885
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003886 display->setPowerMode(mode);
3887
Lloyd Pique4dccc412018-01-22 17:21:36 -08003888 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003889 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003891 if (idx < 0) {
3892 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3893 return;
3894 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003895 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003896 }
3897
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003899 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003900 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003901 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003902 if (mUseScheduler) {
3903 mScheduler->onScreenAcquired(mAppConnectionHandle);
3904 } else {
3905 mEventThread->onScreenAcquired();
3906 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003907 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003908 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003910 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003911 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003912 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003913
3914 struct sched_param param = {0};
3915 param.sched_priority = 1;
3916 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3917 ALOGW("Couldn't set SCHED_FIFO on display on");
3918 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003919 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003920 // Turn off the display
3921 struct sched_param param = {0};
3922 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3923 ALOGW("Couldn't set SCHED_OTHER on display off");
3924 }
3925
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003926 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003927 if (mUseScheduler) {
3928 mScheduler->disableHardwareVsync(true);
3929 } else {
3930 disableHardwareVsync(true); // also cancels any in-progress resync
3931 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003932 if (mUseScheduler) {
3933 mScheduler->onScreenReleased(mAppConnectionHandle);
3934 } else {
3935 mEventThread->onScreenReleased();
3936 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003937 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003938
Dominik Laskowski075d3172018-05-24 15:50:06 -07003939 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003940 mVisibleRegionsDirty = true;
3941 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003942 } else if (mode == HWC_POWER_MODE_DOZE ||
3943 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003944 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003945 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003947 if (mUseScheduler) {
3948 mScheduler->onScreenAcquired(mAppConnectionHandle);
3949 } else {
3950 mEventThread->onScreenAcquired();
3951 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003952 resyncToHardwareVsync(true);
3953 }
3954 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3955 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003956 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003957 if (mUseScheduler) {
3958 mScheduler->disableHardwareVsync(true);
3959 } else {
3960 disableHardwareVsync(true); // also cancels any in-progress resync
3961 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003962 if (mUseScheduler) {
3963 mScheduler->onScreenReleased(mAppConnectionHandle);
3964 } else {
3965 mEventThread->onScreenReleased();
3966 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003967 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003968 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003969 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003970 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003971 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003972 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003973
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003974 if (display->isPrimary()) {
3975 mTimeStats.setPowerMode(mode);
3976 }
3977
Dominik Laskowski34157762018-10-31 13:07:19 -07003978 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003979}
3980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003981void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003982 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003983 const auto display = getDisplayDevice(displayToken);
3984 if (!display) {
3985 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3986 displayToken.get());
3987 } else if (display->isVirtual()) {
3988 ALOGW("Attempt to set power mode %d for virtual display", mode);
3989 } else {
3990 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003991 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003992 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003993}
3994
3995// ---------------------------------------------------------------------------
3996
Lloyd Pique755e3192018-01-31 16:46:15 -08003997status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3998 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003999 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004000
Mathias Agopianbd115332013-04-18 16:41:04 -07004001 IPCThreadState* ipc = IPCThreadState::self();
4002 const int pid = ipc->getCallingPid();
4003 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004004
Mathias Agopianbd115332013-04-18 16:41:04 -07004005 if ((uid != AID_SHELL) &&
4006 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004007 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004008 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004010 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004011 // (this would indicate SF is stuck, but we want to be able to
4012 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004013 status_t err = mStateLock.timedLock(s2ns(1));
4014 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004015 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004016 result.appendFormat(
4017 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4018 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004019 }
4020
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004021 bool dumpAll = true;
4022 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004023 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004024
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004025 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004026 if ((index < numArgs) &&
4027 (args[index] == String16("--list"))) {
4028 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004029 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004030 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004031 }
4032
4033 if ((index < numArgs) &&
4034 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004035 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004036 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004037 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004038 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004039
4040 if ((index < numArgs) &&
4041 (args[index] == String16("--latency-clear"))) {
4042 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004043 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004044 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004045 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004046
4047 if ((index < numArgs) &&
4048 (args[index] == String16("--dispsync"))) {
4049 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004050 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004051 dumpAll = false;
4052 }
Dan Stozab90cf072015-03-05 11:05:59 -08004053
4054 if ((index < numArgs) &&
4055 (args[index] == String16("--static-screen"))) {
4056 index++;
4057 dumpStaticScreenStats(result);
4058 dumpAll = false;
4059 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004060
4061 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004062 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004063 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004064 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004065 dumpAll = false;
4066 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004067
4068 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4069 index++;
4070 dumpWideColorInfo(result);
4071 dumpAll = false;
4072 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004073
4074 if ((index < numArgs) &&
4075 (args[index] == String16("--enable-layer-stats"))) {
4076 index++;
4077 mLayerStats.enable();
4078 dumpAll = false;
4079 }
4080
4081 if ((index < numArgs) &&
4082 (args[index] == String16("--disable-layer-stats"))) {
4083 index++;
4084 mLayerStats.disable();
4085 dumpAll = false;
4086 }
4087
4088 if ((index < numArgs) &&
4089 (args[index] == String16("--clear-layer-stats"))) {
4090 index++;
4091 mLayerStats.clear();
4092 dumpAll = false;
4093 }
4094
4095 if ((index < numArgs) &&
4096 (args[index] == String16("--dump-layer-stats"))) {
4097 index++;
4098 mLayerStats.dump(result);
4099 dumpAll = false;
4100 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004101
4102 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004103 (args[index] == String16("--frame-composition"))) {
4104 index++;
4105 dumpFrameCompositionInfo(result);
4106 dumpAll = false;
4107 }
4108
4109 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004110 (args[index] == String16("--display-identification"))) {
4111 index++;
4112 dumpDisplayIdentificationData(result);
4113 dumpAll = false;
4114 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004115
4116 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4117 index++;
4118 mTimeStats.parseArgs(asProto, args, index, result);
4119 dumpAll = false;
4120 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004122
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004123 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004124 if (asProto) {
4125 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4126 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4127 } else {
4128 dumpAllLocked(args, index, result);
4129 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004130 }
4131
Mathias Agopian9795c422009-08-26 16:36:26 -07004132 if (locked) {
4133 mStateLock.unlock();
4134 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135 }
4136 write(fd, result.string(), result.size());
4137 return NO_ERROR;
4138}
4139
Dan Stozac7014012014-02-14 15:03:43 -08004140void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4141 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004142{
Robert Carr2047fae2016-11-28 14:09:09 -08004143 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004144 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004145 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004146}
4147
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004149 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150{
4151 String8 name;
4152 if (index < args.size()) {
4153 name = String8(args[index]);
4154 index++;
4155 }
4156
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157 if (const auto displayId = getInternalDisplayId();
4158 displayId && getHwComposer().isConnected(*displayId)) {
4159 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004160 const nsecs_t period = activeConfig->getVsyncPeriod();
4161 result.appendFormat("%" PRId64 "\n", period);
4162 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004163
4164 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004165 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004166 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004167 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004168 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004169 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004170 }
Robert Carr2047fae2016-11-28 14:09:09 -08004171 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004172 }
4173}
4174
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004175void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004176 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004177{
4178 String8 name;
4179 if (index < args.size()) {
4180 name = String8(args[index]);
4181 index++;
4182 }
4183
Robert Carr2047fae2016-11-28 14:09:09 -08004184 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004185 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004186 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004187 }
Robert Carr2047fae2016-11-28 14:09:09 -08004188 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004189
Svetoslavd85084b2014-03-20 10:28:31 -07004190 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004191}
4192
Jamie Gennis6547ff42013-07-16 20:12:42 -07004193// This should only be called from the main thread. Otherwise it would need
4194// the lock and should use mCurrentState rather than mDrawingState.
4195void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004196 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004197 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004198 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004199
4200 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4201}
4202
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004203void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004204{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004205 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004206
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004207 if (isLayerTripleBufferingDisabled())
4208 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004209
4210 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004211 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004212 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004213 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004214 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4215 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004216 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004217}
4218
Dan Stozab90cf072015-03-05 11:05:59 -08004219void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4220{
4221 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004222 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4223 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004224 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004225 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004226 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4227 b + 1, bucketTimeSec, percent);
4228 }
David Sodman4a36e932017-11-07 14:29:47 -08004229 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004230 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004231 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004232 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004233 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004234}
4235
Dan Stozae77c7662016-05-13 11:37:28 -07004236void SurfaceFlinger::recordBufferingStats(const char* layerName,
4237 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004238 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4239 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004240 for (const auto& segment : history) {
4241 if (!segment.usedThirdBuffer) {
4242 stats.twoBufferTime += segment.totalTime;
4243 }
4244 if (segment.occupancyAverage < 1.0f) {
4245 stats.doubleBufferedTime += segment.totalTime;
4246 } else if (segment.occupancyAverage < 2.0f) {
4247 stats.tripleBufferedTime += segment.totalTime;
4248 }
4249 ++stats.numSegments;
4250 stats.totalTime += segment.totalTime;
4251 }
4252}
4253
Brian Andersond6927fb2016-07-23 23:37:30 -07004254void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4255 result.appendFormat("Layer frame timestamps:\n");
4256
4257 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4258 const size_t count = currentLayers.size();
4259 for (size_t i=0 ; i<count ; i++) {
4260 currentLayers[i]->dumpFrameEvents(result);
4261 }
4262}
4263
Dan Stozae77c7662016-05-13 11:37:28 -07004264void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4265 result.append("Buffering stats:\n");
4266 result.append(" [Layer name] <Active time> <Two buffer> "
4267 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004268 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004269 typedef std::tuple<std::string, float, float, float> BufferTuple;
4270 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004271 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004272 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004273 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004274 if (stats.numSegments == 0) {
4275 continue;
4276 }
4277 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4278 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4279 stats.totalTime;
4280 float doubleBufferRatio = static_cast<float>(
4281 stats.doubleBufferedTime) / stats.totalTime;
4282 float tripleBufferRatio = static_cast<float>(
4283 stats.tripleBufferedTime) / stats.totalTime;
4284 sorted.insert({activeTime, {name, twoBufferRatio,
4285 doubleBufferRatio, tripleBufferRatio}});
4286 }
4287 for (const auto& sortedPair : sorted) {
4288 float activeTime = sortedPair.first;
4289 const BufferTuple& values = sortedPair.second;
4290 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4291 std::get<0>(values).c_str(), activeTime,
4292 std::get<1>(values), std::get<2>(values),
4293 std::get<3>(values));
4294 }
4295 result.append("\n");
4296}
4297
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004298void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004299 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004300 const auto displayId = display->getId();
4301 if (!displayId) {
4302 continue;
4303 }
4304 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004305 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004306 continue;
4307 }
4308
Dominik Laskowski34157762018-10-31 13:07:19 -07004309 result.appendFormat("Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
Dominik Laskowski075d3172018-05-24 15:50:06 -07004310 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004311 uint8_t port;
4312 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004313 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004314 result.append("no identification data\n");
4315 continue;
4316 }
4317
4318 if (!isEdid(data)) {
4319 result.append("unknown identification data: ");
4320 for (uint8_t byte : data) {
4321 result.appendFormat("%x ", byte);
4322 }
4323 result.append("\n");
4324 continue;
4325 }
4326
4327 const auto edid = parseEdid(data);
4328 if (!edid) {
4329 result.append("invalid EDID: ");
4330 for (uint8_t byte : data) {
4331 result.appendFormat("%x ", byte);
4332 }
4333 result.append("\n");
4334 continue;
4335 }
4336
4337 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4338 result.append(edid->displayName.data(), edid->displayName.length());
4339 result.append("\"\n");
4340 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004341}
4342
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004343void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004344 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4345 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004346 result.appendFormat("DisplayColorSetting: %s\n",
4347 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004348
4349 // TODO: print out if wide-color mode is active or not
4350
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004351 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004352 const auto displayId = display->getId();
4353 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004354 continue;
4355 }
4356
Dominik Laskowski34157762018-10-31 13:07:19 -07004357 result.appendFormat("Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004358 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004359 for (auto&& mode : modes) {
4360 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4361 }
4362
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004363 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004364 result.appendFormat(" Current color mode: %s (%d)\n",
4365 decodeColorMode(currentMode).c_str(), currentMode);
4366 }
4367 result.append("\n");
4368}
4369
David Sodman7e4ae112018-02-09 15:02:28 -08004370void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4371 std::string stringResult;
4372
4373 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004374 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4375 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004376 continue;
4377 }
4378
Dominik Laskowski05275f12018-11-01 15:03:24 -07004379 const auto& compositionInfoList = it->second;
4380 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004381 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4382 for (const auto& compositionInfo : compositionInfoList) {
4383 compositionInfo.dump(stringResult, nullptr);
4384 stringResult += base::StringPrintf("\n");
4385 }
4386 }
4387
4388 result.append(stringResult.c_str());
4389}
4390
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004391LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004392 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004393 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4394 const State& state = useDrawing ? mDrawingState : mCurrentState;
4395 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004396 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004397 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004398 });
4399
4400 return layersProto;
4401}
4402
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004403LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004404 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004405
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004406 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004407 resolution->set_w(display.getWidth());
4408 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4411 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4412 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004413
Dominik Laskowski075d3172018-05-24 15:50:06 -07004414 const auto displayId = display.getId();
4415 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004416 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004417 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004419 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004420 }
4421 });
4422
4423 return layersProto;
4424}
4425
Mathias Agopian74d211a2013-04-22 16:55:35 +02004426void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4427 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004428{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004429 bool colorize = false;
4430 if (index < args.size()
4431 && (args[index] == String16("--color"))) {
4432 colorize = true;
4433 index++;
4434 }
4435
4436 Colorizer colorizer(colorize);
4437
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438 // figure out if we're stuck somewhere
4439 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004440 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4442
4443 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004444 * Dump library configuration.
4445 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446
4447 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004448 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004449 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004450 appendSfConfigString(result);
4451 appendUiConfigString(result);
4452 appendGuiConfigString(result);
4453 result.append("\n");
4454
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004455 result.append("\nDisplay identification data:\n");
4456 dumpDisplayIdentificationData(result);
4457
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004458 result.append("\nWide-Color information:\n");
4459 dumpWideColorInfo(result);
4460
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004461 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004462 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004463 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004464 result.append(SyncFeatures::getInstance().toString());
4465 result.append("\n");
4466
Andy McFadden41d67d72014-04-25 16:58:34 -07004467 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004468 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004469 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004470
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004471 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4472 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004473 if (const auto displayId = getInternalDisplayId();
4474 displayId && getHwComposer().isConnected(*displayId)) {
4475 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski34157762018-10-31 13:07:19 -07004476 result.appendFormat("Display %s: app phase %" PRId64 " ns, "
Dominik Laskowski075d3172018-05-24 15:50:06 -07004477 "sf phase %" PRId64 " ns, "
4478 "early app phase %" PRId64 " ns, "
4479 "early sf phase %" PRId64 " ns, "
4480 "early app gl phase %" PRId64 " ns, "
4481 "early sf gl phase %" PRId64 " ns, "
4482 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dominik Laskowski34157762018-10-31 13:07:19 -07004483 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4484 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
Dominik Laskowski075d3172018-05-24 15:50:06 -07004485 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004486 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004487 result.append("\n");
4488
Dan Stozab90cf072015-03-05 11:05:59 -08004489 // Dump static screen stats
4490 result.append("\n");
4491 dumpStaticScreenStats(result);
4492 result.append("\n");
4493
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004494 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4495
Dan Stozae77c7662016-05-13 11:37:28 -07004496 dumpBufferingStats(result);
4497
Andy McFadden4803b742012-09-24 19:07:20 -07004498 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004499 * Dump the visible layer list
4500 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004501 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004502 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004503 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4504 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004505 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004506
Chia-I Wu2f884132018-09-13 15:17:58 -07004507 {
4508 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4509 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4510 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4511 result.append("\n");
4512 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004513
David Sodman7e4ae112018-02-09 15:02:28 -08004514 result.append("\nFrame-Composition information:\n");
4515 dumpFrameCompositionInfo(result);
4516 result.append("\n");
4517
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004518 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004519 * Dump Display state
4520 */
4521
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004522 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004523 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004524 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004525 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004526 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004527 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004528 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004529
4530 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004531 * Dump SurfaceFlinger global state
4532 */
4533
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004534 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004535 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537
David Sodmanbc815282017-11-05 18:57:52 -08004538 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004539
Dominik Laskowski075d3172018-05-24 15:50:06 -07004540 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004541 display->undefinedRegion.dump(result, "undefinedRegion");
4542 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4543 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004544 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004545 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004546 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004547 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004548
Dominik Laskowski075d3172018-05-24 15:50:06 -07004549 if (const auto displayId = getInternalDisplayId();
4550 displayId && getHwComposer().isConnected(*displayId)) {
4551 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004552 result.appendFormat(" refresh-rate : %f fps\n"
4553 " x-dpi : %f\n"
4554 " y-dpi : %f\n",
4555 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4556 activeConfig->getDpiY());
4557 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004558
Mathias Agopian74d211a2013-04-22 16:55:35 +02004559 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561
Ana Krulec98b5b242018-08-10 15:03:23 -07004562 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 /*
4564 * VSYNC state
4565 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004566 if (mUseScheduler) {
4567 mScheduler->dump(mAppConnectionHandle, result);
4568 } else {
4569 mEventThread->dump(result);
4570 }
Dan Stozae22aec72016-08-01 13:20:59 -07004571 result.append("\n");
4572
4573 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004574 * Tracing state
4575 */
4576 mTracing.dump(result);
4577 result.append("\n");
4578
4579 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004580 * HWC layer minidump
4581 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004582 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004583 const auto displayId = display->getId();
4584 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004585 continue;
4586 }
4587
Dominik Laskowski34157762018-10-31 13:07:19 -07004588 result.appendFormat("Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004589 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004590 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004591 result.append("\n");
4592 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004593
4594 /*
4595 * Dump HWComposer state
4596 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004597 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004598 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004599 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004600 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004601 result.appendFormat(" h/w composer %s\n",
4602 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004603 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604
4605 /*
4606 * Dump gralloc state
4607 */
4608 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4609 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004610
4611 /*
4612 * Dump VrFlinger state if in use.
4613 */
4614 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4615 result.append("VrFlinger state:\n");
4616 result.append(mVrFlinger->Dump().c_str());
4617 result.append("\n");
4618 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004619}
4620
Dominik Laskowski075d3172018-05-24 15:50:06 -07004621const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004622 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004623 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004624 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004625 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004626 }
4627 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004628
Dominik Laskowski34157762018-10-31 13:07:19 -07004629 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004630 static const Vector<sp<Layer>> empty;
4631 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004632}
4633
Keun young Park63f165f2012-08-31 10:53:36 -07004634bool SurfaceFlinger::startDdmConnection()
4635{
4636 void* libddmconnection_dso =
4637 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4638 if (!libddmconnection_dso) {
4639 return false;
4640 }
4641 void (*DdmConnection_start)(const char* name);
4642 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004643 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004644 if (!DdmConnection_start) {
4645 dlclose(libddmconnection_dso);
4646 return false;
4647 }
4648 (*DdmConnection_start)(getServiceName());
4649 return true;
4650}
4651
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652void SurfaceFlinger::updateColorMatrixLocked() {
4653 mat4 colorMatrix;
4654 if (mGlobalSaturationFactor != 1.0f) {
4655 // Rec.709 luma coefficients
4656 float3 luminance{0.213f, 0.715f, 0.072f};
4657 luminance *= 1.0f - mGlobalSaturationFactor;
4658 mat4 saturationMatrix = mat4(
4659 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4660 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4661 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4662 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4663 );
4664 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4665 } else {
4666 colorMatrix = mClientColorMatrix * mDaltonizer();
4667 }
4668
4669 if (mCurrentState.colorMatrix != colorMatrix) {
4670 mCurrentState.colorMatrix = colorMatrix;
4671 mCurrentState.colorMatrixChanged = true;
4672 setTransactionFlags(eTransactionNeeded);
4673 }
4674}
4675
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004676status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004677#pragma clang diagnostic push
4678#pragma clang diagnostic error "-Wswitch-enum"
4679 switch (static_cast<ISurfaceComposerTag>(code)) {
4680 // These methods should at minimum make sure that the client requested
4681 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004682 case BOOT_FINISHED:
4683 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004684 case CREATE_CONNECTION:
4685 case CREATE_DISPLAY:
4686 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004687 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004688 case GET_ACTIVE_COLOR_MODE:
4689 case GET_ANIMATION_FRAME_STATS:
4690 case GET_HDR_CAPABILITIES:
4691 case SET_ACTIVE_CONFIG:
4692 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004693 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004695 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4696 IPCThreadState* ipc = IPCThreadState::self();
4697 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4698 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004699 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004700 }
Robert Carr1db73f62016-12-21 12:58:51 -08004701 return OK;
4702 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004703 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004704 IPCThreadState* ipc = IPCThreadState::self();
4705 const int pid = ipc->getCallingPid();
4706 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004707 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4708 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004709 return PERMISSION_DENIED;
4710 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004711 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004712 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004713 // Used by apps to hook Choreographer to SurfaceFlinger.
4714 case CREATE_DISPLAY_EVENT_CONNECTION:
4715 // The following calls are currently used by clients that do not
4716 // request necessary permissions. However, they do not expose any secret
4717 // information, so it is OK to pass them.
4718 case AUTHENTICATE_SURFACE:
4719 case GET_ACTIVE_CONFIG:
4720 case GET_BUILT_IN_DISPLAY:
4721 case GET_DISPLAY_COLOR_MODES:
4722 case GET_DISPLAY_CONFIGS:
4723 case GET_DISPLAY_STATS:
4724 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4725 // Calling setTransactionState is safe, because you need to have been
4726 // granted a reference to Client* and Handle* to do anything with it.
4727 case SET_TRANSACTION_STATE:
4728 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004729 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004730 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004731 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 return OK;
4733 }
4734 case CAPTURE_LAYERS:
4735 case CAPTURE_SCREEN: {
4736 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004737 IPCThreadState* ipc = IPCThreadState::self();
4738 const int pid = ipc->getCallingPid();
4739 const int uid = ipc->getCallingUid();
4740 if ((uid != AID_GRAPHICS) &&
4741 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4742 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4743 return PERMISSION_DENIED;
4744 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745 return OK;
4746 }
4747 // The following codes are deprecated and should never be allowed to access SF.
4748 case CONNECT_DISPLAY_UNUSED:
4749 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4750 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4751 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004753 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004754
4755 // These codes are used for the IBinder protocol to either interrogate the recipient
4756 // side of the transaction for its canonical interface descriptor or to dump its state.
4757 // We let them pass by default.
4758 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4759 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4760 code == IBinder::SYSPROPS_TRANSACTION) {
4761 return OK;
4762 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004763 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004765 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4767 return OK;
4768 }
4769 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4770 return PERMISSION_DENIED;
4771#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004772}
4773
Ana Krulec13be8ad2018-08-21 02:43:56 +00004774status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4775 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004776 status_t credentialCheck = CheckTransactCodeCredentials(code);
4777 if (credentialCheck != OK) {
4778 return credentialCheck;
4779 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4782 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004783 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004784 IPCThreadState* ipc = IPCThreadState::self();
4785 const int uid = ipc->getCallingUid();
4786 if (CC_UNLIKELY(uid != AID_SYSTEM
4787 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004788 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004789 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004790 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004791 return PERMISSION_DENIED;
4792 }
4793 int n;
4794 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004795 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004796 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004797 return NO_ERROR;
4798 case 1002: // SHOW_UPDATES
4799 n = data.readInt32();
4800 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004801 invalidateHwcGeometry();
4802 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004803 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004804 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004805 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004806 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004807 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004808 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004809 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004810 setTransactionFlags(
4811 eTransactionNeeded|
4812 eDisplayTransactionNeeded|
4813 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004814 return NO_ERROR;
4815 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004816 case 1006:{ // send empty update
4817 signalRefresh();
4818 return NO_ERROR;
4819 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004820 case 1008: // toggle use of hw composer
4821 n = data.readInt32();
4822 mDebugDisableHWC = n ? 1 : 0;
4823 invalidateHwcGeometry();
4824 repaintEverything();
4825 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004826 case 1009: // toggle use of transform hint
4827 n = data.readInt32();
4828 mDebugDisableTransformHint = n ? 1 : 0;
4829 invalidateHwcGeometry();
4830 repaintEverything();
4831 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004832 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004833 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004834 reply->writeInt32(0);
4835 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004836 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004837 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 return NO_ERROR;
4839 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004840 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004841 if (!display) {
4842 return NAME_NOT_FOUND;
4843 }
4844
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004845 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004846 return NO_ERROR;
4847 }
4848 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004849 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004850 // daltonize
4851 n = data.readInt32();
4852 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004853 case 1:
4854 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4855 break;
4856 case 2:
4857 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4858 break;
4859 case 3:
4860 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4861 break;
4862 default:
4863 mDaltonizer.setType(ColorBlindnessType::None);
4864 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004865 }
4866 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004867 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004868 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004869 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004870 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004871
4872 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004873 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004874 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004875 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004876 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 // apply a color matrix
4878 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004879 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004880 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004881 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004882 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004883 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004884 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004885 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004886 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004887 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004888 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004889
4890 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4891 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004893 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4894 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4895 }
4896
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004898 return NO_ERROR;
4899 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004900 // This is an experimental interface
4901 // Needs to be shifted to proper binder interface when we productize
4902 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004903 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004904 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004905 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004906 return NO_ERROR;
4907 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004908 case 1017: {
4909 n = data.readInt32();
4910 mForceFullDamage = static_cast<bool>(n);
4911 return NO_ERROR;
4912 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004913 case 1018: { // Modify Choreographer's phase offset
4914 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004915 if (mUseScheduler) {
4916 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4917 } else {
4918 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4919 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004920 return NO_ERROR;
4921 }
4922 case 1019: { // Modify SurfaceFlinger's phase offset
4923 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004924 if (mUseScheduler) {
4925 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4926 } else {
4927 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4928 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004929 return NO_ERROR;
4930 }
Irvel468051e2016-06-13 16:44:44 -07004931 case 1020: { // Layer updates interceptor
4932 n = data.readInt32();
4933 if (n) {
4934 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004935 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004936 }
4937 else{
4938 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004939 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004940 }
4941 return NO_ERROR;
4942 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004943 case 1021: { // Disable HWC virtual displays
4944 n = data.readInt32();
4945 mUseHwcVirtualDisplays = !n;
4946 return NO_ERROR;
4947 }
Romain Guy0147a172017-06-01 13:53:56 -07004948 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004949 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004950 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004951
Chia-I Wu28f320b2018-05-03 11:02:56 -07004952 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004953 return NO_ERROR;
4954 }
Romain Guy54f154a2017-10-24 21:40:32 +01004955 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004956 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004957 invalidateHwcGeometry();
4958 repaintEverything();
4959 return NO_ERROR;
4960 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004961 // Deprecate, use 1030 to check whether the device is color managed.
4962 case 1024: {
4963 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004964 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004965 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004966 n = data.readInt32();
4967 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004968 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004969 mTracing.enable();
4970 doTracing("tracing.enable");
4971 reply->writeInt32(NO_ERROR);
4972 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004973 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004974 status_t err = mTracing.disable();
4975 reply->writeInt32(err);
4976 }
4977 return NO_ERROR;
4978 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004979 case 1026: { // Get layer tracing status
4980 reply->writeBool(mTracing.isEnabled());
4981 return NO_ERROR;
4982 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004983 // Is a DisplayColorSetting supported?
4984 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004985 const auto display = getDefaultDisplayDevice();
4986 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004987 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004988 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004989
4990 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4991 switch (setting) {
4992 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004993 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004994 break;
4995 case DisplayColorSetting::UNMANAGED:
4996 reply->writeBool(true);
4997 break;
4998 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004999 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005000 break;
5001 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005002 reply->writeBool(
5003 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005004 break;
5005 }
5006 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005007 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005008 // Is VrFlinger active?
5009 case 1028: {
5010 Mutex::Autolock _l(mStateLock);
5011 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5012 return NO_ERROR;
5013 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005014 // Is device color managed?
5015 case 1030: {
5016 reply->writeBool(useColorManagement);
5017 return NO_ERROR;
5018 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005019 // Override default composition data space
5020 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5021 // && adb shell stop zygote && adb shell start zygote
5022 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5023 // adb shell stop zygote && adb shell start zygote
5024 case 1031: {
5025 Mutex::Autolock _l(mStateLock);
5026 n = data.readInt32();
5027 if (n) {
5028 n = data.readInt32();
5029 if (n) {
5030 Dataspace dataspace = static_cast<Dataspace>(n);
5031 if (!validateCompositionDataspace(dataspace)) {
5032 return BAD_VALUE;
5033 }
5034 mDefaultCompositionDataspace = dataspace;
5035 }
5036 n = data.readInt32();
5037 if (n) {
5038 Dataspace dataspace = static_cast<Dataspace>(n);
5039 if (!validateCompositionDataspace(dataspace)) {
5040 return BAD_VALUE;
5041 }
5042 mWideColorGamutCompositionDataspace = dataspace;
5043 }
5044 } else {
5045 // restore composition data space.
5046 mDefaultCompositionDataspace = defaultCompositionDataspace;
5047 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5048 }
5049 return NO_ERROR;
5050 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 }
5052 }
5053 return err;
5054}
5055
Steven Thomas6d8110b2017-08-31 18:24:21 -07005056void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005057 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005058 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005059}
5060
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005061// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5062class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005063public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005064 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5065 ~WindowDisconnector() {
5066 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005067 }
5068
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005069private:
5070 ANativeWindow* mWindow;
5071 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005072};
5073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005074status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005075 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5076 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005077 uint32_t reqWidth, uint32_t reqHeight,
5078 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005079 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005080 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005082 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005083
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005084 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5085
Chia-I Wu20261cb2018-08-23 12:55:44 -07005086 sp<DisplayDevice> display;
5087 {
5088 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005089
Chia-I Wu20261cb2018-08-23 12:55:44 -07005090 display = getDisplayDeviceLocked(displayToken);
5091 if (!display) return BAD_VALUE;
5092
Chia-I Wucb023152018-08-28 12:57:23 -07005093 // set the requested width/height to the logical display viewport size
5094 // by default
5095 if (reqWidth == 0 || reqHeight == 0) {
5096 reqWidth = uint32_t(display->getViewport().width());
5097 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005098 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005099 }
5100
Peiyong Lin0e003c92018-09-17 11:09:51 -07005101 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5102 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005103
5104 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005105 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005106 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5107 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005108}
5109
5110status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005111 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5112 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005113 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005114 ATRACE_CALL();
5115
5116 class LayerRenderArea : public RenderArea {
5117 public:
Robert Carr578038f2018-03-09 12:25:24 -08005118 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005119 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5120 bool childrenOnly)
5121 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005122 mLayer(layer),
5123 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005124 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005125 mFlinger(flinger),
5126 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005127 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005128 Rect getBounds() const override {
5129 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005130 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005131 }
Marissa Wall61c58622018-07-18 10:12:20 -07005132 int getHeight() const override {
5133 return mLayer->getActiveHeight(mLayer->getDrawingState());
5134 }
5135 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005136 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005137 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005138 Rect getSourceCrop() const override {
5139 if (mCrop.isEmpty()) {
5140 return getBounds();
5141 } else {
5142 return mCrop;
5143 }
5144 }
Robert Carr578038f2018-03-09 12:25:24 -08005145 class ReparentForDrawing {
5146 public:
5147 const sp<Layer>& oldParent;
5148 const sp<Layer>& newParent;
5149
5150 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5151 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005152 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005153 }
Robert Carr15eae092018-03-23 13:43:53 -07005154 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005155 };
5156
5157 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005158 const Rect sourceCrop = getSourceCrop();
5159 // no need to check rotation because there is none
5160 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5161 sourceCrop.height() != getReqHeight();
5162
Robert Carr578038f2018-03-09 12:25:24 -08005163 if (!mChildrenOnly) {
5164 mTransform = mLayer->getTransform().inverse();
5165 drawLayers();
5166 } else {
5167 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005168 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005169 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5170 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005171
5172 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5173 drawLayers();
5174 }
5175 }
chaviwa76b2712017-09-20 12:02:26 -07005176
chaviwa76b2712017-09-20 12:02:26 -07005177 private:
chaviw7206d492017-11-10 16:16:12 -08005178 const sp<Layer> mLayer;
5179 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005180
5181 // In the "childrenOnly" case we reparent the children to a screenshot
5182 // layer which has no properties set and which does not draw.
5183 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005184 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005185 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005186
5187 SurfaceFlinger* mFlinger;
5188 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005189 };
5190
5191 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5192 auto parent = layerHandle->owner.promote();
5193
Robert Carr2e102c92018-10-23 12:11:15 -07005194 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005195 ALOGE("captureLayers called with a removed parent");
5196 return NAME_NOT_FOUND;
5197 }
5198
Robert Carr578038f2018-03-09 12:25:24 -08005199 const int uid = IPCThreadState::self()->getCallingUid();
5200 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5201 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5202 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5203 return PERMISSION_DENIED;
5204 }
5205
chaviw7206d492017-11-10 16:16:12 -08005206 Rect crop(sourceCrop);
5207 if (sourceCrop.width() <= 0) {
5208 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005209 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005210 }
5211
5212 if (sourceCrop.height() <= 0) {
5213 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005214 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005215 }
5216
5217 int32_t reqWidth = crop.width() * frameScale;
5218 int32_t reqHeight = crop.height() * frameScale;
5219
Chia-I Wu20261cb2018-08-23 12:55:44 -07005220 // really small crop or frameScale
5221 if (reqWidth <= 0) {
5222 reqWidth = 1;
5223 }
5224 if (reqHeight <= 0) {
5225 reqHeight = 1;
5226 }
5227
Peiyong Lin0e003c92018-09-17 11:09:51 -07005228 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005229
Robert Carr578038f2018-03-09 12:25:24 -08005230 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005231 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5232 if (!layer->isVisible()) {
5233 return;
Robert Carr578038f2018-03-09 12:25:24 -08005234 } else if (childrenOnly && layer == parent.get()) {
5235 return;
chaviwa76b2712017-09-20 12:02:26 -07005236 }
5237 visitor(layer);
5238 });
5239 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005240 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005241}
5242
5243status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5244 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005245 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005246 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005247 bool useIdentityTransform) {
5248 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005249
Peiyong Lin0e003c92018-09-17 11:09:51 -07005250 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005251 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5252 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005253 *outBuffer =
5254 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5255 static_cast<android_pixel_format>(reqPixelFormat), 1,
5256 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005257
5258 // This mutex protects syncFd and captureResult for communication of the return values from the
5259 // main thread back to this Binder thread
5260 std::mutex captureMutex;
5261 std::condition_variable captureCondition;
5262 std::unique_lock<std::mutex> captureLock(captureMutex);
5263 int syncFd = -1;
5264 std::optional<status_t> captureResult;
5265
Robert Carr03480e22018-01-04 16:02:06 -08005266 const int uid = IPCThreadState::self()->getCallingUid();
5267 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5268
Dominik Laskowski8c001672018-05-30 16:52:06 -07005269 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005270 // If there is a refresh pending, bug out early and tell the binder thread to try again
5271 // after the refresh.
5272 if (mRefreshPending) {
5273 ATRACE_NAME("Skipping screenshot for now");
5274 std::unique_lock<std::mutex> captureLock(captureMutex);
5275 captureResult = std::make_optional<status_t>(EAGAIN);
5276 captureCondition.notify_one();
5277 return;
5278 }
5279
5280 status_t result = NO_ERROR;
5281 int fd = -1;
5282 {
5283 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005284 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005285 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5286 useIdentityTransform, forSystem, &fd);
5287 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 }
5289
5290 {
5291 std::unique_lock<std::mutex> captureLock(captureMutex);
5292 syncFd = fd;
5293 captureResult = std::make_optional<status_t>(result);
5294 captureCondition.notify_one();
5295 }
5296 });
5297
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005298 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005299 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005300 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005301 while (*captureResult == EAGAIN) {
5302 captureResult.reset();
5303 result = postMessageAsync(message);
5304 if (result != NO_ERROR) {
5305 return result;
5306 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005307 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005308 }
5309 result = *captureResult;
5310 }
5311
5312 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005313 sync_wait(syncFd, -1);
5314 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005315 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005316
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005317 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005318}
5319
chaviwa76b2712017-09-20 12:02:26 -07005320void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005321 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005322 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005323 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005324
Lloyd Pique144e1162017-12-20 16:44:52 -08005325 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005326
chaviwa76b2712017-09-20 12:02:26 -07005327 const auto reqWidth = renderArea.getReqWidth();
5328 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005329 const auto sourceCrop = renderArea.getSourceCrop();
5330 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005331
Peiyong Lin0e003c92018-09-17 11:09:51 -07005332 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005333 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005334
Mathias Agopian180f10d2013-04-10 22:55:41 -07005335 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005336 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005337
5338 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005339 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005340 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005341
chaviw50da5042018-04-09 13:49:37 -07005342 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005343 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005344 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005345
chaviwa76b2712017-09-20 12:02:26 -07005346 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005347 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005348 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005349 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005350 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005351}
5352
chaviwa76b2712017-09-20 12:02:26 -07005353status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5354 TraverseLayersFunction traverseLayers,
5355 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005356 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005357 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005358 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005359 ATRACE_CALL();
5360
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005361 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005362
5363 traverseLayers([&](Layer* layer) {
5364 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5365 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005366
Robert Carr03480e22018-01-04 16:02:06 -08005367 // We allow the system server to take screenshots of secure layers for
5368 // use in situations like the Screen-rotation animation and place
5369 // the impetus on WindowManager to not persist them.
5370 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005371 ALOGW("FB is protected: PERMISSION_DENIED");
5372 return PERMISSION_DENIED;
5373 }
5374
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005375 // this binds the given EGLImage as a framebuffer for the
5376 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005377 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005378 if (bufferBond.getStatus() != NO_ERROR) {
5379 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005380 return INVALID_OPERATION;
5381 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005382
Dan Stozaabcda352017-06-01 14:37:39 -07005383 // this will in fact render into our dequeued buffer
5384 // via an FBO, which means we didn't have to create
5385 // an EGLSurface and therefore we're not
5386 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005387 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005388
Alec Mouri492bc572018-09-11 21:40:04 +00005389 base::unique_fd syncFd = getRenderEngine().flush();
5390 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005391 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005392 }
Alec Mouri492bc572018-09-11 21:40:04 +00005393 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005394
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005395 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005396}
5397
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005398// ---------------------------------------------------------------------------
5399
Dan Stoza412903f2017-04-27 13:42:17 -07005400void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5401 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005402}
5403
Dan Stoza412903f2017-04-27 13:42:17 -07005404void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5405 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005406}
5407
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005408void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005409 const LayerVector::Visitor& visitor) {
5410 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005411 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005412 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005413 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005414 continue;
5415 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005416 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005417 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005418 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005419 return;
5420 }
chaviwa76b2712017-09-20 12:02:26 -07005421 if (!layer->isVisible()) {
5422 return;
5423 }
5424 visitor(layer);
5425 });
5426 }
5427}
5428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005429}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005430
Lloyd Pique074e8122018-07-26 12:57:23 -07005431
Mathias Agopian3f844832013-08-07 21:24:32 -07005432#if defined(__gl_h_)
5433#error "don't include gl/gl.h in this file"
5434#endif
5435
5436#if defined(__gl2_h_)
5437#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005438#endif