blob: 9d1695814db511611e298d75f3295d1358c82821 [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
Lloyd Piquefcd86612017-12-14 17:15:36 -0800679 // make the default display GLContext current so that we can create textures
680 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800682
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
1046 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%" PRIu64,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski075d3172018-05-24 15:50:06 -07001048 renderIntent, *displayId);
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;
1258 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001259 // Hardware vsync is not currently available, so abort the resync
1260 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261 return;
1262 }
1263
Dominik Laskowski075d3172018-05-24 15:50:06 -07001264 const auto displayId = getInternalDisplayId();
1265 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001266 return;
1267 }
1268
Dominik Laskowski075d3172018-05-24 15:50:06 -07001269 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271
Ana Krulece588e312018-09-18 12:32:24 -07001272 if (mUseScheduler) {
1273 mScheduler->setVsyncPeriod(period);
1274 } else {
1275 mPrimaryDispSync->reset();
1276 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
Ana Krulece588e312018-09-18 12:32:24 -07001278 if (!mPrimaryHWVsyncEnabled) {
1279 mPrimaryDispSync->beginResync();
1280 mEventControlThread->setVsyncEnabled(true);
1281 mPrimaryHWVsyncEnabled = true;
1282 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 }
1284}
1285
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 Mutex::Autolock _l(mHWVsyncLock);
1288 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001290 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 mPrimaryHWVsyncEnabled = false;
1292 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001293 if (makeUnavailable) {
1294 mHWVsyncAvailable = false;
1295 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296}
1297
Tim Murray4a4e4a22016-04-19 16:29:23 +00001298void SurfaceFlinger::resyncWithRateLimit() {
1299 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001300
1301 // No explicit locking is needed here since EventThread holds a lock while calling this method
1302 static nsecs_t sLastResyncAttempted = 0;
1303 const nsecs_t now = systemTime();
1304 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001305 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306 }
Dan Stoza57164302017-05-08 14:03:54 -07001307 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001308}
1309
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001310void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1311 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001312 ATRACE_NAME("SF onVsync");
1313
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001316 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 return;
1318 }
1319
Dominik Laskowski075d3172018-05-24 15:50:06 -07001320 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001321 return;
1322 }
1323
Dominik Laskowski075d3172018-05-24 15:50:06 -07001324 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001325 // For now, we don't do anything with external display vsyncs.
1326 return;
1327 }
1328
Ana Krulece588e312018-09-18 12:32:24 -07001329 if (mUseScheduler) {
1330 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001332 bool needsHwVsync = false;
1333 { // Scope for the lock
1334 Mutex::Autolock _l(mHWVsyncLock);
1335 if (mPrimaryHWVsyncEnabled) {
1336 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1337 }
1338 }
1339
1340 if (needsHwVsync) {
1341 enableHardwareVsync();
1342 } else {
1343 disableHardwareVsync(false);
1344 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001345 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001346}
1347
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001348void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001349 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1350 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001351}
1352
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001353void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001354 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001355 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001356 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357
Lloyd Piqueba04e622017-12-14 17:11:26 -08001358 // Ignore events that do not have the right sequenceId.
1359 if (sequenceId != getBE().mComposerSequenceId) {
1360 return;
1361 }
1362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 // Only lock if we're not on the main thread. This function is normally
1364 // called on a hwbinder thread, but for the primary display it's called on
1365 // the main thread with the state lock already held, so don't attempt to
1366 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001367 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001368
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001369 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001370
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001371 if (std::this_thread::get_id() == mMainThreadId) {
1372 // Process all pending hot plug events immediately if we are on the main thread.
1373 processDisplayHotplugEventsLocked();
1374 }
1375
Lloyd Piqueba04e622017-12-14 17:11:26 -08001376 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001377}
1378
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001379void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001381 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001383 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001384 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001385}
1386
Dominik Laskowski075d3172018-05-24 15:50:06 -07001387void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001388 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001390 if (const auto displayId = getInternalDisplayId()) {
1391 getHwComposer().setVsyncEnabled(*displayId,
1392 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1393 }
Mathias Agopian86303202012-07-24 22:46:10 -07001394}
1395
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001396// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001397void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001398 if (mUseScheduler) {
1399 mScheduler->disableHardwareVsync(true);
1400 } else {
1401 disableHardwareVsync(true);
1402 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 // Clear the drawing state so that the logic inside of
1404 // handleTransactionLocked will fire. It will determine the delta between
1405 // mCurrentState and mDrawingState and re-apply all changes when we make the
1406 // transition.
1407 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001408 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 mDisplays.clear();
1410}
1411
Steven Thomas050b2c82017-03-06 11:45:16 -08001412void SurfaceFlinger::updateVrFlinger() {
1413 if (!mVrFlinger)
1414 return;
1415 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001416 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001417 return;
1418 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 ALOGE("Vr flinger is only supported for remote hardware composer"
1422 " service connections. Ignoring request to transition to vr"
1423 " flinger.");
1424 mVrFlingerRequestsDisplay = false;
1425 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001426 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Steven Thomas0123ac62018-07-12 11:32:34 -07001430 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001431 LOG_ALWAYS_FATAL_IF(!display);
1432 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001433 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1434 // called below. Clear the reference now so we don't accidentally use it
1435 // later.
1436 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001443 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001444 getBE().mHwc = getFactory().createHWComposer(
1445 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001446 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447
David Sodman105b7dc2017-11-04 20:28:14 -07001448 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1449 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001450
1451 if (vrFlingerRequestsDisplay) {
1452 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001453 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454
1455 mVisibleRegionsDirty = true;
1456 invalidateHwcGeometry();
1457
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001458 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001459 display = getDefaultDisplayDeviceLocked();
1460 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001461 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001464 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 const nsecs_t period = activeConfig->getVsyncPeriod();
1466 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001467
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001468 // The present fences returned from vr_hwc are not an accurate
1469 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001470 if (mUseScheduler) {
1471 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1472 } else {
1473 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1474 !hasSyncFramework);
1475 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001476
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 // Use phase of 0 since phase is not known.
1478 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001479 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1480 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001481
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001482 resyncToHardwareVsync(false);
1483
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001484 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001486}
1487
Mathias Agopian4fec8732012-06-29 14:12:52 -07001488void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001489 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001490 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001492 bool frameMissed = !mHadClientComposition &&
1493 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001494 (mPreviousPresentFence->getSignalTime() ==
1495 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001496 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001497 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001498 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001499 mTimeStats.incrementMissedFrames();
1500 if (mPropagateBackpressure) {
1501 signalLayerUpdate();
1502 break;
1503 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001504 }
Dan Stoza50182882016-07-08 12:02:20 -07001505
Steven Thomas050b2c82017-03-06 11:45:16 -08001506 // Now that we're going to make it to the handleMessageTransaction()
1507 // call below it's safe to call updateVrFlinger(), which will
1508 // potentially trigger a display handoff.
1509 updateVrFlinger();
1510
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 bool refreshNeeded = handleMessageTransaction();
1512 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001513 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001514 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001515 // Signal a refresh if a transaction modified the window state,
1516 // a new buffer was latched, or if HWC has requested a full
1517 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 signalRefresh();
1519 }
1520 break;
1521 }
1522 case MessageQueue::REFRESH: {
1523 handleMessageRefresh();
1524 break;
1525 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526 }
1527}
1528
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001530 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001532 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001533 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001535 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001536}
1537
Mathias Agopian4fec8732012-06-29 14:12:52 -07001538void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001540
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001541 mRefreshPending = false;
1542
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001543 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001544 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001545 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001546 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001547 for (const auto& [token, display] : mDisplays) {
1548 beginFrame(display);
1549 prepareFrame(display);
1550 doDebugFlashRegions(display, repaintEverything);
1551 doComposition(display, repaintEverything);
1552 }
1553
Adrian Roos1e1a1282017-11-01 19:05:31 +01001554 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001555 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001556
1557 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001558 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001559
Dan Stozabfbffeb2016-07-21 14:49:33 -07001560 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001561 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001562 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001563 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001564 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001565
Alec Mouri86770e52018-09-24 22:40:58 +00001566 // Setup RenderEngine sync fences if native sync is supported.
1567 if (getBE().mRenderEngine->useNativeFenceSync()) {
1568 if (mHadClientComposition) {
1569 base::unique_fd flushFence(getRenderEngine().flush());
1570 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1571 getBE().flushFence = new Fence(std::move(flushFence));
1572 } else {
1573 // Cleanup for hygiene.
1574 getBE().flushFence = Fence::NO_FENCE;
1575 }
1576 }
1577
Jorim Jaggi90535212018-05-23 23:44:06 +02001578 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001579
David Sodman7e4ae112018-02-09 15:02:28 -08001580 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001581 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001582 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001583 compositionInfo.hwc.hwcLayer = nullptr;
1584 }
David Sodmanba340492018-08-05 21:51:33 -07001585 }
David Sodman7e4ae112018-02-09 15:02:28 -08001586
1587 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001589
David Sodmanfa9b2af2017-12-24 13:28:59 -08001590
1591bool SurfaceFlinger::handleMessageInvalidate() {
1592 ATRACE_CALL();
1593 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001594}
1595
David Sodman79bba0e2018-08-05 18:07:49 -07001596void SurfaceFlinger::calculateWorkingSet() {
1597 ATRACE_CALL();
1598 ALOGV(__FUNCTION__);
1599
David Sodman79bba0e2018-08-05 18:07:49 -07001600 // build the h/w work list
1601 if (CC_UNLIKELY(mGeometryInvalid)) {
1602 mGeometryInvalid = false;
1603 for (const auto& [token, display] : mDisplays) {
1604 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001605 if (!displayId) {
1606 continue;
1607 }
David Sodman79bba0e2018-08-05 18:07:49 -07001608
Dominik Laskowski075d3172018-05-24 15:50:06 -07001609 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1610 for (size_t i = 0; i < currentLayers.size(); i++) {
1611 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001612
Dominik Laskowski075d3172018-05-24 15:50:06 -07001613 if (!layer->hasHwcLayer(*displayId)) {
1614 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1615 layer->forceClientComposition(*displayId);
1616 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001617 }
1618 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001619
1620 layer->setGeometry(display, i);
1621 if (mDebugDisableHWC || mDebugRegion) {
1622 layer->forceClientComposition(*displayId);
1623 }
David Sodman79bba0e2018-08-05 18:07:49 -07001624 }
1625 }
1626 }
1627
1628 // Set the per-frame data
1629 for (const auto& [token, display] : mDisplays) {
1630 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001631 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001632 continue;
1633 }
1634
1635 if (mDrawingState.colorMatrixChanged) {
1636 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001637 status_t result =
1638 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
1639 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %" PRIu64 ": %d",
1640 *displayId, result);
David Sodman79bba0e2018-08-05 18:07:49 -07001641 }
1642 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1643 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001644 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001645 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1646 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1647 !display->hasHDR10Support()) {
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_HLG ||
1650 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1651 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001652 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001653 }
1654
Peiyong Lind3788632018-09-18 16:01:31 -07001655 // TODO(b/111562338) remove when composer 2.3 is shipped.
1656 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001657 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001658 }
1659
Dominik Laskowski075d3172018-05-24 15:50:06 -07001660 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001661 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001662 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001663 continue;
1664 }
1665
Dominik Laskowski075d3172018-05-24 15:50:06 -07001666 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1667 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001668 }
1669
Peiyong Lin13effd12018-07-24 17:01:47 -07001670 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001671 ColorMode colorMode;
1672 Dataspace dataSpace;
1673 RenderIntent renderIntent;
1674 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1675 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1676 }
1677 }
1678
1679 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001680
1681 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001682 getBE().mCompositionInfo[token].clear();
1683
David Sodmanba340492018-08-05 21:51:33 -07001684 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001685 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001686 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001687
1688 if (displayId) {
1689 if (!layer->setHwcLayer(*displayId)) {
1690 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1691 }
1692 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001693 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001694
Dominik Laskowski05275f12018-11-01 15:03:24 -07001695 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001696 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1697 }
1698 }
David Sodman79bba0e2018-08-05 18:07:49 -07001699}
1700
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702{
1703 // is debugging enabled
1704 if (CC_LIKELY(!mDebugRegion))
1705 return;
1706
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707 if (display->isPoweredOn()) {
1708 // transform the dirty region into this screen's coordinate space
1709 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1710 if (!dirtyRegion.isEmpty()) {
1711 // redraw the whole screen
1712 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713
David Sodmanfa9b2af2017-12-24 13:28:59 -08001714 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001715 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001716 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001717
David Sodmanfa9b2af2017-12-24 13:28:59 -08001718 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719 }
1720 }
1721
David Sodmanfa9b2af2017-12-24 13:28:59 -08001722 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001723
1724 if (mDebugRegion > 1) {
1725 usleep(mDebugRegion * 1000);
1726 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001727
Dominik Laskowski05275f12018-11-01 15:03:24 -07001728 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001729}
1730
Adrian Roos1e1a1282017-11-01 19:05:31 +01001731void SurfaceFlinger::doTracing(const char* where) {
1732 ATRACE_CALL();
1733 ATRACE_NAME(where);
1734 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001735 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001736 }
1737}
1738
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001739void SurfaceFlinger::logLayerStats() {
1740 ATRACE_CALL();
1741 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001742 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001743 if (display->isPrimary()) {
1744 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001745 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001746 }
1747 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001748
1749 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001750 }
1751}
1752
David Sodman2b406362017-12-15 13:33:47 -08001753void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001755 ATRACE_CALL();
1756 ALOGV("preComposition");
1757
David Sodman2b406362017-12-15 13:33:47 -08001758 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1759
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001761 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001762 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763 needExtraInvalidate = true;
1764 }
Robert Carr2047fae2016-11-28 14:09:09 -08001765 });
1766
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767 if (needExtraInvalidate) {
1768 signalLayerUpdate();
1769 }
1770}
1771
Ana Krulece588e312018-09-18 12:32:24 -07001772void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1773 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 // Update queue of past composite+present times and determine the
1775 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001776 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001777 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001778 while (!getBE().mCompositePresentTimes.empty()) {
1779 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780 // Cached values should have been updated before calling this method,
1781 // which helps avoid duplicate syscalls.
1782 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1783 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1784 break;
1785 }
1786 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001787 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788 }
1789
1790 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001791 while (getBE().mCompositePresentTimes.size() > 16) {
1792 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001793 }
1794
Ana Krulece588e312018-09-18 12:32:24 -07001795 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001796}
1797
Ana Krulece588e312018-09-18 12:32:24 -07001798void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1799 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001800 // Integer division and modulo round toward 0 not -inf, so we need to
1801 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001802 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1803 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1804 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001805
Brian Andersond0010582017-03-07 13:20:31 -08001806 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1807 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001808 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001809 }
1810
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001811 // Snap the latency to a value that removes scheduling jitter from the
1812 // composition and present times, which often have >1ms of jitter.
1813 // Reducing jitter is important if an app attempts to extrapolate
1814 // something (such as user input) to an accurate diasplay time.
1815 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1816 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001817 nsecs_t bias = stats.vsyncPeriod / 2;
1818 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1819 nsecs_t snappedCompositeToPresentLatency =
1820 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821
David Sodman99974d22017-11-28 12:04:33 -08001822 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001823 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1824 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001825 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826}
1827
David Sodman2b406362017-12-15 13:33:47 -08001828void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 ATRACE_CALL();
1831 ALOGV("postComposition");
1832
Brian Anderson3546a3f2016-07-14 11:51:14 -07001833 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001834 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001835 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001836 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001837 }
1838
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001839 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001840 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001841
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001844 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001845 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001846 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001847 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001848 } else {
1849 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1850 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001851
David Sodman73beded2017-11-15 11:56:06 -08001852 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001853 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001854 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001855 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001856 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001857
Ana Krulece588e312018-09-18 12:32:24 -07001858 DisplayStatInfo stats;
1859 if (mUseScheduler) {
1860 mScheduler->getDisplayStatInfo(&stats);
1861 } else {
1862 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1863 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1864 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865
David Sodman2b406362017-12-15 13:33:47 -08001866 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001867 // when we started doing work for this frame, but that should be okay
1868 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001869 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001870 CompositorTiming compositorTiming;
1871 {
David Sodman99974d22017-11-28 12:04:33 -08001872 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1873 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001874 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001875
Robert Carr2047fae2016-11-28 14:09:09 -08001876 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001877 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1878 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001879 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001880 recordBufferingStats(layer->getName().string(),
1881 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001882 }
Robert Carr2047fae2016-11-28 14:09:09 -08001883 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001884
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001885 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001886 if (mUseScheduler) {
1887 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001888 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001889 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1890 enableHardwareVsync();
1891 } else {
1892 disableHardwareVsync(false);
1893 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001894 }
1895 }
1896
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001897 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001898 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001899 if (mUseScheduler) {
1900 mScheduler->enableHardwareVsync();
1901 } else {
1902 enableHardwareVsync();
1903 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001904 }
1905 }
1906
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001907 if (mAnimCompositionPending) {
1908 mAnimCompositionPending = false;
1909
Brian Anderson4e606e32017-03-16 15:34:57 -07001910 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001911 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001912 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001913 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001914 // The HWC doesn't support present fences, so use the refresh
1915 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001916 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001917 mAnimFrameTracker.setActualPresentTime(presentTime);
1918 }
1919 mAnimFrameTracker.advanceFrame();
1920 }
Dan Stozab90cf072015-03-05 11:05:59 -08001921
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001922 mTimeStats.incrementTotalFrames();
1923 if (mHadClientComposition) {
1924 mTimeStats.incrementClientCompositionFrames();
1925 }
1926
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001927 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1928
Dominik Laskowski075d3172018-05-24 15:50:06 -07001929 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001930 return;
1931 }
1932
1933 nsecs_t currentTime = systemTime();
1934 if (mHasPoweredOff) {
1935 mHasPoweredOff = false;
1936 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001937 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001938 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001939 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1940 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001941 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001942 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001943 }
David Sodman4a36e932017-11-07 14:29:47 -08001944 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001945 }
David Sodman4a36e932017-11-07 14:29:47 -08001946 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001947
1948 {
1949 std::lock_guard lock(mTexturePoolMutex);
1950 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1951 if (refillCount > 0) {
1952 const size_t offset = mTexturePool.size();
1953 mTexturePool.resize(mTexturePoolSize);
1954 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1955 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1956 }
1957 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958}
1959
1960void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 ATRACE_CALL();
1962 ALOGV("rebuildLayerStacks");
1963
Mathias Agopiancd60f992012-08-16 16:28:27 -07001964 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001965 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001966 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001967 mVisibleRegionsDirty = false;
1968 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001969
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001970 for (const auto& pair : mDisplays) {
1971 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001972 Region opaqueRegion;
1973 Region dirtyRegion;
1974 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001975 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001976 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001977 const Rect bounds = display->getBounds();
1978 if (display->isPoweredOn()) {
1979 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001980
Jeff Sharkey76488112017-02-27 14:15:18 -07001981 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001982 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07001983 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001984 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001985 Region drawRegion(tr.transform(
1986 layer->visibleNonTransparentRegion));
1987 drawRegion.andSelf(bounds);
1988 if (!drawRegion.isEmpty()) {
1989 layersSortedByZ.add(layer);
1990 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001991 // Clear out the HWC layer if this layer was
1992 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07001993 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07001994 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001995 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001996 // WM changes display->layerStack upon sleep/awake.
1997 // Here we make sure we delete the HWC layers even if
1998 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001999 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002000 }
2001
2002 // If a layer is not going to get a release fence because
2003 // it is invisible, but it is also going to release its
2004 // old buffer, add it to the list of layers needing
2005 // fences.
2006 if (hwcLayerDestroyed) {
2007 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2008 mLayersWithQueuedFrames.cend(), layer);
2009 if (found != mLayersWithQueuedFrames.cend()) {
2010 layersNeedingFences.add(layer);
2011 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002012 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002013 });
2014 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002015 display->setVisibleLayersSortedByZ(layersSortedByZ);
2016 display->setLayersNeedingFences(layersNeedingFences);
2017 display->undefinedRegion.set(bounds);
2018 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2019 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002020 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002021 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002023
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002024// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002025// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002026// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002027// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002028// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002029// The returned HDR data space is one of
2030// - Dataspace::UNKNOWN
2031// - Dataspace::BT2020_HLG
2032// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002033Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2034 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002035 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002036 *outHdrDataSpace = Dataspace::UNKNOWN;
2037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002038 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002039 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 case Dataspace::V0_SCRGB:
2041 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002042 case Dataspace::BT2020:
2043 case Dataspace::BT2020_ITU:
2044 case Dataspace::BT2020_LINEAR:
2045 case Dataspace::DISPLAY_BT2020:
2046 bestDataSpace = Dataspace::DISPLAY_BT2020;
2047 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002048 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002049 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002050 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002051 case Dataspace::BT2020_PQ:
2052 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002053 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002054 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002055 case Dataspace::BT2020_HLG:
2056 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002057 // When there's mixed PQ content and HLG content, we set the HDR
2058 // data space to be BT2020_PQ and convert HLG to PQ.
2059 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2060 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002061 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002062 break;
2063 default:
2064 break;
2065 }
Romain Guy54f154a2017-10-24 21:40:32 +01002066 }
2067
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002068 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002069}
2070
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002071// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002072void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2073 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002074 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2075 *outMode = ColorMode::NATIVE;
2076 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002077 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002078 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002079 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002080
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002081 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002082 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002083
Peiyong Lindfde5112018-06-05 10:58:41 -07002084 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002085 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002086 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002087 if (isHdr) {
2088 bestDataSpace = hdrDataSpace;
2089 }
2090
Chia-I Wu0d711262018-05-21 15:19:35 -07002091 RenderIntent intent;
2092 switch (mDisplayColorSetting) {
2093 case DisplayColorSetting::MANAGED:
2094 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002095 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002096 break;
2097 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002098 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002099 break;
2100 default: // vendor display color setting
2101 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2102 break;
2103 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002105 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002106}
2107
David Sodmanfa9b2af2017-12-24 13:28:59 -08002108void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002109{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002110 bool dirty = !display->getDirtyRegion(false).isEmpty();
2111 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2112 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002113
David Sodmanfa9b2af2017-12-24 13:28:59 -08002114 // If nothing has changed (!dirty), don't recompose.
2115 // If something changed, but we don't currently have any visible layers,
2116 // and didn't when we last did a composition, then skip it this time.
2117 // The second rule does two things:
2118 // - When all layers are removed from a display, we'll emit one black
2119 // frame, then nothing more until we get new layers.
2120 // - When a display is created with a private layer stack, we won't
2121 // emit any black frames until a layer is added to the layer stack.
2122 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002123
Dominik Laskowski075d3172018-05-24 15:50:06 -07002124 const char flagPrefix[] = {'-', '+'};
2125 static_cast<void>(flagPrefix);
2126 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2127 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2128 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002129
David Sodmanfa9b2af2017-12-24 13:28:59 -08002130 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002131
David Sodmanfa9b2af2017-12-24 13:28:59 -08002132 if (mustRecompose) {
2133 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002134 }
2135}
2136
David Sodmanfa9b2af2017-12-24 13:28:59 -08002137void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002138{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 if (!display->isPoweredOn()) {
2140 return;
David Sodman2b406362017-12-15 13:33:47 -08002141 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142
Dominik Laskowski05275f12018-11-01 15:03:24 -07002143 status_t result = display->prepareFrame(getHwComposer(),
2144 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002145 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2146 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002147}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002148
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 ALOGV("doComposition");
2152
David Sodmanfa9b2af2017-12-24 13:28:59 -08002153 if (display->isPoweredOn()) {
2154 // transform the dirty region into this screen's coordinate space
2155 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002156
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157 // repaint the framebuffer (if needed)
2158 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002159
David Sodmanfa9b2af2017-12-24 13:28:59 -08002160 display->dirtyRegion.clear();
2161 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002162 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002163 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002164}
2165
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166void SurfaceFlinger::postFrame()
2167{
2168 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002169 const auto display = getDefaultDisplayDeviceLocked();
2170 if (display && getHwComposer().isConnected(*display->getId())) {
2171 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2173 logFrameStats();
2174 }
2175 }
2176}
2177
2178void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002179{
Mathias Agopian841cde52012-03-01 15:44:37 -08002180 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002182
David Sodmanfa9b2af2017-12-24 13:28:59 -08002183 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002184
David Sodmanfa9b2af2017-12-24 13:28:59 -08002185 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002186 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002187 if (displayId) {
2188 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002189 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002190 display->onSwapBuffersCompleted();
2191 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002192 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002193 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002194
Chia-I Wu7b549592017-11-15 09:14:57 -08002195 // The layer buffer from the previous frame (if any) is released
2196 // by HWC only when the release fence from this frame (if any) is
2197 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002198 if (displayId && layer->hasHwcLayer(*displayId)) {
2199 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2200 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002201 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002202
2203 // If the layer was client composited in the previous frame, we
2204 // need to merge with the previous client target acquire fence.
2205 // Since we do not track that, always merge with the current
2206 // client target acquire fence when it is available, even though
2207 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002208 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002209 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002210 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002211 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002212
David Sodman15094112018-10-11 09:39:37 -07002213 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214 }
Chia-I Wu83806892017-11-16 10:50:20 -08002215
2216 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002218 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002219 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002220 sp<Fence> presentFence =
2221 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002222 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002223 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002224 }
2225 }
2226
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 if (displayId) {
2228 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002229 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002230 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231}
2232
Mathias Agopian87baae12012-07-31 12:38:26 -07002233void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234{
Mathias Agopian841cde52012-03-01 15:44:37 -08002235 ATRACE_CALL();
2236
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002237 // here we keep a copy of the drawing state (that is the state that's
2238 // going to be overwritten by handleTransactionLocked()) outside of
2239 // mStateLock so that the side-effects of the State assignment
2240 // don't happen with mStateLock held (which can cause deadlocks).
2241 State drawingState(mDrawingState);
2242
Mathias Agopianca4d3602011-05-19 15:38:14 -07002243 Mutex::Autolock _l(mStateLock);
2244 const nsecs_t now = systemTime();
2245 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246
Mathias Agopianca4d3602011-05-19 15:38:14 -07002247 // Here we're guaranteed that some transaction flags are set
2248 // so we can call handleTransactionLocked() unconditionally.
2249 // We call getTransactionFlags(), which will also clear the flags,
2250 // with mStateLock held to guarantee that mCurrentState won't change
2251 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002252
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002253 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002254 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002255 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002256
Mathias Agopianca4d3602011-05-19 15:38:14 -07002257 mLastTransactionTime = systemTime() - now;
2258 mDebugInTransaction = 0;
2259 invalidateHwcGeometry();
2260 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002261}
2262
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2264 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 const std::optional<DisplayIdentificationInfo> info =
2266 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002267
Dominik Laskowski075d3172018-05-24 15:50:06 -07002268 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002269 continue;
2270 }
2271
Lloyd Piqueba04e622017-12-14 17:11:26 -08002272 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 if (!mPhysicalDisplayTokens.count(info->id)) {
2274 ALOGV("Creating display %" PRIu64, info->id);
2275 mPhysicalDisplayTokens[info->id] = new BBinder();
2276 DisplayDeviceState state;
2277 state.displayId = info->id;
2278 state.isSecure = true; // All physical displays are currently considered secure.
2279 state.displayName = info->name;
2280 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2281 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002282 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002283 } else {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002284 ALOGV("Removing display %" PRIu64, info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002285
Dominik Laskowski075d3172018-05-24 15:50:06 -07002286 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2287 if (index >= 0) {
2288 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2289 mInterceptor->saveDisplayDeletion(state.sequenceId);
2290 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002291 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002292 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002293 }
2294
2295 processDisplayChangesLocked();
2296 }
2297
2298 mPendingHotplugEvents.clear();
2299}
2300
Lloyd Pique99d3da52018-01-22 17:48:03 -08002301sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002302 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2303 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2304 const sp<IGraphicBufferProducer>& producer) {
2305 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2306 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002307 creationArgs.isSecure = state.isSecure;
2308 creationArgs.displaySurface = dispSurface;
2309 creationArgs.hasWideColorGamut = false;
2310 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311
Dominik Laskowski075d3172018-05-24 15:50:06 -07002312 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2313 creationArgs.isPrimary = isInternalDisplay;
2314
2315 if (useColorManagement && displayId) {
2316 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002318 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002319 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002323 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002324 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 }
tangrobin6753a022018-08-10 10:58:54 +08002326 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 if (displayId) {
2329 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002330 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002331 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002332 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333
Lloyd Pique90c115d2018-09-18 21:39:42 -07002334 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002336 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337
2338 /*
2339 * Create our display's surface
2340 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002341 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002342 renderSurface->setCritical(isInternalDisplay);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002343 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002345 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346
2347 // Make sure that composition can never be stalled by a virtual display
2348 // consumer that isn't processing buffers fast enough. We have to do this
2349 // in two places:
2350 // * Here, in case the display is composed entirely by HWC.
2351 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2352 // window's swap interval in eglMakeCurrent, so they'll override the
2353 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002354 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2356 }
2357
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 creationArgs.displayInstallOrientation =
2359 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002360
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002362 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363
Lloyd Pique90c115d2018-09-18 21:39:42 -07002364 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365
2366 if (maxFrameBufferAcquiredBuffers >= 3) {
2367 nativeWindowSurface->preallocateBuffers();
2368 }
2369
2370 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002372 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002373 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002374 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002378 if (!state.isVirtual()) {
2379 LOG_ALWAYS_FATAL_IF(!displayId);
2380 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002381 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002382
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 display->setLayerStack(state.layerStack);
2384 display->setProjection(state.orientation, state.viewport, state.frame);
2385 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002387 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388}
2389
Lloyd Pique347200f2017-12-14 17:00:15 -08002390void SurfaceFlinger::processDisplayChangesLocked() {
2391 // here we take advantage of Vector's copy-on-write semantics to
2392 // improve performance by skipping the transaction entirely when
2393 // know that the lists are identical
2394 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2395 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2396 if (!curr.isIdenticalTo(draw)) {
2397 mVisibleRegionsDirty = true;
2398 const size_t cc = curr.size();
2399 size_t dc = draw.size();
2400
2401 // find the displays that were removed
2402 // (ie: in drawing state but not in current state)
2403 // also handle displays that changed
2404 // (ie: displays that are in both lists)
2405 for (size_t i = 0; i < dc;) {
2406 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2407 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 // Save display IDs before disconnecting.
2409 const auto internalDisplayId = getInternalDisplayId();
2410 const auto externalDisplayId = getExternalDisplayId();
2411
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002413 // Call makeCurrent() on the primary display so we can
2414 // be sure that nothing associated with this display
2415 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002416 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2417 defaultDisplay->makeCurrent();
2418 }
2419 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2420 display->disconnect(getHwComposer());
2421 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002422 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002423 if (mUseScheduler) {
2424 mScheduler->hotplugReceived(mAppConnectionHandle,
2425 EventThread::DisplayType::Primary, false);
2426 } else {
2427 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2428 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002430 if (mUseScheduler) {
2431 mScheduler->hotplugReceived(mAppConnectionHandle,
2432 EventThread::DisplayType::External, false);
2433 } else {
2434 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2435 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002436 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002437 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 } else {
2439 // this display is in both lists. see if something changed.
2440 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2443 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2444 if (state_binder != draw_binder) {
2445 // changing the surface is like destroying and
2446 // recreating the DisplayDevice, so we just remove it
2447 // from the drawing state, so that it get re-added
2448 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2450 display->disconnect(getHwComposer());
2451 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002452 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 mDrawingState.displays.removeItemsAt(i);
2454 dc--;
2455 // at this point we must loop to the next item
2456 continue;
2457 }
2458
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002459 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002460 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002462 }
2463 if ((state.orientation != draw[i].orientation) ||
2464 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 }
2467 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002469 }
2470 }
2471 }
2472 ++i;
2473 }
2474
2475 // find displays that were added
2476 // (ie: in current state but not in drawing state)
2477 for (size_t i = 0; i < cc; i++) {
2478 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2479 const DisplayDeviceState& state(curr[i]);
2480
2481 sp<DisplaySurface> dispSurface;
2482 sp<IGraphicBufferProducer> producer;
2483 sp<IGraphicBufferProducer> bqProducer;
2484 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002485 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002488 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002489 // Virtual displays without a surface are dormant:
2490 // they have external state (layer stack, projection,
2491 // etc.) but no internal state (i.e. a DisplayDevice).
2492 if (state.surface != nullptr) {
2493 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 int width = 0;
2496 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2497 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2498 int height = 0;
2499 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2500 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2501 int intFormat = 0;
2502 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2503 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002504 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002505
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 displayId =
2507 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 }
2509
2510 // TODO: Plumb requested format back up to consumer
2511
2512 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 bqProducer, bqConsumer,
2515 state.displayName);
2516
2517 dispSurface = vds;
2518 producer = vds;
2519 }
2520 } else {
2521 ALOGE_IF(state.surface != nullptr,
2522 "adding a supported display, but rendering "
2523 "surface is provided (%p), ignoring it",
2524 state.surface.get());
2525
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 displayId = state.displayId;
2527 LOG_ALWAYS_FATAL_IF(!displayId);
2528 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 producer = bqProducer;
2530 }
2531
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002533 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002534 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002535 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002536 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002537 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 LOG_ALWAYS_FATAL_IF(!displayId);
2539
2540 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002541 if (mUseScheduler) {
2542 mScheduler->hotplugReceived(mAppConnectionHandle,
2543 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002544 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002545 } else {
2546 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2547 true);
2548 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002550 if (mUseScheduler) {
2551 mScheduler->hotplugReceived(mAppConnectionHandle,
2552 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002553 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002554 } else {
2555 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2556 true);
2557 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002558 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002559 }
2560 }
2561 }
2562 }
2563 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002564
2565 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002566}
2567
Mathias Agopian87baae12012-07-31 12:38:26 -07002568void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002569{
Dan Stoza7dde5992015-05-22 09:51:44 -07002570 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002571 mCurrentState.traverseInZOrder([](Layer* layer) {
2572 layer->notifyAvailableFrames();
2573 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002574
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 /*
2576 * Traversal of the children
2577 * (perform the transaction for each of them if needed)
2578 */
2579
Mathias Agopian3559b072012-08-15 13:46:03 -07002580 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002581 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002583 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584
2585 const uint32_t flags = layer->doTransaction(0);
2586 if (flags & Layer::eVisibleRegion)
2587 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002588 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 }
2590
2591 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002592 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 */
2594
Mathias Agopiane57f2922012-08-09 16:29:12 -07002595 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002596 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002597 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002598 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002600 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002601 // The transform hint might have changed for some layers
2602 // (either because a display has changed, or because a layer
2603 // as changed).
2604 //
2605 // Walk through all the layers in currentLayers,
2606 // and update their transform hint.
2607 //
2608 // If a layer is visible only on a single display, then that
2609 // display is used to calculate the hint, otherwise we use the
2610 // default display.
2611 //
2612 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2613 // the hint is set before we acquire a buffer from the surface texture.
2614 //
2615 // NOTE: layer transactions have taken place already, so we use their
2616 // drawing state. However, SurfaceFlinger's own transaction has not
2617 // happened yet, so we must use the current state layer list
2618 // (soon to become the drawing state list).
2619 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002620 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002621 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002622 bool first = true;
2623 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002624 // NOTE: we rely on the fact that layers are sorted by
2625 // layerStack first (so we don't have to traverse the list
2626 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002627 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002628 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002629 currentlayerStack = layerStack;
2630 // figure out if this layerstack is mirrored
2631 // (more than one display) if so, pick the default display,
2632 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002633 hintDisplay = nullptr;
2634 for (const auto& [token, display] : mDisplays) {
2635 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2636 if (hintDisplay) {
2637 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002638 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002639 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002640 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002641 }
2642 }
2643 }
2644 }
Chet Haase91d25932013-04-11 15:24:55 -07002645
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002646 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002647 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2648 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002649
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002650 // could be null when this layer is using a layerStack
2651 // that is not visible on any display. Also can occur at
2652 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002653 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002654 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002656 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002657 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 if (hintDisplay) {
2659 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002660 }
Robert Carr2047fae2016-11-28 14:09:09 -08002661
2662 first = false;
2663 });
Mathias Agopian84300952012-11-21 16:02:13 -08002664 }
2665
2666
Mathias Agopian3559b072012-08-15 13:46:03 -07002667 /*
2668 * Perform our own transaction if needed
2669 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002670
2671 if (mLayersAdded) {
2672 mLayersAdded = false;
2673 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002674 mVisibleRegionsDirty = true;
2675 }
2676
2677 // some layers might have been removed, so
2678 // we need to update the regions they're exposing.
2679 if (mLayersRemoved) {
2680 mLayersRemoved = false;
2681 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002682 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002684 // this layer is not visible anymore
2685 // TODO: we could traverse the tree from front to back and
2686 // compute the actual visible region
2687 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688 Region visibleReg;
2689 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002690 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002691 }
Robert Carr2047fae2016-11-28 14:09:09 -08002692 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693 }
2694
2695 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002696
2697 updateCursorAsync();
2698}
2699
2700void SurfaceFlinger::updateCursorAsync()
2701{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002702 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002704 continue;
2705 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2708 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002709 }
2710 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711}
2712
2713void SurfaceFlinger::commitTransaction()
2714{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002715 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002716 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 for (const auto& l : mLayersPendingRemoval) {
2718 recordBufferingStats(l->getName().string(),
2719 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002720
2721 // We need to release the HWC layers when the Layer is removed
2722 // from the current state otherwise the HWC layer just continues
2723 // showing at its last configured state until we eventually
2724 // abandon the buffer queue.
2725 if (l->isRemovedFromCurrentState()) {
2726 l->destroyAllHwcLayers();
2727 l->releasePendingBuffer(systemTime());
2728 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 }
2730 mLayersPendingRemoval.clear();
2731 }
2732
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002733 // If this transaction is part of a window animation then the next frame
2734 // we composite should be considered an animation as well.
2735 mAnimCompositionPending = mAnimTransactionPending;
2736
Mathias Agopian4fec8732012-06-29 14:12:52 -07002737 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002738 // clear the "changed" flags in current state
2739 mCurrentState.colorMatrixChanged = false;
2740
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 mDrawingState.traverseInZOrder([](Layer* layer) {
2742 layer->commitChildList();
2743 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002744 mTransactionPending = false;
2745 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747}
2748
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2750 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002751 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002753
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 Region aboveOpaqueLayers;
2755 Region aboveCoveredLayers;
2756 Region dirty;
2757
Mathias Agopian87baae12012-07-31 12:38:26 -07002758 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
Robert Carr2047fae2016-11-28 14:09:09 -08002760 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002762 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763
Jesse Hall01e29052013-02-19 16:13:35 -08002764 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002765 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002766 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002768
Mathias Agopianab028732010-03-16 16:41:46 -07002769 /*
2770 * opaqueRegion: area of a surface that is fully opaque.
2771 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002773
2774 /*
2775 * visibleRegion: area of a surface that is visible on screen
2776 * and not fully transparent. This is essentially the layer's
2777 * footprint minus the opaque regions above it.
2778 * Areas covered by a translucent surface are considered visible.
2779 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002781
2782 /*
2783 * coveredRegion: area of a surface that is covered by all
2784 * visible regions above it (which includes the translucent areas).
2785 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002787
Jesse Halla8026d22012-09-25 13:25:04 -07002788 /*
2789 * transparentRegion: area of a surface that is hinted to be completely
2790 * transparent. This is only used to tell when the layer has no visible
2791 * non-transparent regions and can be removed from the layer list. It
2792 * does not affect the visibleRegion of this layer or any layers
2793 * beneath it. The hint may not be correct if apps don't respect the
2794 * SurfaceView restrictions (which, sadly, some don't).
2795 */
2796 Region transparentRegion;
2797
Mathias Agopianab028732010-03-16 16:41:46 -07002798
2799 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002800 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002801 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002802 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002804 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002805 if (!visibleRegion.isEmpty()) {
2806 // Remove the transparent area from the visible region
2807 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002808 if (tr.preserveRects()) {
2809 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002810 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002812 // transformation too complex, can't do the
2813 // transparent region optimization.
2814 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002815 }
Mathias Agopianab028732010-03-16 16:41:46 -07002816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
Mathias Agopianab028732010-03-16 16:41:46 -07002818 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002820 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002821 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002822 // the opaque region is the layer's footprint
2823 opaqueRegion = visibleRegion;
2824 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 }
2826 }
2827
Robert Carre5f4f692018-01-12 13:12:28 -08002828 if (visibleRegion.isEmpty()) {
2829 layer->clearVisibilityRegions();
2830 return;
2831 }
2832
Mathias Agopianab028732010-03-16 16:41:46 -07002833 // Clip the covered region to the visible region
2834 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2835
2836 // Update aboveCoveredLayers for next (lower) layer
2837 aboveCoveredLayers.orSelf(visibleRegion);
2838
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 // subtract the opaque region covered by the layers above us
2840 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841
2842 // compute this layer's dirty region
2843 if (layer->contentDirty) {
2844 // we need to invalidate the whole region
2845 dirty = visibleRegion;
2846 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 layer->contentDirty = false;
2849 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002850 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002851 * the exposed region consists of two components:
2852 * 1) what's VISIBLE now and was COVERED before
2853 * 2) what's EXPOSED now less what was EXPOSED before
2854 *
2855 * note that (1) is conservative, we start with the whole
2856 * visible region but only keep what used to be covered by
2857 * something -- which mean it may have been exposed.
2858 *
2859 * (2) handles areas that were not covered by anything but got
2860 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002861 */
Mathias Agopianab028732010-03-16 16:41:46 -07002862 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863 const Region oldVisibleRegion = layer->visibleRegion;
2864 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002865 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2866 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 }
2868 dirty.subtractSelf(aboveOpaqueLayers);
2869
2870 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002871 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872
Mathias Agopianab028732010-03-16 16:41:46 -07002873 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002875
Jesse Halla8026d22012-09-25 13:25:04 -07002876 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 layer->setVisibleRegion(visibleRegion);
2878 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002879 layer->setVisibleNonTransparentRegion(
2880 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002881 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Mathias Agopian87baae12012-07-31 12:38:26 -07002883 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884}
2885
Chia-I Wuab0c3192017-08-01 11:29:00 -07002886void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2889 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002890 }
2891 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002892}
2893
Dan Stoza6b9454d2014-11-07 16:00:59 -08002894bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 ALOGV("handlePageFlip");
2897
Brian Andersond6927fb2016-07-23 23:37:30 -07002898 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899
Mathias Agopian4fec8732012-06-29 14:12:52 -07002900 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002901 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002902 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002903
2904 // Store the set of layers that need updates. This set must not change as
2905 // buffers are being latched, as this could result in a deadlock.
2906 // Example: Two producers share the same command stream and:
2907 // 1.) Layer 0 is latched
2908 // 2.) Layer 0 gets a new frame
2909 // 2.) Layer 1 gets a new frame
2910 // 3.) Layer 1 is latched.
2911 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2912 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002913 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002914 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002915 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002916 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2917 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002918 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002919 } else {
2920 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002922 } else {
2923 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002924 }
Robert Carr2047fae2016-11-28 14:09:09 -08002925 });
2926
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002928 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002929 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002930 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002931 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002932 newDataLatched = true;
2933 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002934 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002935
Alec Mouri86770e52018-09-24 22:40:58 +00002936 // Clear the renderengine fence here...
2937 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2938 // clear instead of sp::clear.
2939 getBE().flushFence = Fence::NO_FENCE;
2940
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002941 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002942
2943 // If we will need to wake up at some time in the future to deal with a
2944 // queued frame that shouldn't be displayed during this vsync period, wake
2945 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002946 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002947 signalLayerUpdate();
2948 }
2949
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002950 // enter boot animation on first buffer latch
2951 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2952 ALOGI("Enter boot animation");
2953 mBootStage = BootStage::BOOTANIMATION;
2954 }
2955
Dan Stoza6b9454d2014-11-07 16:00:59 -08002956 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002957 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958}
2959
Mathias Agopianad456f92011-01-13 17:53:01 -08002960void SurfaceFlinger::invalidateHwcGeometry()
2961{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002963}
2964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002965void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2966 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002967 // We only need to actually compose the display if:
2968 // 1) It is being handled by hardware composer, which may need this to
2969 // keep its virtual display state machine in sync, or
2970 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002971 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002972 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002974 return;
2975 }
2976
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002979
2980 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002981 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002984bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002987 const Region bounds(display->bounds());
2988 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002989 const auto displayId = display->getId();
2990 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002991 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002992
Peiyong Lind3788632018-09-18 16:01:31 -07002993 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002994 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002995 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002996
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 if (hasClientComposition) {
2998 ALOGV("hasClientComposition");
2999
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003000 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003001 if (display->hasWideColorGamut()) {
3002 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003003 }
3004 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003005 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003007
Dominik Laskowski7e045462018-05-30 13:02:02 -07003008 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003009 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3010 HWC2::Capability::SkipClientColorTransform);
3011
Peiyong Lind3788632018-09-18 16:01:31 -07003012 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003013 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3014 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003015 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003016 }
3017
Chia-I Wud49d6692018-06-27 07:17:41 +08003018 // The current enhanced saturation matrix is designed to enhance Display P3,
3019 // thus we only apply this matrix when the render intent is not colorimetric
3020 // and the output color space is Display P3.
3021 needsEnhancedColorMatrix =
3022 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3023 outputDataspace == Dataspace::DISPLAY_P3);
3024 if (needsEnhancedColorMatrix) {
3025 colorMatrix *= mEnhancedSaturationMatrix;
3026 }
3027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003028 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003029 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003031 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003032
3033 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003034 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3035 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3036 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003037 }
3038 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003039 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003040
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003041 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003042 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003043 // when using overlays, we assume a fully transparent framebuffer
3044 // NOTE: we could reduce how much we need to clear, for instance
3045 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003046 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003047 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003048 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003049 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003050 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003051 // we're left with the letterbox region
3052 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003054
3055 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003056 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003057
Mathias Agopianb9494d52012-04-18 02:28:45 -07003058 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003059 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003060 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003061 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003062 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003063 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003064
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003065 const Rect& bounds = display->getBounds();
3066 const Rect& scissor = display->getScissor();
3067 if (scissor != bounds) {
3068 // scissor doesn't match the screen's dimensions, so we
3069 // need to clear everything outside of it and enable
3070 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003071
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003072 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003073 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003075 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003076
Mathias Agopian85d751c2012-08-29 16:59:24 -07003077 /*
3078 * and then, render the layers targeted at the framebuffer
3079 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003080
Dan Stoza9e56aa02015-11-02 13:00:03 -08003081 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003082 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003083 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003084 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003085 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003086 displayTransform.transform(layer->visibleRegion)));
3087 ALOGV("Layer: %s", layer->getName().string());
3088 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003089 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003090 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003091 case HWC2::Composition::Cursor:
3092 case HWC2::Composition::Device:
3093 case HWC2::Composition::Sideband:
3094 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003095 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003096 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003097 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003098 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3099 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 // never clear the very first layer since we're
3101 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003102 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003103 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003104 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003105 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003107 if (layer->hasColorTransform()) {
3108 mat4 tmpMatrix;
3109 if (applyColorMatrix) {
3110 tmpMatrix = mDrawingState.colorMatrix;
3111 }
3112 tmpMatrix *= layer->getColorTransform();
3113 if (needsEnhancedColorMatrix) {
3114 tmpMatrix *= mEnhancedSaturationMatrix;
3115 }
3116 getRenderEngine().setColorTransform(tmpMatrix);
3117 } else {
3118 getRenderEngine().setColorTransform(colorMatrix);
3119 }
David Sodmanc1498e62018-09-12 14:36:26 -07003120 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003121 break;
3122 }
3123 default:
3124 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003125 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003126 } else {
3127 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003128 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003129 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003130 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003131
Peiyong Lind3788632018-09-18 16:01:31 -07003132 // Clear color transform matrix at the end of the frame.
3133 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003134
Mathias Agopianf45c5102012-10-24 16:29:17 -07003135 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003136 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003137 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138}
3139
Chia-I Wu28e3a252018-09-07 12:05:02 -07003140void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003141 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003142 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143}
3144
Dan Stoza7d89d062015-04-30 13:29:25 -07003145status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003146 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003147 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 const sp<Layer>& lbc,
3149 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003150{
Dan Stoza7d89d062015-04-30 13:29:25 -07003151 // add this layer to the current state list
3152 {
3153 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003155 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3156 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003157 return NO_MEMORY;
3158 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 if (parent == nullptr) {
3160 mCurrentState.layersSortedByZ.add(lbc);
3161 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003162 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003163 ALOGE("addClientLayer called with a removed parent");
3164 return NAME_NOT_FOUND;
3165 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 parent->addChild(lbc);
3167 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003168
Yiwei Zhang243b3782018-05-15 17:40:04 -07003169 if (gbc != nullptr) {
3170 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3171 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3172 mMaxGraphicBufferProducerListSize,
3173 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3174 mGraphicBufferProducerList.size(),
3175 mMaxGraphicBufferProducerListSize, mNumLayers);
3176 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003178 }
3179
Mathias Agopian96f08192010-06-02 23:28:45 -07003180 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003181 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003182
Dan Stoza7d89d062015-04-30 13:29:25 -07003183 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003184}
3185
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003186status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003187 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003188 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3189}
Robert Carr7f9b8992017-03-10 11:08:39 -08003190
Robert Carr2e102c92018-10-23 12:11:15 -07003191status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003192 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003194 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003195 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003196 if (topLevelOnly) {
3197 return NO_ERROR;
3198 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003199 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003200 } else {
3201 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003202 }
3203
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003204 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003205
3206 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208}
3209
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003210uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003211 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003212}
3213
Mathias Agopian3f844832013-08-07 21:24:32 -07003214uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003215 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216}
3217
Mathias Agopian3f844832013-08-07 21:24:32 -07003218uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003219 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003220}
3221
3222uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003223 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003224 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003225 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003227 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 }
3229 return old;
3230}
3231
chaviwca27f252018-02-06 16:46:39 -08003232bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3233 for (const ComposerState& state : states) {
3234 // Here we need to check that the interface we're given is indeed
3235 // one of our own. A malicious client could give us a nullptr
3236 // IInterface, or one of its own or even one of our own but a
3237 // different type. All these situations would cause us to crash.
3238 if (state.client == nullptr) {
3239 return true;
3240 }
3241
3242 sp<IBinder> binder = IInterface::asBinder(state.client);
3243 if (binder == nullptr) {
3244 return true;
3245 }
3246
3247 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3248 return true;
3249 }
3250 }
3251 return false;
3252}
3253
Mathias Agopian8b33f032012-07-24 20:43:54 -07003254void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003255 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003256 const Vector<DisplayState>& displays,
3257 uint32_t flags)
3258{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003259 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003260 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003261 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003262
chaviwca27f252018-02-06 16:46:39 -08003263 if (containsAnyInvalidClientState(states)) {
3264 return;
3265 }
3266
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003267 if (flags & eAnimation) {
3268 // For window updates that are part of an animation we must wait for
3269 // previous animation "frames" to be handled.
3270 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003271 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003272 if (CC_UNLIKELY(err != NO_ERROR)) {
3273 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003274 // caller after a few seconds.
3275 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3276 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003277 mAnimTransactionPending = false;
3278 break;
3279 }
3280 }
3281 }
3282
chaviwca27f252018-02-06 16:46:39 -08003283 for (const DisplayState& display : displays) {
3284 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003285 }
3286
chaviwca27f252018-02-06 16:46:39 -08003287 for (const ComposerState& state : states) {
3288 transactionFlags |= setClientStateLocked(state);
3289 }
3290
3291 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3292 // as destroyed should only occur after setting all other states. This is to allow for a
3293 // child re-parent to happen before marking its original parent as destroyed (which would
3294 // then mark the child as destroyed).
3295 for (const ComposerState& state : states) {
3296 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003297 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003298
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003299 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3300 // anyway. This can be used as a flush mechanism for previous async transactions.
3301 // Empty animation transaction can be used to simulate back-pressure, so also force a
3302 // transaction for empty animation transactions.
3303 if (transactionFlags == 0 &&
3304 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003305 transactionFlags = eTransactionNeeded;
3306 }
3307
Mathias Agopian386aa982011-11-07 21:58:03 -08003308 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003309 if (mInterceptor->isEnabled()) {
3310 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003311 }
Irvel468051e2016-06-13 16:44:44 -07003312
Mathias Agopian386aa982011-11-07 21:58:03 -08003313 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003314 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3315 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003316 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003317
3318 // if this is a synchronous transaction, wait for it to take effect
3319 // before returning.
3320 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003321 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003322 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003323 if (flags & eAnimation) {
3324 mAnimTransactionPending = true;
3325 }
3326 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3328 if (CC_UNLIKELY(err != NO_ERROR)) {
3329 // just in case something goes wrong in SF, return to the
3330 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003331 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3332 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003333 break;
3334 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003335 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336 }
3337}
3338
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003339uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3340 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3341 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003342
Mathias Agopiane57f2922012-08-09 16:29:12 -07003343 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003344 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3345
3346 const uint32_t what = s.what;
3347 if (what & DisplayState::eSurfaceChanged) {
3348 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3349 state.surface = s.surface;
3350 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003351 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003352 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003353 if (what & DisplayState::eLayerStackChanged) {
3354 if (state.layerStack != s.layerStack) {
3355 state.layerStack = s.layerStack;
3356 flags |= eDisplayTransactionNeeded;
3357 }
3358 }
3359 if (what & DisplayState::eDisplayProjectionChanged) {
3360 if (state.orientation != s.orientation) {
3361 state.orientation = s.orientation;
3362 flags |= eDisplayTransactionNeeded;
3363 }
3364 if (state.frame != s.frame) {
3365 state.frame = s.frame;
3366 flags |= eDisplayTransactionNeeded;
3367 }
3368 if (state.viewport != s.viewport) {
3369 state.viewport = s.viewport;
3370 flags |= eDisplayTransactionNeeded;
3371 }
3372 }
3373 if (what & DisplayState::eDisplaySizeChanged) {
3374 if (state.width != s.width) {
3375 state.width = s.width;
3376 flags |= eDisplayTransactionNeeded;
3377 }
3378 if (state.height != s.height) {
3379 state.height = s.height;
3380 flags |= eDisplayTransactionNeeded;
3381 }
3382 }
3383
Mathias Agopiane57f2922012-08-09 16:29:12 -07003384 return flags;
3385}
3386
Robert Carrd4ae7f32018-06-07 16:10:57 -07003387bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3388 IPCThreadState* ipc = IPCThreadState::self();
3389 const int pid = ipc->getCallingPid();
3390 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003391 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003392 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003393 return false;
3394 }
3395 return true;
3396}
3397
chaviwca27f252018-02-06 16:46:39 -08003398uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3399 const layer_state_t& s = composerState.state;
3400 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3401
Mathias Agopian13127d82013-03-05 17:47:11 -08003402 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003403 if (layer == nullptr) {
3404 return 0;
3405 }
3406
chaviw8b3871a2017-11-01 17:41:01 -07003407 uint32_t flags = 0;
3408
3409 const uint32_t what = s.what;
3410 bool geometryAppliesWithResize =
3411 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003412
3413 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3414 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003415 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003416 layer->pushPendingState();
3417 }
3418
chaviw8b3871a2017-11-01 17:41:01 -07003419 if (what & layer_state_t::ePositionChanged) {
3420 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3421 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003422 }
chaviw8b3871a2017-11-01 17:41:01 -07003423 }
3424 if (what & layer_state_t::eLayerChanged) {
3425 // NOTE: index needs to be calculated before we update the state
3426 const auto& p = layer->getParent();
3427 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003428 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003429 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003430 mCurrentState.layersSortedByZ.removeAt(idx);
3431 mCurrentState.layersSortedByZ.add(layer);
3432 // we need traversal (state changed)
3433 // AND transaction (list changed)
3434 flags |= eTransactionNeeded|eTraversalNeeded;
3435 }
chaviw8b3871a2017-11-01 17:41:01 -07003436 } else {
3437 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003438 flags |= eTransactionNeeded|eTraversalNeeded;
3439 }
3440 }
chaviw8b3871a2017-11-01 17:41:01 -07003441 }
3442 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003443 // NOTE: index needs to be calculated before we update the state
3444 const auto& p = layer->getParent();
3445 if (p == nullptr) {
3446 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3447 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3448 mCurrentState.layersSortedByZ.removeAt(idx);
3449 mCurrentState.layersSortedByZ.add(layer);
3450 // we need traversal (state changed)
3451 // AND transaction (list changed)
3452 flags |= eTransactionNeeded|eTraversalNeeded;
3453 }
3454 } else {
3455 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3456 flags |= eTransactionNeeded|eTraversalNeeded;
3457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 }
3459 }
3460 if (what & layer_state_t::eSizeChanged) {
3461 if (layer->setSize(s.w, s.h)) {
3462 flags |= eTraversalNeeded;
3463 }
3464 }
3465 if (what & layer_state_t::eAlphaChanged) {
3466 if (layer->setAlpha(s.alpha))
3467 flags |= eTraversalNeeded;
3468 }
3469 if (what & layer_state_t::eColorChanged) {
3470 if (layer->setColor(s.color))
3471 flags |= eTraversalNeeded;
3472 }
Peiyong Lind3788632018-09-18 16:01:31 -07003473 if (what & layer_state_t::eColorTransformChanged) {
3474 if (layer->setColorTransform(s.colorTransform)) {
3475 flags |= eTraversalNeeded;
3476 }
3477 }
chaviw8b3871a2017-11-01 17:41:01 -07003478 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003479 // TODO: b/109894387
3480 //
3481 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3482 // rotation. To see the problem observe that if we have a square parent, and a child
3483 // of the same size, then we rotate the child 45 degrees around it's center, the child
3484 // must now be cropped to a non rectangular 8 sided region.
3485 //
3486 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3487 // private API, and the WindowManager only uses rotation in one case, which is on a top
3488 // level layer in which cropping is not an issue.
3489 //
3490 // However given that abuse of rotation matrices could lead to surfaces extending outside
3491 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3492 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3493 // transformations.
3494 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003495 flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eTransparentRegionChanged) {
3498 if (layer->setTransparentRegionHint(s.transparentRegion))
3499 flags |= eTraversalNeeded;
3500 }
3501 if (what & layer_state_t::eFlagsChanged) {
3502 if (layer->setFlags(s.flags, s.mask))
3503 flags |= eTraversalNeeded;
3504 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003505 if (what & layer_state_t::eCropChanged_legacy) {
3506 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003507 flags |= eTraversalNeeded;
3508 }
chaviw8b3871a2017-11-01 17:41:01 -07003509 if (what & layer_state_t::eLayerStackChanged) {
3510 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3511 // We only allow setting layer stacks for top level layers,
3512 // everything else inherits layer stack from its parent.
3513 if (layer->hasParent()) {
3514 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3515 layer->getName().string());
3516 } else if (idx < 0) {
3517 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3518 "that also does not appear in the top level layer list. Something"
3519 " has gone wrong.", layer->getName().string());
3520 } else if (layer->setLayerStack(s.layerStack)) {
3521 mCurrentState.layersSortedByZ.removeAt(idx);
3522 mCurrentState.layersSortedByZ.add(layer);
3523 // we need traversal (state changed)
3524 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003525 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003526 }
3527 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003528 if (what & layer_state_t::eDeferTransaction_legacy) {
3529 if (s.barrierHandle_legacy != nullptr) {
3530 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3531 } else if (s.barrierGbp_legacy != nullptr) {
3532 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003533 if (authenticateSurfaceTextureLocked(gbp)) {
3534 const auto& otherLayer =
3535 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003536 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003537 } else {
3538 ALOGE("Attempt to defer transaction to to an"
3539 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003540 }
3541 }
chaviw8b3871a2017-11-01 17:41:01 -07003542 // We don't trigger a traversal here because if no other state is
3543 // changed, we don't want this to cause any more work
3544 }
3545 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003546 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003547 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003548 if (!hadParent) {
3549 mCurrentState.layersSortedByZ.remove(layer);
3550 }
chaviw8b3871a2017-11-01 17:41:01 -07003551 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003552 }
chaviw8b3871a2017-11-01 17:41:01 -07003553 }
3554 if (what & layer_state_t::eReparentChildren) {
3555 if (layer->reparentChildren(s.reparentHandle)) {
3556 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003557 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (what & layer_state_t::eDetachChildren) {
3560 layer->detachChildren();
3561 }
3562 if (what & layer_state_t::eOverrideScalingModeChanged) {
3563 layer->setOverrideScalingMode(s.overrideScalingMode);
3564 // We don't trigger a traversal here because if no other state is
3565 // changed, we don't want this to cause any more work
3566 }
Marissa Wall61c58622018-07-18 10:12:20 -07003567 if (what & layer_state_t::eTransformChanged) {
3568 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3569 }
3570 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3571 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3572 flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eCropChanged) {
3575 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eBufferChanged) {
3578 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eAcquireFenceChanged) {
3581 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3582 }
3583 if (what & layer_state_t::eDataspaceChanged) {
3584 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eHdrMetadataChanged) {
3587 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3590 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3591 }
3592 if (what & layer_state_t::eApiChanged) {
3593 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eSidebandStreamChanged) {
3596 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3597 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003598 return flags;
3599}
3600
chaviwca27f252018-02-06 16:46:39 -08003601void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3602 const layer_state_t& state = composerState.state;
3603 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3604
3605 sp<Layer> layer(client->getLayerUser(state.surface));
3606 if (layer == nullptr) {
3607 return;
3608 }
3609
chaviwca27f252018-02-06 16:46:39 -08003610 if (state.what & layer_state_t::eDestroySurface) {
3611 removeLayerLocked(mStateLock, layer);
3612 }
3613}
3614
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003616 const String8& name,
3617 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003619 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003620 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003622 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003623 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003624 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003626 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003627
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003628 status_t result = NO_ERROR;
3629
3630 sp<Layer> layer;
3631
Cody Northropbc755282017-03-31 12:00:08 -06003632 String8 uniqueName = getUniqueLayerName(name);
3633
Mathias Agopian3165cc22012-08-08 19:42:09 -07003634 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003635 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003636 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3637 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003639 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003640 case ISurfaceComposerClient::eFXSurfaceBufferState:
3641 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3642 break;
chaviw13fdc492017-06-27 12:40:18 -07003643 case ISurfaceComposerClient::eFXSurfaceColor:
3644 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003645 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003646 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003647 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003648 case ISurfaceComposerClient::eFXSurfaceContainer:
3649 result = createContainerLayer(client,
3650 uniqueName, w, h, flags,
3651 handle, &layer);
3652 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003653 default:
3654 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003655 break;
3656 }
3657
Dan Stoza7d89d062015-04-30 13:29:25 -07003658 if (result != NO_ERROR) {
3659 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003661
Chia-I Wuab0c3192017-08-01 11:29:00 -07003662 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3663 // TODO b/64227542
3664 if (windowType == 441731) {
3665 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3666 layer->setPrimaryDisplayOnly();
3667 }
3668
Albert Chaulk479c60c2017-01-27 14:21:34 -05003669 layer->setInfo(windowType, ownerUid);
3670
Robert Carr1f0a16a2016-10-24 16:27:39 -07003671 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003672 if (result != NO_ERROR) {
3673 return result;
3674 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003675 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003676
3677 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003678 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679}
3680
Cody Northropbc755282017-03-31 12:00:08 -06003681String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3682{
3683 bool matchFound = true;
3684 uint32_t dupeCounter = 0;
3685
3686 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3687 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3688
Dan Stoza436ccf32018-06-21 12:10:12 -07003689 // Grab the state lock since we're accessing mCurrentState
3690 Mutex::Autolock lock(mStateLock);
3691
Cody Northropbc755282017-03-31 12:00:08 -06003692 // Loop over layers until we're sure there is no matching name
3693 while (matchFound) {
3694 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003695 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003696 if (layer->getName() == uniqueName) {
3697 matchFound = true;
3698 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3699 }
3700 });
3701 }
3702
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003703 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3704 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003705
3706 return uniqueName;
3707}
3708
Marissa Wallfd668622018-05-10 10:21:13 -07003709status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3710 uint32_t w, uint32_t h, uint32_t flags,
3711 PixelFormat& format, sp<IBinder>* handle,
3712 sp<IGraphicBufferProducer>* gbp,
3713 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003715 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 case PIXEL_FORMAT_TRANSPARENT:
3717 case PIXEL_FORMAT_TRANSLUCENT:
3718 format = PIXEL_FORMAT_RGBA_8888;
3719 break;
3720 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003721 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003722 break;
3723 }
3724
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003725 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003726 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003727 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003729 *handle = layer->getHandle();
3730 *gbp = layer->getProducer();
3731 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003733
Marissa Wallfd668622018-05-10 10:21:13 -07003734 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003736}
3737
Marissa Wall61c58622018-07-18 10:12:20 -07003738status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3739 uint32_t w, uint32_t h, uint32_t flags,
3740 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003741 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003742 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003743 *handle = layer->getHandle();
3744 *outLayer = layer;
3745
3746 return NO_ERROR;
3747}
3748
chaviw13fdc492017-06-27 12:40:18 -07003749status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003751 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003752{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003753 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003754 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003755 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003756}
3757
Robert Carr6b3f6c52018-08-13 13:05:17 -07003758status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3759 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3760 sp<IBinder>* handle, sp<Layer>* outLayer)
3761{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003762 *outLayer =
3763 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003764 *handle = (*outLayer)->getHandle();
3765 return NO_ERROR;
3766}
3767
3768
Mathias Agopianac9fa422013-02-11 16:40:36 -08003769status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003770{
Robert Carr9524cb32017-02-13 11:32:32 -08003771 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003772 status_t err = NO_ERROR;
3773 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003774 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003775 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003776 err = removeLayer(l);
3777 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3778 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003779 }
3780 return err;
3781}
3782
Robert Carr2e102c92018-10-23 12:11:15 -07003783void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3784 mLayersPendingRemoval.add(layer);
3785 mLayersRemoved = true;
3786 setTransactionFlags(eTransactionNeeded);
3787}
3788
3789void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003790{
Robert Carr2e102c92018-10-23 12:11:15 -07003791 Mutex::Autolock lock(mStateLock);
3792 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003793}
3794
Mathias Agopianb60314a2012-04-10 22:09:54 -07003795// ---------------------------------------------------------------------------
3796
Andy McFadden13a082e2012-08-24 10:16:42 -07003797void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003798 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003799 if (!displayToken) return;
3800
Jesse Hall01e29052013-02-19 16:13:35 -08003801 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003802 Vector<ComposerState> state;
3803 Vector<DisplayState> displays;
3804 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003805 d.what = DisplayState::eDisplayProjectionChanged |
3806 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003807 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003808 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003809 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003810 d.frame.makeInvalid();
3811 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003812 d.width = 0;
3813 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003814 displays.add(d);
3815 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003816
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003817 const auto display = getDisplayDevice(displayToken);
3818 if (!display) return;
3819
3820 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3821
Dominik Laskowski075d3172018-05-24 15:50:06 -07003822 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003823 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003824 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003825
Brian Andersond0010582017-03-07 13:20:31 -08003826 // Use phase of 0 since phase is not known.
3827 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003828 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3829 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003830}
3831
3832void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003833 // Async since we may be called from the main thread.
3834 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003835}
3836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003837void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3838 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003839 if (display->isVirtual()) {
3840 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003841 return;
3842 }
3843
Dominik Laskowski075d3172018-05-24 15:50:06 -07003844 const auto displayId = display->getId();
3845 LOG_ALWAYS_FATAL_IF(!displayId);
3846
3847 ALOGD("Setting power mode %d on display %" PRIu64, mode, *displayId);
3848
3849 int currentMode = display->getPowerMode();
3850 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 return;
3852 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003853
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003854 display->setPowerMode(mode);
3855
Lloyd Pique4dccc412018-01-22 17:21:36 -08003856 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003857 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003858 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003859 if (idx < 0) {
3860 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3861 return;
3862 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003863 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003864 }
3865
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003866 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003867 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003868 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003869 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003870 if (mUseScheduler) {
3871 mScheduler->onScreenAcquired(mAppConnectionHandle);
3872 } else {
3873 mEventThread->onScreenAcquired();
3874 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003875 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003876 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003877
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003879 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003880 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003881
3882 struct sched_param param = {0};
3883 param.sched_priority = 1;
3884 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3885 ALOGW("Couldn't set SCHED_FIFO on display on");
3886 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003887 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003888 // Turn off the display
3889 struct sched_param param = {0};
3890 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3891 ALOGW("Couldn't set SCHED_OTHER on display off");
3892 }
3893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003894 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003895 if (mUseScheduler) {
3896 mScheduler->disableHardwareVsync(true);
3897 } else {
3898 disableHardwareVsync(true); // also cancels any in-progress resync
3899 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003900 if (mUseScheduler) {
3901 mScheduler->onScreenReleased(mAppConnectionHandle);
3902 } else {
3903 mEventThread->onScreenReleased();
3904 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003905 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003906
Dominik Laskowski075d3172018-05-24 15:50:06 -07003907 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003908 mVisibleRegionsDirty = true;
3909 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003910 } else if (mode == HWC_POWER_MODE_DOZE ||
3911 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003912 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003913 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003914 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003915 if (mUseScheduler) {
3916 mScheduler->onScreenAcquired(mAppConnectionHandle);
3917 } else {
3918 mEventThread->onScreenAcquired();
3919 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003920 resyncToHardwareVsync(true);
3921 }
3922 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3923 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003924 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003925 if (mUseScheduler) {
3926 mScheduler->disableHardwareVsync(true);
3927 } else {
3928 disableHardwareVsync(true); // also cancels any in-progress resync
3929 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003930 if (mUseScheduler) {
3931 mScheduler->onScreenReleased(mAppConnectionHandle);
3932 } else {
3933 mEventThread->onScreenReleased();
3934 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003935 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003936 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003937 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003938 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003939 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003940 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003941
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003942 if (display->isPrimary()) {
3943 mTimeStats.setPowerMode(mode);
3944 }
3945
Dominik Laskowski075d3172018-05-24 15:50:06 -07003946 ALOGD("Finished setting power mode %d on display %" PRIu64, mode, *displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003947}
3948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003949void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003950 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951 const auto display = getDisplayDevice(displayToken);
3952 if (!display) {
3953 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3954 displayToken.get());
3955 } else if (display->isVirtual()) {
3956 ALOGW("Attempt to set power mode %d for virtual display", mode);
3957 } else {
3958 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003959 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003960 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003961}
3962
3963// ---------------------------------------------------------------------------
3964
Lloyd Pique755e3192018-01-31 16:46:15 -08003965status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3966 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003968
Mathias Agopianbd115332013-04-18 16:41:04 -07003969 IPCThreadState* ipc = IPCThreadState::self();
3970 const int pid = ipc->getCallingPid();
3971 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003972
Mathias Agopianbd115332013-04-18 16:41:04 -07003973 if ((uid != AID_SHELL) &&
3974 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003975 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003976 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003978 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003979 // (this would indicate SF is stuck, but we want to be able to
3980 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003981 status_t err = mStateLock.timedLock(s2ns(1));
3982 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003983 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003984 result.appendFormat(
3985 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3986 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003987 }
3988
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003989 bool dumpAll = true;
3990 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003991 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003992
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003993 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003994 if ((index < numArgs) &&
3995 (args[index] == String16("--list"))) {
3996 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003997 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003998 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003999 }
4000
4001 if ((index < numArgs) &&
4002 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004003 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004004 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004005 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004006 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007
4008 if ((index < numArgs) &&
4009 (args[index] == String16("--latency-clear"))) {
4010 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004011 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004012 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004014
4015 if ((index < numArgs) &&
4016 (args[index] == String16("--dispsync"))) {
4017 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004018 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004019 dumpAll = false;
4020 }
Dan Stozab90cf072015-03-05 11:05:59 -08004021
4022 if ((index < numArgs) &&
4023 (args[index] == String16("--static-screen"))) {
4024 index++;
4025 dumpStaticScreenStats(result);
4026 dumpAll = false;
4027 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004028
4029 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004030 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004031 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004032 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004033 dumpAll = false;
4034 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004035
4036 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4037 index++;
4038 dumpWideColorInfo(result);
4039 dumpAll = false;
4040 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004041
4042 if ((index < numArgs) &&
4043 (args[index] == String16("--enable-layer-stats"))) {
4044 index++;
4045 mLayerStats.enable();
4046 dumpAll = false;
4047 }
4048
4049 if ((index < numArgs) &&
4050 (args[index] == String16("--disable-layer-stats"))) {
4051 index++;
4052 mLayerStats.disable();
4053 dumpAll = false;
4054 }
4055
4056 if ((index < numArgs) &&
4057 (args[index] == String16("--clear-layer-stats"))) {
4058 index++;
4059 mLayerStats.clear();
4060 dumpAll = false;
4061 }
4062
4063 if ((index < numArgs) &&
4064 (args[index] == String16("--dump-layer-stats"))) {
4065 index++;
4066 mLayerStats.dump(result);
4067 dumpAll = false;
4068 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004069
4070 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004071 (args[index] == String16("--frame-composition"))) {
4072 index++;
4073 dumpFrameCompositionInfo(result);
4074 dumpAll = false;
4075 }
4076
4077 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004078 (args[index] == String16("--display-identification"))) {
4079 index++;
4080 dumpDisplayIdentificationData(result);
4081 dumpAll = false;
4082 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004083
4084 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4085 index++;
4086 mTimeStats.parseArgs(asProto, args, index, result);
4087 dumpAll = false;
4088 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004090
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004091 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004092 if (asProto) {
4093 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4094 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4095 } else {
4096 dumpAllLocked(args, index, result);
4097 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004098 }
4099
Mathias Agopian9795c422009-08-26 16:36:26 -07004100 if (locked) {
4101 mStateLock.unlock();
4102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103 }
4104 write(fd, result.string(), result.size());
4105 return NO_ERROR;
4106}
4107
Dan Stozac7014012014-02-14 15:03:43 -08004108void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4109 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004110{
Robert Carr2047fae2016-11-28 14:09:09 -08004111 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004112 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004113 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004114}
4115
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004116void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004117 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004118{
4119 String8 name;
4120 if (index < args.size()) {
4121 name = String8(args[index]);
4122 index++;
4123 }
4124
Dominik Laskowski075d3172018-05-24 15:50:06 -07004125 if (const auto displayId = getInternalDisplayId();
4126 displayId && getHwComposer().isConnected(*displayId)) {
4127 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004128 const nsecs_t period = activeConfig->getVsyncPeriod();
4129 result.appendFormat("%" PRId64 "\n", period);
4130 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004131
4132 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004133 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004134 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004135 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004136 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004137 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004138 }
Robert Carr2047fae2016-11-28 14:09:09 -08004139 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004140 }
4141}
4142
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004144 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004145{
4146 String8 name;
4147 if (index < args.size()) {
4148 name = String8(args[index]);
4149 index++;
4150 }
4151
Robert Carr2047fae2016-11-28 14:09:09 -08004152 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004154 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155 }
Robert Carr2047fae2016-11-28 14:09:09 -08004156 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004157
Svetoslavd85084b2014-03-20 10:28:31 -07004158 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004159}
4160
Jamie Gennis6547ff42013-07-16 20:12:42 -07004161// This should only be called from the main thread. Otherwise it would need
4162// the lock and should use mCurrentState rather than mDrawingState.
4163void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004164 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004165 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004166 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004167
4168 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4169}
4170
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004171void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004172{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004173 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004174
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004175 if (isLayerTripleBufferingDisabled())
4176 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004177
4178 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004179 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004180 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004181 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004182 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4183 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004184 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004185}
4186
Dan Stozab90cf072015-03-05 11:05:59 -08004187void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4188{
4189 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004190 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4191 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004192 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004193 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004194 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4195 b + 1, bucketTimeSec, percent);
4196 }
David Sodman4a36e932017-11-07 14:29:47 -08004197 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004198 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004199 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004200 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004201 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004202}
4203
Dan Stozae77c7662016-05-13 11:37:28 -07004204void SurfaceFlinger::recordBufferingStats(const char* layerName,
4205 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004206 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4207 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004208 for (const auto& segment : history) {
4209 if (!segment.usedThirdBuffer) {
4210 stats.twoBufferTime += segment.totalTime;
4211 }
4212 if (segment.occupancyAverage < 1.0f) {
4213 stats.doubleBufferedTime += segment.totalTime;
4214 } else if (segment.occupancyAverage < 2.0f) {
4215 stats.tripleBufferedTime += segment.totalTime;
4216 }
4217 ++stats.numSegments;
4218 stats.totalTime += segment.totalTime;
4219 }
4220}
4221
Brian Andersond6927fb2016-07-23 23:37:30 -07004222void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4223 result.appendFormat("Layer frame timestamps:\n");
4224
4225 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4226 const size_t count = currentLayers.size();
4227 for (size_t i=0 ; i<count ; i++) {
4228 currentLayers[i]->dumpFrameEvents(result);
4229 }
4230}
4231
Dan Stozae77c7662016-05-13 11:37:28 -07004232void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4233 result.append("Buffering stats:\n");
4234 result.append(" [Layer name] <Active time> <Two buffer> "
4235 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004236 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004237 typedef std::tuple<std::string, float, float, float> BufferTuple;
4238 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004239 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004240 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004241 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004242 if (stats.numSegments == 0) {
4243 continue;
4244 }
4245 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4246 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4247 stats.totalTime;
4248 float doubleBufferRatio = static_cast<float>(
4249 stats.doubleBufferedTime) / stats.totalTime;
4250 float tripleBufferRatio = static_cast<float>(
4251 stats.tripleBufferedTime) / stats.totalTime;
4252 sorted.insert({activeTime, {name, twoBufferRatio,
4253 doubleBufferRatio, tripleBufferRatio}});
4254 }
4255 for (const auto& sortedPair : sorted) {
4256 float activeTime = sortedPair.first;
4257 const BufferTuple& values = sortedPair.second;
4258 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4259 std::get<0>(values).c_str(), activeTime,
4260 std::get<1>(values), std::get<2>(values),
4261 std::get<3>(values));
4262 }
4263 result.append("\n");
4264}
4265
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004266void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004267 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004268 const auto displayId = display->getId();
4269 if (!displayId) {
4270 continue;
4271 }
4272 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004273 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004274 continue;
4275 }
4276
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 result.appendFormat("Display %" PRIu64 " (HWC display %" PRIu64 "): ", *displayId,
4278 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004279 uint8_t port;
4280 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004281 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004282 result.append("no identification data\n");
4283 continue;
4284 }
4285
4286 if (!isEdid(data)) {
4287 result.append("unknown identification data: ");
4288 for (uint8_t byte : data) {
4289 result.appendFormat("%x ", byte);
4290 }
4291 result.append("\n");
4292 continue;
4293 }
4294
4295 const auto edid = parseEdid(data);
4296 if (!edid) {
4297 result.append("invalid EDID: ");
4298 for (uint8_t byte : data) {
4299 result.appendFormat("%x ", byte);
4300 }
4301 result.append("\n");
4302 continue;
4303 }
4304
4305 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4306 result.append(edid->displayName.data(), edid->displayName.length());
4307 result.append("\"\n");
4308 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004309}
4310
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004311void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004312 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4313 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004314 result.appendFormat("DisplayColorSetting: %s\n",
4315 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004316
4317 // TODO: print out if wide-color mode is active or not
4318
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004319 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004320 const auto displayId = display->getId();
4321 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004322 continue;
4323 }
4324
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 result.appendFormat("Display %" PRIu64 " color modes:\n", *displayId);
4326 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004327 for (auto&& mode : modes) {
4328 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4329 }
4330
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004331 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004332 result.appendFormat(" Current color mode: %s (%d)\n",
4333 decodeColorMode(currentMode).c_str(), currentMode);
4334 }
4335 result.append("\n");
4336}
4337
David Sodman7e4ae112018-02-09 15:02:28 -08004338void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4339 std::string stringResult;
4340
4341 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004342 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4343 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004344 continue;
4345 }
4346
Dominik Laskowski05275f12018-11-01 15:03:24 -07004347 const auto& compositionInfoList = it->second;
4348 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004349 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4350 for (const auto& compositionInfo : compositionInfoList) {
4351 compositionInfo.dump(stringResult, nullptr);
4352 stringResult += base::StringPrintf("\n");
4353 }
4354 }
4355
4356 result.append(stringResult.c_str());
4357}
4358
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004359LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004360 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004361 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4362 const State& state = useDrawing ? mDrawingState : mCurrentState;
4363 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004364 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004365 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004366 });
4367
4368 return layersProto;
4369}
4370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004372 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004373
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004374 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004375 resolution->set_w(display.getWidth());
4376 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004377
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004378 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4379 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4380 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004381
Dominik Laskowski075d3172018-05-24 15:50:06 -07004382 const auto displayId = display.getId();
4383 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004384 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004385 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004386 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004387 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004388 }
4389 });
4390
4391 return layersProto;
4392}
4393
Mathias Agopian74d211a2013-04-22 16:55:35 +02004394void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4395 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004397 bool colorize = false;
4398 if (index < args.size()
4399 && (args[index] == String16("--color"))) {
4400 colorize = true;
4401 index++;
4402 }
4403
4404 Colorizer colorizer(colorize);
4405
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406 // figure out if we're stuck somewhere
4407 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4410
4411 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004412 * Dump library configuration.
4413 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004414
4415 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004416 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004417 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004418 appendSfConfigString(result);
4419 appendUiConfigString(result);
4420 appendGuiConfigString(result);
4421 result.append("\n");
4422
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423 result.append("\nDisplay identification data:\n");
4424 dumpDisplayIdentificationData(result);
4425
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004426 result.append("\nWide-Color information:\n");
4427 dumpWideColorInfo(result);
4428
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004429 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004430 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004431 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004432 result.append(SyncFeatures::getInstance().toString());
4433 result.append("\n");
4434
Andy McFadden41d67d72014-04-25 16:58:34 -07004435 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004436 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004437 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004438
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004439 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4440 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004441 if (const auto displayId = getInternalDisplayId();
4442 displayId && getHwComposer().isConnected(*displayId)) {
4443 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
4444 result.appendFormat("Display %" PRIu64 ": app phase %" PRId64 " ns, "
4445 "sf phase %" PRId64 " ns, "
4446 "early app phase %" PRId64 " ns, "
4447 "early sf phase %" PRId64 " ns, "
4448 "early app gl phase %" PRId64 " ns, "
4449 "early sf gl phase %" PRId64 " ns, "
4450 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4451 *displayId, vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset,
4452 sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4453 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004455 result.append("\n");
4456
Dan Stozab90cf072015-03-05 11:05:59 -08004457 // Dump static screen stats
4458 result.append("\n");
4459 dumpStaticScreenStats(result);
4460 result.append("\n");
4461
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004462 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4463
Dan Stozae77c7662016-05-13 11:37:28 -07004464 dumpBufferingStats(result);
4465
Andy McFadden4803b742012-09-24 19:07:20 -07004466 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467 * Dump the visible layer list
4468 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004469 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004470 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004471 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4472 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004473 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004474
Chia-I Wu2f884132018-09-13 15:17:58 -07004475 {
4476 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4477 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4478 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4479 result.append("\n");
4480 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004481
David Sodman7e4ae112018-02-09 15:02:28 -08004482 result.append("\nFrame-Composition information:\n");
4483 dumpFrameCompositionInfo(result);
4484 result.append("\n");
4485
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004486 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004487 * Dump Display state
4488 */
4489
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004490 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004491 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004492 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004493 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004494 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004495 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004496 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004497
4498 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004499 * Dump SurfaceFlinger global state
4500 */
4501
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004502 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004503 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004504 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004505
David Sodmanbc815282017-11-05 18:57:52 -08004506 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004507
Dominik Laskowski075d3172018-05-24 15:50:06 -07004508 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004509 display->undefinedRegion.dump(result, "undefinedRegion");
4510 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4511 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004512 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004513 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004514 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004515 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004516
Dominik Laskowski075d3172018-05-24 15:50:06 -07004517 if (const auto displayId = getInternalDisplayId();
4518 displayId && getHwComposer().isConnected(*displayId)) {
4519 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004520 result.appendFormat(" refresh-rate : %f fps\n"
4521 " x-dpi : %f\n"
4522 " y-dpi : %f\n",
4523 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4524 activeConfig->getDpiY());
4525 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526
Mathias Agopian74d211a2013-04-22 16:55:35 +02004527 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004528 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004529
Ana Krulec98b5b242018-08-10 15:03:23 -07004530 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004531 /*
4532 * VSYNC state
4533 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004534 if (mUseScheduler) {
4535 mScheduler->dump(mAppConnectionHandle, result);
4536 } else {
4537 mEventThread->dump(result);
4538 }
Dan Stozae22aec72016-08-01 13:20:59 -07004539 result.append("\n");
4540
4541 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004542 * Tracing state
4543 */
4544 mTracing.dump(result);
4545 result.append("\n");
4546
4547 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004548 * HWC layer minidump
4549 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004550 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004551 const auto displayId = display->getId();
4552 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004553 continue;
4554 }
4555
Dominik Laskowski075d3172018-05-24 15:50:06 -07004556 result.appendFormat("Display %" PRIu64 " HWC layers:\n", *displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004557 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004558 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004559 result.append("\n");
4560 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561
4562 /*
4563 * Dump HWComposer state
4564 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004565 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004566 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004568 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004569 result.appendFormat(" h/w composer %s\n",
4570 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004571 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004572
4573 /*
4574 * Dump gralloc state
4575 */
4576 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4577 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004578
4579 /*
4580 * Dump VrFlinger state if in use.
4581 */
4582 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4583 result.append("VrFlinger state:\n");
4584 result.append(mVrFlinger->Dump().c_str());
4585 result.append("\n");
4586 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004587}
4588
Dominik Laskowski075d3172018-05-24 15:50:06 -07004589const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004590 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004591 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004592 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004593 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004594 }
4595 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004596
Dominik Laskowski075d3172018-05-24 15:50:06 -07004597 ALOGE("%s: Invalid display %" PRIu64, __FUNCTION__, displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004598 static const Vector<sp<Layer>> empty;
4599 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004600}
4601
Keun young Park63f165f2012-08-31 10:53:36 -07004602bool SurfaceFlinger::startDdmConnection()
4603{
4604 void* libddmconnection_dso =
4605 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4606 if (!libddmconnection_dso) {
4607 return false;
4608 }
4609 void (*DdmConnection_start)(const char* name);
4610 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004611 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004612 if (!DdmConnection_start) {
4613 dlclose(libddmconnection_dso);
4614 return false;
4615 }
4616 (*DdmConnection_start)(getServiceName());
4617 return true;
4618}
4619
Chia-I Wu28f320b2018-05-03 11:02:56 -07004620void SurfaceFlinger::updateColorMatrixLocked() {
4621 mat4 colorMatrix;
4622 if (mGlobalSaturationFactor != 1.0f) {
4623 // Rec.709 luma coefficients
4624 float3 luminance{0.213f, 0.715f, 0.072f};
4625 luminance *= 1.0f - mGlobalSaturationFactor;
4626 mat4 saturationMatrix = mat4(
4627 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4628 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4629 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4630 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4631 );
4632 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4633 } else {
4634 colorMatrix = mClientColorMatrix * mDaltonizer();
4635 }
4636
4637 if (mCurrentState.colorMatrix != colorMatrix) {
4638 mCurrentState.colorMatrix = colorMatrix;
4639 mCurrentState.colorMatrixChanged = true;
4640 setTransactionFlags(eTransactionNeeded);
4641 }
4642}
4643
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004644status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004645#pragma clang diagnostic push
4646#pragma clang diagnostic error "-Wswitch-enum"
4647 switch (static_cast<ISurfaceComposerTag>(code)) {
4648 // These methods should at minimum make sure that the client requested
4649 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004650 case BOOT_FINISHED:
4651 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004652 case CREATE_CONNECTION:
4653 case CREATE_DISPLAY:
4654 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004655 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004656 case GET_ACTIVE_COLOR_MODE:
4657 case GET_ANIMATION_FRAME_STATS:
4658 case GET_HDR_CAPABILITIES:
4659 case SET_ACTIVE_CONFIG:
4660 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004661 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004662 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004663 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4664 IPCThreadState* ipc = IPCThreadState::self();
4665 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4666 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004667 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004668 }
Robert Carr1db73f62016-12-21 12:58:51 -08004669 return OK;
4670 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004671 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004672 IPCThreadState* ipc = IPCThreadState::self();
4673 const int pid = ipc->getCallingPid();
4674 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004675 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4676 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004677 return PERMISSION_DENIED;
4678 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004679 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004680 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004681 // Used by apps to hook Choreographer to SurfaceFlinger.
4682 case CREATE_DISPLAY_EVENT_CONNECTION:
4683 // The following calls are currently used by clients that do not
4684 // request necessary permissions. However, they do not expose any secret
4685 // information, so it is OK to pass them.
4686 case AUTHENTICATE_SURFACE:
4687 case GET_ACTIVE_CONFIG:
4688 case GET_BUILT_IN_DISPLAY:
4689 case GET_DISPLAY_COLOR_MODES:
4690 case GET_DISPLAY_CONFIGS:
4691 case GET_DISPLAY_STATS:
4692 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4693 // Calling setTransactionState is safe, because you need to have been
4694 // granted a reference to Client* and Handle* to do anything with it.
4695 case SET_TRANSACTION_STATE:
4696 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004697 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004698 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004699 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004700 return OK;
4701 }
4702 case CAPTURE_LAYERS:
4703 case CAPTURE_SCREEN: {
4704 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004705 IPCThreadState* ipc = IPCThreadState::self();
4706 const int pid = ipc->getCallingPid();
4707 const int uid = ipc->getCallingUid();
4708 if ((uid != AID_GRAPHICS) &&
4709 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4710 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4711 return PERMISSION_DENIED;
4712 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004713 return OK;
4714 }
4715 // The following codes are deprecated and should never be allowed to access SF.
4716 case CONNECT_DISPLAY_UNUSED:
4717 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4718 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4719 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004721 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722
4723 // These codes are used for the IBinder protocol to either interrogate the recipient
4724 // side of the transaction for its canonical interface descriptor or to dump its state.
4725 // We let them pass by default.
4726 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4727 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4728 code == IBinder::SYSPROPS_TRANSACTION) {
4729 return OK;
4730 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004731 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004733 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004734 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4735 return OK;
4736 }
4737 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4738 return PERMISSION_DENIED;
4739#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004740}
4741
Ana Krulec13be8ad2018-08-21 02:43:56 +00004742status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4743 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004744 status_t credentialCheck = CheckTransactCodeCredentials(code);
4745 if (credentialCheck != OK) {
4746 return credentialCheck;
4747 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004749 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4750 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004751 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004752 IPCThreadState* ipc = IPCThreadState::self();
4753 const int uid = ipc->getCallingUid();
4754 if (CC_UNLIKELY(uid != AID_SYSTEM
4755 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004756 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004757 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004758 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004759 return PERMISSION_DENIED;
4760 }
4761 int n;
4762 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004763 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004764 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 return NO_ERROR;
4766 case 1002: // SHOW_UPDATES
4767 n = data.readInt32();
4768 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004769 invalidateHwcGeometry();
4770 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004772 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004773 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004774 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004775 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004776 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004777 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004778 setTransactionFlags(
4779 eTransactionNeeded|
4780 eDisplayTransactionNeeded|
4781 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004782 return NO_ERROR;
4783 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004784 case 1006:{ // send empty update
4785 signalRefresh();
4786 return NO_ERROR;
4787 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004788 case 1008: // toggle use of hw composer
4789 n = data.readInt32();
4790 mDebugDisableHWC = n ? 1 : 0;
4791 invalidateHwcGeometry();
4792 repaintEverything();
4793 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004794 case 1009: // toggle use of transform hint
4795 n = data.readInt32();
4796 mDebugDisableTransformHint = n ? 1 : 0;
4797 invalidateHwcGeometry();
4798 repaintEverything();
4799 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004800 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004801 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 reply->writeInt32(0);
4803 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004804 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004805 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004806 return NO_ERROR;
4807 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004808 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004809 if (!display) {
4810 return NAME_NOT_FOUND;
4811 }
4812
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004813 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004814 return NO_ERROR;
4815 }
4816 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004817 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004818 // daltonize
4819 n = data.readInt32();
4820 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004821 case 1:
4822 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4823 break;
4824 case 2:
4825 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4826 break;
4827 case 3:
4828 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4829 break;
4830 default:
4831 mDaltonizer.setType(ColorBlindnessType::None);
4832 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004833 }
4834 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004835 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004836 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004837 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004838 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004839
4840 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004841 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004842 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004843 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004844 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004845 // apply a color matrix
4846 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004847 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004848 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004849 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004850 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004851 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004852 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004853 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004854 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004855 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004856 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004857
4858 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4859 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004860 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004861 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4862 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4863 }
4864
Chia-I Wu28f320b2018-05-03 11:02:56 -07004865 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004866 return NO_ERROR;
4867 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004868 // This is an experimental interface
4869 // Needs to be shifted to proper binder interface when we productize
4870 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004871 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004872 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004873 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004874 return NO_ERROR;
4875 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004876 case 1017: {
4877 n = data.readInt32();
4878 mForceFullDamage = static_cast<bool>(n);
4879 return NO_ERROR;
4880 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004881 case 1018: { // Modify Choreographer's phase offset
4882 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004883 if (mUseScheduler) {
4884 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4885 } else {
4886 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4887 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004888 return NO_ERROR;
4889 }
4890 case 1019: { // Modify SurfaceFlinger's phase offset
4891 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004892 if (mUseScheduler) {
4893 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4894 } else {
4895 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4896 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004897 return NO_ERROR;
4898 }
Irvel468051e2016-06-13 16:44:44 -07004899 case 1020: { // Layer updates interceptor
4900 n = data.readInt32();
4901 if (n) {
4902 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004903 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004904 }
4905 else{
4906 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004907 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004908 }
4909 return NO_ERROR;
4910 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004911 case 1021: { // Disable HWC virtual displays
4912 n = data.readInt32();
4913 mUseHwcVirtualDisplays = !n;
4914 return NO_ERROR;
4915 }
Romain Guy0147a172017-06-01 13:53:56 -07004916 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004917 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004918 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004919
Chia-I Wu28f320b2018-05-03 11:02:56 -07004920 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004921 return NO_ERROR;
4922 }
Romain Guy54f154a2017-10-24 21:40:32 +01004923 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004924 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004925 invalidateHwcGeometry();
4926 repaintEverything();
4927 return NO_ERROR;
4928 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004929 // Deprecate, use 1030 to check whether the device is color managed.
4930 case 1024: {
4931 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004932 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004933 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004934 n = data.readInt32();
4935 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004936 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004937 mTracing.enable();
4938 doTracing("tracing.enable");
4939 reply->writeInt32(NO_ERROR);
4940 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004941 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004942 status_t err = mTracing.disable();
4943 reply->writeInt32(err);
4944 }
4945 return NO_ERROR;
4946 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004947 case 1026: { // Get layer tracing status
4948 reply->writeBool(mTracing.isEnabled());
4949 return NO_ERROR;
4950 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004951 // Is a DisplayColorSetting supported?
4952 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004953 const auto display = getDefaultDisplayDevice();
4954 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004955 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004956 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004957
4958 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4959 switch (setting) {
4960 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004961 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004962 break;
4963 case DisplayColorSetting::UNMANAGED:
4964 reply->writeBool(true);
4965 break;
4966 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004967 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004968 break;
4969 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004970 reply->writeBool(
4971 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004972 break;
4973 }
4974 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004975 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004976 // Is VrFlinger active?
4977 case 1028: {
4978 Mutex::Autolock _l(mStateLock);
4979 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4980 return NO_ERROR;
4981 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004982 // Is device color managed?
4983 case 1030: {
4984 reply->writeBool(useColorManagement);
4985 return NO_ERROR;
4986 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004987 // Override default composition data space
4988 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4989 // && adb shell stop zygote && adb shell start zygote
4990 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4991 // adb shell stop zygote && adb shell start zygote
4992 case 1031: {
4993 Mutex::Autolock _l(mStateLock);
4994 n = data.readInt32();
4995 if (n) {
4996 n = data.readInt32();
4997 if (n) {
4998 Dataspace dataspace = static_cast<Dataspace>(n);
4999 if (!validateCompositionDataspace(dataspace)) {
5000 return BAD_VALUE;
5001 }
5002 mDefaultCompositionDataspace = dataspace;
5003 }
5004 n = data.readInt32();
5005 if (n) {
5006 Dataspace dataspace = static_cast<Dataspace>(n);
5007 if (!validateCompositionDataspace(dataspace)) {
5008 return BAD_VALUE;
5009 }
5010 mWideColorGamutCompositionDataspace = dataspace;
5011 }
5012 } else {
5013 // restore composition data space.
5014 mDefaultCompositionDataspace = defaultCompositionDataspace;
5015 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5016 }
5017 return NO_ERROR;
5018 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 }
5020 }
5021 return err;
5022}
5023
Steven Thomas6d8110b2017-08-31 18:24:21 -07005024void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005025 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005026 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005027}
5028
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005029// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5030class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005031public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005032 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5033 ~WindowDisconnector() {
5034 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005035 }
5036
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005037private:
5038 ANativeWindow* mWindow;
5039 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005040};
5041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005042status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005043 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5044 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005045 uint32_t reqWidth, uint32_t reqHeight,
5046 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005047 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005048 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005050 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005051
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005052 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5053
Chia-I Wu20261cb2018-08-23 12:55:44 -07005054 sp<DisplayDevice> display;
5055 {
5056 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005057
Chia-I Wu20261cb2018-08-23 12:55:44 -07005058 display = getDisplayDeviceLocked(displayToken);
5059 if (!display) return BAD_VALUE;
5060
Chia-I Wucb023152018-08-28 12:57:23 -07005061 // set the requested width/height to the logical display viewport size
5062 // by default
5063 if (reqWidth == 0 || reqHeight == 0) {
5064 reqWidth = uint32_t(display->getViewport().width());
5065 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005066 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005067 }
5068
Peiyong Lin0e003c92018-09-17 11:09:51 -07005069 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5070 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005071
5072 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005073 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005074 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5075 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005076}
5077
5078status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005079 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5080 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005081 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005082 ATRACE_CALL();
5083
5084 class LayerRenderArea : public RenderArea {
5085 public:
Robert Carr578038f2018-03-09 12:25:24 -08005086 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005087 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5088 bool childrenOnly)
5089 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005090 mLayer(layer),
5091 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005092 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005093 mFlinger(flinger),
5094 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005095 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005096 Rect getBounds() const override {
5097 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005098 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005099 }
Marissa Wall61c58622018-07-18 10:12:20 -07005100 int getHeight() const override {
5101 return mLayer->getActiveHeight(mLayer->getDrawingState());
5102 }
5103 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005104 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005105 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005106 Rect getSourceCrop() const override {
5107 if (mCrop.isEmpty()) {
5108 return getBounds();
5109 } else {
5110 return mCrop;
5111 }
5112 }
Robert Carr578038f2018-03-09 12:25:24 -08005113 class ReparentForDrawing {
5114 public:
5115 const sp<Layer>& oldParent;
5116 const sp<Layer>& newParent;
5117
5118 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5119 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005120 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005121 }
Robert Carr15eae092018-03-23 13:43:53 -07005122 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005123 };
5124
5125 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005126 const Rect sourceCrop = getSourceCrop();
5127 // no need to check rotation because there is none
5128 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5129 sourceCrop.height() != getReqHeight();
5130
Robert Carr578038f2018-03-09 12:25:24 -08005131 if (!mChildrenOnly) {
5132 mTransform = mLayer->getTransform().inverse();
5133 drawLayers();
5134 } else {
5135 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005136 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005137 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5138 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005139
5140 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5141 drawLayers();
5142 }
5143 }
chaviwa76b2712017-09-20 12:02:26 -07005144
chaviwa76b2712017-09-20 12:02:26 -07005145 private:
chaviw7206d492017-11-10 16:16:12 -08005146 const sp<Layer> mLayer;
5147 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005148
5149 // In the "childrenOnly" case we reparent the children to a screenshot
5150 // layer which has no properties set and which does not draw.
5151 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005152 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005153 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005154
5155 SurfaceFlinger* mFlinger;
5156 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005157 };
5158
5159 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5160 auto parent = layerHandle->owner.promote();
5161
Robert Carr2e102c92018-10-23 12:11:15 -07005162 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005163 ALOGE("captureLayers called with a removed parent");
5164 return NAME_NOT_FOUND;
5165 }
5166
Robert Carr578038f2018-03-09 12:25:24 -08005167 const int uid = IPCThreadState::self()->getCallingUid();
5168 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5169 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5170 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5171 return PERMISSION_DENIED;
5172 }
5173
chaviw7206d492017-11-10 16:16:12 -08005174 Rect crop(sourceCrop);
5175 if (sourceCrop.width() <= 0) {
5176 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005177 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005178 }
5179
5180 if (sourceCrop.height() <= 0) {
5181 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005182 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005183 }
5184
5185 int32_t reqWidth = crop.width() * frameScale;
5186 int32_t reqHeight = crop.height() * frameScale;
5187
Chia-I Wu20261cb2018-08-23 12:55:44 -07005188 // really small crop or frameScale
5189 if (reqWidth <= 0) {
5190 reqWidth = 1;
5191 }
5192 if (reqHeight <= 0) {
5193 reqHeight = 1;
5194 }
5195
Peiyong Lin0e003c92018-09-17 11:09:51 -07005196 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005197
Robert Carr578038f2018-03-09 12:25:24 -08005198 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005199 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5200 if (!layer->isVisible()) {
5201 return;
Robert Carr578038f2018-03-09 12:25:24 -08005202 } else if (childrenOnly && layer == parent.get()) {
5203 return;
chaviwa76b2712017-09-20 12:02:26 -07005204 }
5205 visitor(layer);
5206 });
5207 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005208 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005209}
5210
5211status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5212 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005213 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005214 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005215 bool useIdentityTransform) {
5216 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005217
Peiyong Lin0e003c92018-09-17 11:09:51 -07005218 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005219 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5220 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005221 *outBuffer =
5222 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5223 static_cast<android_pixel_format>(reqPixelFormat), 1,
5224 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005225
5226 // This mutex protects syncFd and captureResult for communication of the return values from the
5227 // main thread back to this Binder thread
5228 std::mutex captureMutex;
5229 std::condition_variable captureCondition;
5230 std::unique_lock<std::mutex> captureLock(captureMutex);
5231 int syncFd = -1;
5232 std::optional<status_t> captureResult;
5233
Robert Carr03480e22018-01-04 16:02:06 -08005234 const int uid = IPCThreadState::self()->getCallingUid();
5235 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5236
Dominik Laskowski8c001672018-05-30 16:52:06 -07005237 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005238 // If there is a refresh pending, bug out early and tell the binder thread to try again
5239 // after the refresh.
5240 if (mRefreshPending) {
5241 ATRACE_NAME("Skipping screenshot for now");
5242 std::unique_lock<std::mutex> captureLock(captureMutex);
5243 captureResult = std::make_optional<status_t>(EAGAIN);
5244 captureCondition.notify_one();
5245 return;
5246 }
5247
5248 status_t result = NO_ERROR;
5249 int fd = -1;
5250 {
5251 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005252 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005253 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5254 useIdentityTransform, forSystem, &fd);
5255 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005256 }
5257
5258 {
5259 std::unique_lock<std::mutex> captureLock(captureMutex);
5260 syncFd = fd;
5261 captureResult = std::make_optional<status_t>(result);
5262 captureCondition.notify_one();
5263 }
5264 });
5265
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005266 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005268 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005269 while (*captureResult == EAGAIN) {
5270 captureResult.reset();
5271 result = postMessageAsync(message);
5272 if (result != NO_ERROR) {
5273 return result;
5274 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005275 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005276 }
5277 result = *captureResult;
5278 }
5279
5280 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005281 sync_wait(syncFd, -1);
5282 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005283 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005284
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005285 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005286}
5287
chaviwa76b2712017-09-20 12:02:26 -07005288void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005289 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005290 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005291 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005292
Lloyd Pique144e1162017-12-20 16:44:52 -08005293 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005294
chaviwa76b2712017-09-20 12:02:26 -07005295 const auto reqWidth = renderArea.getReqWidth();
5296 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005297 const auto sourceCrop = renderArea.getSourceCrop();
5298 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005299
Peiyong Lin0e003c92018-09-17 11:09:51 -07005300 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005301 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005302
Mathias Agopian180f10d2013-04-10 22:55:41 -07005303 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005304 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005305
5306 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005307 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005308 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005309
chaviw50da5042018-04-09 13:49:37 -07005310 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005311 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005312 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005313
chaviwa76b2712017-09-20 12:02:26 -07005314 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005315 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005316 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005317 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005318 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005319}
5320
chaviwa76b2712017-09-20 12:02:26 -07005321status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5322 TraverseLayersFunction traverseLayers,
5323 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005324 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005325 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005326 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005327 ATRACE_CALL();
5328
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005329 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005330
5331 traverseLayers([&](Layer* layer) {
5332 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5333 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005334
Robert Carr03480e22018-01-04 16:02:06 -08005335 // We allow the system server to take screenshots of secure layers for
5336 // use in situations like the Screen-rotation animation and place
5337 // the impetus on WindowManager to not persist them.
5338 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005339 ALOGW("FB is protected: PERMISSION_DENIED");
5340 return PERMISSION_DENIED;
5341 }
5342
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005343 // this binds the given EGLImage as a framebuffer for the
5344 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005345 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005346 if (bufferBond.getStatus() != NO_ERROR) {
5347 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005348 return INVALID_OPERATION;
5349 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005350
Dan Stozaabcda352017-06-01 14:37:39 -07005351 // this will in fact render into our dequeued buffer
5352 // via an FBO, which means we didn't have to create
5353 // an EGLSurface and therefore we're not
5354 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005355 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005356
Alec Mouri492bc572018-09-11 21:40:04 +00005357 base::unique_fd syncFd = getRenderEngine().flush();
5358 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005359 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005360 }
Alec Mouri492bc572018-09-11 21:40:04 +00005361 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005362
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005363 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005364}
5365
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005366// ---------------------------------------------------------------------------
5367
Dan Stoza412903f2017-04-27 13:42:17 -07005368void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5369 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005370}
5371
Dan Stoza412903f2017-04-27 13:42:17 -07005372void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5373 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005374}
5375
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005376void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005377 const LayerVector::Visitor& visitor) {
5378 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005379 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005380 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005381 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005382 continue;
5383 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005384 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005385 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005386 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005387 return;
5388 }
chaviwa76b2712017-09-20 12:02:26 -07005389 if (!layer->isVisible()) {
5390 return;
5391 }
5392 visitor(layer);
5393 });
5394 }
5395}
5396
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005397}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005398
Lloyd Pique074e8122018-07-26 12:57:23 -07005399
Mathias Agopian3f844832013-08-07 21:24:32 -07005400#if defined(__gl_h_)
5401#error "don't include gl/gl.h in this file"
5402#endif
5403
5404#if defined(__gl2_h_)
5405#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005406#endif