blob: 2858b7b8b789ab17a9483ebcbece0352c2baa95c [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>
Alec Mouri8147b0e2018-10-09 20:57:19 -070048#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070051#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070052#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Robert Carr578038f2018-03-09 12:25:24 -080066#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070067#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070068#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020069#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080070#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020071#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080073#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070078#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070079#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070081#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070090#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091#include "Scheduler/EventControlThread.h"
92#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070093#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070095#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070098
David Sodman7e4ae112018-02-09 15:02:28 -080099#include "android-base/stringprintf.h"
100
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800102#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700103#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800104#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900105#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106
chaviw1d044282017-09-27 12:19:28 -0700107#include <layerproto/LayerProtoParser.h>
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700113using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700114using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700115using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700116using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
Steven Thomasb02664d2017-07-26 18:48:28 -0700118namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700119
120#pragma clang diagnostic push
121#pragma clang diagnostic error "-Wswitch-enum"
122
123bool isWideColorMode(const ColorMode colorMode) {
124 switch (colorMode) {
125 case ColorMode::DISPLAY_P3:
126 case ColorMode::ADOBE_RGB:
127 case ColorMode::DCI_P3:
128 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700129 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700130 case ColorMode::BT2100_PQ:
131 case ColorMode::BT2100_HLG:
132 return true;
133 case ColorMode::NATIVE:
134 case ColorMode::STANDARD_BT601_625:
135 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
136 case ColorMode::STANDARD_BT601_525:
137 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
138 case ColorMode::STANDARD_BT709:
139 case ColorMode::SRGB:
140 return false;
141 }
142 return false;
143}
144
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700145ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
146 switch (rotation) {
147 case ISurfaceComposer::eRotateNone:
148 return ui::Transform::ROT_0;
149 case ISurfaceComposer::eRotate90:
150 return ui::Transform::ROT_90;
151 case ISurfaceComposer::eRotate180:
152 return ui::Transform::ROT_180;
153 case ISurfaceComposer::eRotate270:
154 return ui::Transform::ROT_270;
155 }
156 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
157 return ui::Transform::ROT_0;
158}
159
Peiyong Linfca547f2018-07-09 13:03:33 -0700160#pragma clang diagnostic pop
161
Steven Thomasb02664d2017-07-26 18:48:28 -0700162class ConditionalLock {
163public:
164 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
165 if (lock) {
166 mMutex.lock();
167 }
168 }
169 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
170private:
171 Mutex& mMutex;
172 bool mLocked;
173};
Peiyong Linfca547f2018-07-09 13:03:33 -0700174
Peiyong Lin9d846a52018-11-05 13:18:20 -0800175// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
176bool validateCompositionDataspace(Dataspace dataspace) {
177 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
178}
179
Steven Thomasb02664d2017-07-26 18:48:28 -0700180} // namespace anonymous
181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182// ---------------------------------------------------------------------------
183
Mathias Agopian99b49842011-06-27 16:05:52 -0700184const String16 sHardwareTest("android.permission.HARDWARE_TEST");
185const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
186const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
187const String16 sDump("android.permission.DUMP");
188
189// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800190int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
191int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700192int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700193bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800194uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800195bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800196bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800197int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600198bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700199int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700200bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700201bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700202Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
203ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
204Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
205ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700206
Kalle Raitaa099a242017-01-11 11:17:29 -0800207std::string getHwcServiceName() {
208 char value[PROPERTY_VALUE_MAX] = {};
209 property_get("debug.sf.hwc_service_name", value, "default");
210 ALOGI("Using HWComposer service: '%s'", value);
211 return std::string(value);
212}
213
214bool useTrebleTestingOverride() {
215 char value[PROPERTY_VALUE_MAX] = {};
216 property_get("debug.sf.treble_testing_override", value, "false");
217 ALOGI("Treble testing override: '%s'", value);
218 return std::string(value) == "true";
219}
220
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800221std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
222 switch(displayColorSetting) {
223 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700224 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700226 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Enhanced");
229 default:
230 return std::string("Unknown ") +
231 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800232 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233}
234
David Sodmanbc815282017-11-05 18:57:52 -0800235SurfaceFlingerBE::SurfaceFlingerBE()
236 : mHwcServiceName(getHwcServiceName()),
237 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Pique90c115d2018-09-18 21:39:42 -0700244SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
245 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800246 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700247 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700248 mTransactionPending(false),
249 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700250 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700251 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInTransaction(0),
262 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700263 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700264 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700265 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800266 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800267 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800268 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700269 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Lloyd Pique90c115d2018-09-18 21:39:42 -0700272SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
273 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800274 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800275
276 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
278
279 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
281
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700285 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
287
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700288 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
290
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800291 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
293
Steven Thomas050b2c82017-03-06 11:45:16 -0800294 // Vr flinger is only enabled on Daydream ready devices.
295 useVrFlinger = getBool< ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::useVrFlinger>(false);
297
Fabien Sanglard1971b632017-03-10 14:50:03 -0800298 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
300
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600301 hasWideColorDisplay =
302 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700303 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700304 getBool<V1_2::ISurfaceFlingerConfigs,
305 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
306
307 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
308 if (surfaceFlingerConfigsServiceV1_2) {
309 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700310 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
311 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
312 defaultCompositionDataspace = tmpDefaultDataspace;
313 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
314 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
315 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
316 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700317 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800318 mDefaultCompositionDataspace = defaultCompositionDataspace;
319 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600320
Peiyong Linb3839ad2018-09-05 15:37:19 -0700321 useContextPriority = getBool<ISurfaceFlingerConfigs,
322 &ISurfaceFlingerConfigs::useContextPriority>(true);
323
Iris Chang7501ed62018-04-30 14:45:42 +0800324 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700325 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
326 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800327 V1_1::DisplayOrientation::ORIENTATION_0);
328
329 switch (primaryDisplayOrientation) {
330 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800344
Lloyd Pique90c115d2018-09-18 21:39:42 -0700345 mPrimaryDispSync =
346 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
347 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349 // debugging stuff...
350 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351
Mathias Agopianb4b17302013-03-20 18:36:41 -0700352 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700353 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700354
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355 property_get("debug.sf.showupdates", value, "0");
356 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700357
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700358 property_get("debug.sf.ddms", value, "0");
359 mDebugDDMS = atoi(value);
360 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700361 if (!startDdmConnection()) {
362 // start failed, and DDMS debugging not enabled
363 mDebugDDMS = 0;
364 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700365 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700366 ALOGI_IF(mDebugRegion, "showupdates enabled");
367 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700368
369 property_get("debug.sf.disable_backpressure", value, "0");
370 mPropagateBackpressure = !atoi(value);
371 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700372
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800373 property_get("debug.sf.enable_hwc_vds", value, "0");
374 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800375 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800376
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800377 property_get("ro.sf.disable_triple_buffer", value, "1");
378 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800379 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700380
Yiwei Zhang243b3782018-05-15 17:40:04 -0700381 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700382 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
383 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
384
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200385 property_get("debug.sf.early_phase_offset_ns", value, "-1");
386 const int earlySfOffsetNs = atoi(value);
387
388 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
389 const int earlyGlSfOffsetNs = atoi(value);
390
391 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
392 const int earlyAppOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
395 const int earlyGlAppOffsetNs = atoi(value);
396
Ana Krulec98b5b242018-08-10 15:03:23 -0700397 property_get("debug.sf.use_scheduler", value, "0");
398 mUseScheduler = atoi(value);
399
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200400 const VSyncModulator::Offsets earlyOffsets =
401 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
402 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
403 const VSyncModulator::Offsets earlyGlOffsets =
404 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
405 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
406 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
407 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700408
Romain Guy11d63f42017-07-20 12:47:14 -0700409 // We should be reading 'persist.sys.sf.color_saturation' here
410 // but since /data may be encrypted, we need to wait until after vold
411 // comes online to attempt to read the property. The property is
412 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800413
414 if (useTrebleTestingOverride()) {
415 // Without the override SurfaceFlinger cannot connect to HIDL
416 // services that are not listed in the manifests. Considered
417 // deriving the setting from the set service name, but it
418 // would be brittle if the name that's not 'default' is used
419 // for production purposes later on.
420 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424void SurfaceFlinger::onFirstRef()
425{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800426 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427}
428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429SurfaceFlinger::~SurfaceFlinger()
430{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431}
432
Dan Stozac7014012014-02-14 15:03:43 -0800433void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434{
435 // the window manager died on us. prepare its eulogy.
436
Andy McFadden13a082e2012-08-24 10:16:42 -0700437 // restore initial conditions (default device unblank, etc)
438 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439
440 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700441 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442}
443
Robert Carr1db73f62016-12-21 12:58:51 -0800444static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700445 status_t err = client->initCheck();
446 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800447 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448 }
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return nullptr;
450}
451
452sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
453 return initClient(new Client(this));
454}
455
456sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
457 const sp<IGraphicBufferProducer>& gbp) {
458 if (authenticateSurfaceTexture(gbp) == false) {
459 return nullptr;
460 }
461 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
462 if (layer == nullptr) {
463 return nullptr;
464 }
465
466 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800467}
468
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700469sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
470 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471{
472 class DisplayToken : public BBinder {
473 sp<SurfaceFlinger> flinger;
474 virtual ~DisplayToken() {
475 // no more references, this display must be terminated
476 Mutex::Autolock _l(flinger->mStateLock);
477 flinger->mCurrentState.displays.removeItem(this);
478 flinger->setTransactionFlags(eDisplayTransactionNeeded);
479 }
480 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700481 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700482 : flinger(flinger) {
483 }
484 };
485
486 sp<BBinder> token = new DisplayToken(this);
487
488 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 // Display ID is assigned when virtual display is allocated by HWC.
490 DisplayDeviceState state;
491 state.isSecure = secure;
492 state.displayName = displayName;
493 mCurrentState.displays.add(token, state);
494 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 return token;
496}
497
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700498void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 Mutex::Autolock _l(mStateLock);
500
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
502 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 return;
505 }
506
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
508 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 ALOGE("destroyDisplay called for non-virtual display");
510 return;
511 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512 mInterceptor->saveDisplayDeletion(state.sequenceId);
513 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 setTransactionFlags(eDisplayTransactionNeeded);
515}
516
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700518 std::optional<DisplayId> displayId;
519
520 if (id == HWC_DISPLAY_PRIMARY) {
521 displayId = getInternalDisplayId();
522 } else if (id == HWC_DISPLAY_EXTERNAL) {
523 displayId = getExternalDisplayId();
524 }
525
526 if (!displayId) {
527 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800528 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700530
531 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700532}
533
Ady Abraham37965d42018-11-01 13:43:32 -0700534status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
535 if (!outGetColorManagement) {
536 return BAD_VALUE;
537 }
538 *outGetColorManagement = useColorManagement;
539 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700540}
541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542void SurfaceFlinger::bootFinished()
543{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700544 if (mStartPropertySetThread->join() != NO_ERROR) {
545 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547 const nsecs_t now = systemTime();
548 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000549 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550
551 // wait patiently for the window manager death
552 const String16 name("window");
553 sp<IBinder> window(defaultServiceManager()->getService(name));
554 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700555 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556 }
557
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 if (mVrFlinger) {
559 mVrFlinger->OnBootFinished();
560 }
561
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700563 // formerly we would just kill the process, but we now ask it to exit so it
564 // can choose where to stop the animation.
565 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700566
567 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
568 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
569 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700570
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800571 postMessageAsync(new LambdaMessage([this] {
572 readPersistentProperties();
573 mBootStage = BootStage::FINISHED;
574 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575}
576
Dan Stoza436ccf32018-06-21 12:10:12 -0700577uint32_t SurfaceFlinger::getNewTexture() {
578 {
579 std::lock_guard lock(mTexturePoolMutex);
580 if (!mTexturePool.empty()) {
581 uint32_t name = mTexturePool.back();
582 mTexturePool.pop_back();
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
584 return name;
585 }
586
587 // The pool was too small, so increase it for the future
588 ++mTexturePoolSize;
589 }
590
591 // The pool was empty, so we need to get a new texture name directly using a
592 // blocking call to the main thread
593 uint32_t name = 0;
594 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
595 return name;
596}
597
Mathias Agopian3f844832013-08-07 21:24:32 -0700598void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700599 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700600}
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
607
Thierry Strudel2924d012017-08-14 15:19:37 -0700608 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700613 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700614 mScheduler = getFactory().createScheduler([this](bool enabled) {
615 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
616 });
617
Ana Krulec98b5b242018-08-10 15:03:23 -0700618 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700619 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700620 [this] { resyncWithRateLimit(); },
621 impl::EventThread::InterceptVSyncsCallback());
622 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700623 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700624 [this] { resyncWithRateLimit(); },
625 [this](nsecs_t timestamp) {
626 mInterceptor->saveVSyncEvent(timestamp);
627 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800628
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700630 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
631 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 } else {
633 mEventThreadSource =
634 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
635 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
636 mEventThread =
637 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
638 [this] { resyncWithRateLimit(); },
639 impl::EventThread::InterceptVSyncsCallback(),
640 "appEventThread");
641 mSfEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
643 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
644
645 mSFEventThread =
646 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
647 [this] { resyncWithRateLimit(); },
648 [this](nsecs_t timestamp) {
649 mInterceptor->saveVSyncEvent(timestamp);
650 },
651 "sfEventThread");
652 mEventQueue->setEventThread(mSFEventThread.get());
653 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
654 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700657 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700658 renderEngineFeature |= (useColorManagement ?
659 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700660 renderEngineFeature |= (useContextPriority ?
661 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700662
663 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
664 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700665 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
666 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800667 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700668
669 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
670 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700671 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700672 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800673 // Process any initial hotplug and resulting display changes.
674 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 const auto display = getDefaultDisplayDeviceLocked();
676 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700677 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700678 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800679
Steven Thomas050b2c82017-03-06 11:45:16 -0800680 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700682 // This callback is called from the vr flinger dispatch thread. We
683 // need to call signalTransaction(), which requires holding
684 // mStateLock when we're not on the main thread. Acquiring
685 // mStateLock from the vr flinger dispatch thread might trigger a
686 // deadlock in surface flinger (see b/66916578), so post a message
687 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
690 mVrFlingerRequestsDisplay = requestDisplay;
691 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700692 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
695 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700696 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 .value_or(0),
698 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800699 if (!mVrFlinger) {
700 ALOGE("Failed to start vrflinger");
701 }
702 }
703
Lloyd Pique90c115d2018-09-18 21:39:42 -0700704 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700705 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700706
Mathias Agopian92a979a2012-08-02 18:32:23 -0700707 // initialize our drawing state
708 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700709
Andy McFadden13a082e2012-08-24 10:16:42 -0700710 // set initial conditions (e.g. unblank default device)
711 initializeDisplays();
712
David Sodmanbc815282017-11-05 18:57:52 -0800713 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700714
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700716
717 const bool presentFenceReliable =
718 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
719 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720
721 if (mStartPropertySetThread->Start() != NO_ERROR) {
722 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724
Chia-I Wud49d6692018-06-27 07:17:41 +0800725 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
726 // is used to saturate legacy sRGB content. However, to make sure the same color under
727 // Display P3 will be saturated to the same color, we intentionally break the API spec
728 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
729 // such saturation matrix on Display P3 is understood fully, the API should always return
730 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700731 mEnhancedSaturationMatrix =
732 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800733
734 // we will apply this on Display P3.
735 if (mEnhancedSaturationMatrix != mat4()) {
736 ColorSpace srgb(ColorSpace::sRGB());
737 ColorSpace displayP3(ColorSpace::DisplayP3());
738 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
739 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
740 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
741 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700744}
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 Mutex::Autolock _l(mStateLock);
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749 char value[PROPERTY_VALUE_MAX];
750
751 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100755
756 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700757 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700758}
759
Mathias Agopiana67e4182012-06-19 17:26:12 -0700760void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Start boot animation service by setting a property mailbox
762 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 if (mStartPropertySetThread->join() != NO_ERROR) {
766 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800767 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800771 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800775 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800779
Jamie Gennis582270d2011-08-17 18:19:00 -0700780bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800782 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800783 return authenticateSurfaceTextureLocked(bufferProducer);
784}
785
786bool SurfaceFlinger::authenticateSurfaceTextureLocked(
787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800788 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800789 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800790}
791
Brian Anderson6b376712017-04-04 10:51:39 -0700792status_t SurfaceFlinger::getSupportedFrameTimestamps(
793 std::vector<FrameEvent>* outSupported) const {
794 *outSupported = {
795 FrameEvent::REQUESTED_PRESENT,
796 FrameEvent::ACQUIRE,
797 FrameEvent::LATCH,
798 FrameEvent::FIRST_REFRESH_START,
799 FrameEvent::LAST_REFRESH_START,
800 FrameEvent::GPU_COMPOSITION_DONE,
801 FrameEvent::DEQUEUE_READY,
802 FrameEvent::RELEASE,
803 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700804 ConditionalLock _l(mStateLock,
805 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700806 if (!getHwComposer().hasCapability(
807 HWC2::Capability::PresentFenceIsNotReliable)) {
808 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
809 }
810 return NO_ERROR;
811}
812
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700813status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
814 Vector<DisplayInfo>* configs) {
815 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 return BAD_VALUE;
817 }
818
Dominik Laskowski075d3172018-05-24 15:50:06 -0700819 const auto displayId = getPhysicalDisplayId(displayToken);
820 if (!displayId) {
821 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700822 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 // TODO: Not sure if display density should handled by SF any longer
825 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700828 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800829 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 }
832 return density;
833 }
834 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("ro.sf.lcd_density"); }
839 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Steven Thomas6d8110b2017-08-31 18:24:21 -0700843 ConditionalLock _l(mStateLock,
844 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700845 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 DisplayInfo info = DisplayInfo();
847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 float xdpi = hwConfig->getDpiX();
849 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700850
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700851 info.w = hwConfig->getWidth();
852 info.h = hwConfig->getHeight();
853 // Default display viewport to display width and height
854 info.viewportW = info.w;
855 info.viewportH = info.h;
856
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 // The density of the device is provided by a build property
859 float density = Density::getBuildDensity() / 160.0f;
860 if (density == 0) {
861 // the build doesn't provide a density -- this is wrong!
862 // use xdpi instead
863 ALOGE("ro.sf.lcd_density must be defined as a build property");
864 density = xdpi / 160.0f;
865 }
866 if (Density::getEmuDensity()) {
867 // if "qemu.sf.lcd_density" is specified, it overrides everything
868 xdpi = ydpi = density = Density::getEmuDensity();
869 density /= 160.0f;
870 }
871 info.density = density;
872
873 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700874 const auto display = getDefaultDisplayDeviceLocked();
875 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700876
877 // This is for screenrecord
878 const Rect viewport = display->getViewport();
879 if (viewport.isValid()) {
880 info.viewportW = uint32_t(viewport.getWidth());
881 info.viewportH = uint32_t(viewport.getHeight());
882 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 } else {
884 // TODO: where should this value come from?
885 static const int TV_DENSITY = 213;
886 info.density = TV_DENSITY / 160.0f;
887 info.orientation = 0;
888 }
889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 info.xdpi = xdpi;
891 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900893 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800908 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
910 // All non-virtual displays are currently considered secure.
911 info.secure = true;
912
Dominik Laskowski075d3172018-05-24 15:50:06 -0700913 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700914 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800915 std::swap(info.w, info.h);
916 }
917
Michael Wright28f24d02016-07-12 13:30:53 -0700918 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700919 }
920
Dan Stoza7f7da322014-05-02 15:26:25 -0700921 return NO_ERROR;
922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
925 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700926 return BAD_VALUE;
927 }
928
Ana Krulece588e312018-09-18 12:32:24 -0700929 if (mUseScheduler) {
930 mScheduler->getDisplayStatInfo(stats);
931 } else {
932 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
933 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
934 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700935 return NO_ERROR;
936}
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
939 const auto display = getDisplayDevice(displayToken);
940 if (!display) {
941 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800942 return BAD_VALUE;
943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700946}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700949 if (display->isVirtual()) {
950 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
951 return;
952 }
953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700956 return;
957 }
958
Dominik Laskowski075d3172018-05-24 15:50:06 -0700959 const auto displayId = display->getId();
960 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700963 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964}
965
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700967 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968 Vector<DisplayInfo> configs;
969 getDisplayConfigs(displayToken, &configs);
970 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
971 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
972 configs.size());
973 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700975 const auto display = getDisplayDevice(displayToken);
976 if (!display) {
977 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
978 displayToken.get());
979 } else if (display->isVirtual()) {
980 ALOGW("Attempt to set active config %d for virtual display", mode);
981 } else {
982 setActiveConfigInternal(display, mode);
983 }
984 }));
985
Mathias Agopian888c8222012-08-04 21:10:38 -0700986 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700987}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
990 Vector<ColorMode>* outColorModes) {
991 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700992 return BAD_VALUE;
993 }
994
Dominik Laskowski075d3172018-05-24 15:50:06 -0700995 const auto displayId = getPhysicalDisplayId(displayToken);
996 if (!displayId) {
997 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001004 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1013 if (const auto display = getDisplayDevice(displayToken)) {
1014 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1020 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001021 if (display->isVirtual()) {
1022 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1023 return;
1024 }
1025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001026 ColorMode currentMode = display->getActiveColorMode();
1027 Dataspace currentDataSpace = display->getCompositionDataSpace();
1028 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001029
Peiyong Lin38e9a562018-04-10 16:24:20 -07001030 if (mode == currentMode && dataSpace == currentDataSpace &&
1031 renderIntent == currentRenderIntent) {
1032 return;
1033 }
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 display->setActiveColorMode(mode);
1036 display->setCompositionDataSpace(dataSpace);
1037 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001038
Dominik Laskowski075d3172018-05-24 15:50:06 -07001039 const auto displayId = display->getId();
1040 LOG_ALWAYS_FATAL_IF(!displayId);
1041 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1042
1043 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%" PRIu64,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski075d3172018-05-24 15:50:06 -07001045 renderIntent, *displayId);
Michael Wright28f24d02016-07-12 13:30:53 -07001046}
1047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001049 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 Vector<ColorMode> modes;
1051 getDisplayColorModes(displayToken, &modes);
1052 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1053 if (mode < ColorMode::NATIVE || !exists) {
1054 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1055 decodeColorMode(mode).c_str(), mode, displayToken.get());
1056 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 const auto display = getDisplayDevice(displayToken);
1059 if (!display) {
1060 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1061 decodeColorMode(mode).c_str(), mode, displayToken.get());
1062 } else if (display->isVirtual()) {
1063 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1064 decodeColorMode(mode).c_str(), mode);
1065 } else {
1066 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1067 RenderIntent::COLORIMETRIC);
1068 }
1069 }));
1070
Michael Wright28f24d02016-07-12 13:30:53 -07001071 return NO_ERROR;
1072}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001073
Svetoslavd85084b2014-03-20 10:28:31 -07001074status_t SurfaceFlinger::clearAnimationFrameStats() {
1075 Mutex::Autolock _l(mStateLock);
1076 mAnimFrameTracker.clearStats();
1077 return NO_ERROR;
1078}
1079
1080status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1081 Mutex::Autolock _l(mStateLock);
1082 mAnimFrameTracker.getStats(outStats);
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1087 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 Mutex::Autolock _l(mStateLock);
1089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090 const auto display = getDisplayDeviceLocked(displayToken);
1091 if (!display) {
1092 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 return BAD_VALUE;
1094 }
1095
Peiyong Linfb069302018-04-25 14:34:31 -07001096 // At this point the DisplayDeivce should already be set up,
1097 // meaning the luminance information is already queried from
1098 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001100 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1101 capabilities.getDesiredMaxLuminance(),
1102 capabilities.getDesiredMaxAverageLuminance(),
1103 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001104
1105 return NO_ERROR;
1106}
1107
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 if (mInjectVSyncs == enable) {
1113 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001114 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115
Ana Krulec98b5b242018-08-10 15:03:23 -07001116 // TODO(akrulec): Part of the Injector should be refactored, so that it
1117 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 if (enable) {
1119 ALOGV("VSync Injections enabled");
1120 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001121 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001122 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001123 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001124 impl::EventThread::InterceptVSyncsCallback(),
1125 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001127 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 } else {
1129 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001130 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 }
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001134 }));
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 return NO_ERROR;
1137}
1138
1139status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 Mutex::Autolock _l(mStateLock);
1141
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 if (!mInjectVSyncs) {
1143 ALOGE("VSync Injections not enabled");
1144 return BAD_VALUE;
1145 }
1146 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1147 ALOGV("Injecting VSync inside SurfaceFlinger");
1148 mVSyncInjector->onInjectSyncEvent(when);
1149 }
1150 return NO_ERROR;
1151}
1152
Lloyd Pique755e3192018-01-31 16:46:15 -08001153status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1154 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001155 // Try to acquire a lock for 1s, fail gracefully
1156 const status_t err = mStateLock.timedLock(s2ns(1));
1157 const bool locked = (err == NO_ERROR);
1158 if (!locked) {
1159 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1160 return TIMED_OUT;
1161 }
1162
1163 outLayers->clear();
1164 mCurrentState.traverseInZOrder([&](Layer* layer) {
1165 outLayers->push_back(layer->getLayerDebugInfo());
1166 });
1167
1168 mStateLock.unlock();
1169 return NO_ERROR;
1170}
1171
Peiyong Linc6780972018-10-28 15:24:08 -07001172status_t SurfaceFlinger::getCompositionPreference(
1173 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1174 Dataspace* outWideColorGamutDataspace,
1175 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001176 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001177 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001178 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001179 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001180 return NO_ERROR;
1181}
1182
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001183// ----------------------------------------------------------------------------
1184
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001185sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1186 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001187 if (mUseScheduler) {
1188 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1189 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1190 } else {
1191 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1192 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001193 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001194 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1195 return mSFEventThread->createEventConnection();
1196 } else {
1197 return mEventThread->createEventConnection();
1198 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001199 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001200}
1201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001202// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203
1204void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001205 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206}
1207
1208void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001209 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001210}
1211
1212void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001213 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001214}
1215
1216void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001217 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001222 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001223 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001227 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229 if (res == NO_ERROR) {
1230 msg->wait();
1231 }
1232 return res;
1233}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001234
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001235void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001236 do {
1237 waitForEvent();
1238 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239}
1240
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241void SurfaceFlinger::enableHardwareVsync() {
1242 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001243 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001244 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001245 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001247 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248}
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 Mutex::Autolock _l(mHWVsyncLock);
1252
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253 if (makeAvailable) {
1254 mHWVsyncAvailable = true;
1255 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001256 // Hardware vsync is not currently available, so abort the resync
1257 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 return;
1259 }
1260
Dominik Laskowski075d3172018-05-24 15:50:06 -07001261 const auto displayId = getInternalDisplayId();
1262 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001263 return;
1264 }
1265
Dominik Laskowski075d3172018-05-24 15:50:06 -07001266 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001267 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268
Ana Krulece588e312018-09-18 12:32:24 -07001269 if (mUseScheduler) {
1270 mScheduler->setVsyncPeriod(period);
1271 } else {
1272 mPrimaryDispSync->reset();
1273 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274
Ana Krulece588e312018-09-18 12:32:24 -07001275 if (!mPrimaryHWVsyncEnabled) {
1276 mPrimaryDispSync->beginResync();
1277 mEventControlThread->setVsyncEnabled(true);
1278 mPrimaryHWVsyncEnabled = true;
1279 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 }
1281}
1282
Jesse Hall948fe0c2013-10-14 12:56:09 -07001283void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284 Mutex::Autolock _l(mHWVsyncLock);
1285 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001286 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001287 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 mPrimaryHWVsyncEnabled = false;
1289 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290 if (makeUnavailable) {
1291 mHWVsyncAvailable = false;
1292 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293}
1294
Tim Murray4a4e4a22016-04-19 16:29:23 +00001295void SurfaceFlinger::resyncWithRateLimit() {
1296 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001297
1298 // No explicit locking is needed here since EventThread holds a lock while calling this method
1299 static nsecs_t sLastResyncAttempted = 0;
1300 const nsecs_t now = systemTime();
1301 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001302 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001303 }
Dan Stoza57164302017-05-08 14:03:54 -07001304 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001305}
1306
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001307void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1308 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001309 ATRACE_NAME("SF onVsync");
1310
Steven Thomas3cfac282017-02-06 12:29:30 -08001311 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001312 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001313 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001314 return;
1315 }
1316
Dominik Laskowski075d3172018-05-24 15:50:06 -07001317 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 return;
1319 }
1320
Dominik Laskowski075d3172018-05-24 15:50:06 -07001321 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001322 // For now, we don't do anything with external display vsyncs.
1323 return;
1324 }
1325
Ana Krulece588e312018-09-18 12:32:24 -07001326 if (mUseScheduler) {
1327 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001328 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001329 bool needsHwVsync = false;
1330 { // Scope for the lock
1331 Mutex::Autolock _l(mHWVsyncLock);
1332 if (mPrimaryHWVsyncEnabled) {
1333 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1334 }
1335 }
1336
1337 if (needsHwVsync) {
1338 enableHardwareVsync();
1339 } else {
1340 disableHardwareVsync(false);
1341 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343}
1344
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001345void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001346 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1347 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001348}
1349
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001351 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001352 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001353 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354
Lloyd Piqueba04e622017-12-14 17:11:26 -08001355 // Ignore events that do not have the right sequenceId.
1356 if (sequenceId != getBE().mComposerSequenceId) {
1357 return;
1358 }
1359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Only lock if we're not on the main thread. This function is normally
1361 // called on a hwbinder thread, but for the primary display it's called on
1362 // the main thread with the state lock already held, so don't attempt to
1363 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001366 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001367
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001368 if (std::this_thread::get_id() == mMainThreadId) {
1369 // Process all pending hot plug events immediately if we are on the main thread.
1370 processDisplayHotplugEventsLocked();
1371 }
1372
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001374}
1375
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001376void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001378 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001381 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001382}
1383
Dominik Laskowski075d3172018-05-24 15:50:06 -07001384void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001385 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001387 if (const auto displayId = getInternalDisplayId()) {
1388 getHwComposer().setVsyncEnabled(*displayId,
1389 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1390 }
Mathias Agopian86303202012-07-24 22:46:10 -07001391}
1392
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001394void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001395 if (mUseScheduler) {
1396 mScheduler->disableHardwareVsync(true);
1397 } else {
1398 disableHardwareVsync(true);
1399 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400 // Clear the drawing state so that the logic inside of
1401 // handleTransactionLocked will fire. It will determine the delta between
1402 // mCurrentState and mDrawingState and re-apply all changes when we make the
1403 // transition.
1404 mDrawingState.displays.clear();
1405 mDisplays.clear();
1406}
1407
Steven Thomas050b2c82017-03-06 11:45:16 -08001408void SurfaceFlinger::updateVrFlinger() {
1409 if (!mVrFlinger)
1410 return;
1411 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001413 return;
1414 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415
David Sodman105b7dc2017-11-04 20:28:14 -07001416 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 ALOGE("Vr flinger is only supported for remote hardware composer"
1418 " service connections. Ignoring request to transition to vr"
1419 " flinger.");
1420 mVrFlingerRequestsDisplay = false;
1421 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001422 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001425
Steven Thomas0123ac62018-07-12 11:32:34 -07001426 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001427 LOG_ALWAYS_FATAL_IF(!display);
1428 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001429 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1430 // called below. Clear the reference now so we don't accidentally use it
1431 // later.
1432 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001439 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001440 getBE().mHwc = getFactory().createHWComposer(
1441 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001442 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
David Sodman105b7dc2017-11-04 20:28:14 -07001444 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1445 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001446
1447 if (vrFlingerRequestsDisplay) {
1448 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001449 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
1451 mVisibleRegionsDirty = true;
1452 invalidateHwcGeometry();
1453
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001455 display = getDefaultDisplayDeviceLocked();
1456 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001457 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001458
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001460 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 const nsecs_t period = activeConfig->getVsyncPeriod();
1462 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001463
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001464 // The present fences returned from vr_hwc are not an accurate
1465 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001466 if (mUseScheduler) {
1467 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1468 } else {
1469 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1470 !hasSyncFramework);
1471 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001472
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 // Use phase of 0 since phase is not known.
1474 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001475 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1476 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001477
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001478 resyncToHardwareVsync(false);
1479
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001480 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001482}
1483
Mathias Agopian4fec8732012-06-29 14:12:52 -07001484void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001485 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001486 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001488 bool frameMissed = !mHadClientComposition &&
1489 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001490 (mPreviousPresentFence->getSignalTime() ==
1491 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001492 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001493 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001494 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001495 mTimeStats.incrementMissedFrames();
1496 if (mPropagateBackpressure) {
1497 signalLayerUpdate();
1498 break;
1499 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001500 }
Dan Stoza50182882016-07-08 12:02:20 -07001501
Steven Thomas050b2c82017-03-06 11:45:16 -08001502 // Now that we're going to make it to the handleMessageTransaction()
1503 // call below it's safe to call updateVrFlinger(), which will
1504 // potentially trigger a display handoff.
1505 updateVrFlinger();
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507 bool refreshNeeded = handleMessageTransaction();
1508 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001509 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001510 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001511 // Signal a refresh if a transaction modified the window state,
1512 // a new buffer was latched, or if HWC has requested a full
1513 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514 signalRefresh();
1515 }
1516 break;
1517 }
1518 case MessageQueue::REFRESH: {
1519 handleMessageRefresh();
1520 break;
1521 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522 }
1523}
1524
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001526 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001528 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001530 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001531 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001532}
1533
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001536
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001537 mRefreshPending = false;
1538
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001539 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001540 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001541 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001542 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001543 for (const auto& [token, display] : mDisplays) {
1544 beginFrame(display);
1545 prepareFrame(display);
1546 doDebugFlashRegions(display, repaintEverything);
1547 doComposition(display, repaintEverything);
1548 }
1549
Adrian Roos1e1a1282017-11-01 19:05:31 +01001550 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001551 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001552
1553 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001554 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001555
Dan Stozabfbffeb2016-07-21 14:49:33 -07001556 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001557 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001558 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001559 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001560 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001561
Alec Mouri86770e52018-09-24 22:40:58 +00001562 // Setup RenderEngine sync fences if native sync is supported.
1563 if (getBE().mRenderEngine->useNativeFenceSync()) {
1564 if (mHadClientComposition) {
1565 base::unique_fd flushFence(getRenderEngine().flush());
1566 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1567 getBE().flushFence = new Fence(std::move(flushFence));
1568 } else {
1569 // Cleanup for hygiene.
1570 getBE().flushFence = Fence::NO_FENCE;
1571 }
1572 }
1573
Jorim Jaggi90535212018-05-23 23:44:06 +02001574 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001575
David Sodman7e4ae112018-02-09 15:02:28 -08001576 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001577 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001578 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001579 compositionInfo.hwc.hwcLayer = nullptr;
1580 }
David Sodmanba340492018-08-05 21:51:33 -07001581 }
David Sodman7e4ae112018-02-09 15:02:28 -08001582
1583 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001585
David Sodmanfa9b2af2017-12-24 13:28:59 -08001586
1587bool SurfaceFlinger::handleMessageInvalidate() {
1588 ATRACE_CALL();
1589 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001590}
1591
David Sodman79bba0e2018-08-05 18:07:49 -07001592void SurfaceFlinger::calculateWorkingSet() {
1593 ATRACE_CALL();
1594 ALOGV(__FUNCTION__);
1595
David Sodman79bba0e2018-08-05 18:07:49 -07001596 // build the h/w work list
1597 if (CC_UNLIKELY(mGeometryInvalid)) {
1598 mGeometryInvalid = false;
1599 for (const auto& [token, display] : mDisplays) {
1600 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001601 if (!displayId) {
1602 continue;
1603 }
David Sodman79bba0e2018-08-05 18:07:49 -07001604
Dominik Laskowski075d3172018-05-24 15:50:06 -07001605 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1606 for (size_t i = 0; i < currentLayers.size(); i++) {
1607 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001608
Dominik Laskowski075d3172018-05-24 15:50:06 -07001609 if (!layer->hasHwcLayer(*displayId)) {
1610 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1611 layer->forceClientComposition(*displayId);
1612 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001613 }
1614 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001615
1616 layer->setGeometry(display, i);
1617 if (mDebugDisableHWC || mDebugRegion) {
1618 layer->forceClientComposition(*displayId);
1619 }
David Sodman79bba0e2018-08-05 18:07:49 -07001620 }
1621 }
1622 }
1623
1624 // Set the per-frame data
1625 for (const auto& [token, display] : mDisplays) {
1626 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001627 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001628 continue;
1629 }
1630
1631 if (mDrawingState.colorMatrixChanged) {
1632 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001633 status_t result =
1634 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
1635 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %" PRIu64 ": %d",
1636 *displayId, result);
David Sodman79bba0e2018-08-05 18:07:49 -07001637 }
1638 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1639 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001640 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001641 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1642 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1643 !display->hasHDR10Support()) {
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_HLG ||
1646 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1647 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001648 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001649 }
1650
Peiyong Lind3788632018-09-18 16:01:31 -07001651 // TODO(b/111562338) remove when composer 2.3 is shipped.
1652 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001653 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001654 }
1655
Dominik Laskowski075d3172018-05-24 15:50:06 -07001656 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001657 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001658 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001659 continue;
1660 }
1661
Dominik Laskowski075d3172018-05-24 15:50:06 -07001662 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1663 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001664 }
1665
Peiyong Lin13effd12018-07-24 17:01:47 -07001666 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001667 ColorMode colorMode;
1668 Dataspace dataSpace;
1669 RenderIntent renderIntent;
1670 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1671 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1672 }
1673 }
1674
1675 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001676
1677 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001678 getBE().mCompositionInfo[token].clear();
1679
David Sodmanba340492018-08-05 21:51:33 -07001680 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001681 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001682 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001683
1684 if (displayId) {
1685 if (!layer->setHwcLayer(*displayId)) {
1686 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1687 }
1688 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001689 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001690
Dominik Laskowski05275f12018-11-01 15:03:24 -07001691 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001692 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1693 }
1694 }
David Sodman79bba0e2018-08-05 18:07:49 -07001695}
1696
David Sodmanfa9b2af2017-12-24 13:28:59 -08001697void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698{
1699 // is debugging enabled
1700 if (CC_LIKELY(!mDebugRegion))
1701 return;
1702
David Sodmanfa9b2af2017-12-24 13:28:59 -08001703 if (display->isPoweredOn()) {
1704 // transform the dirty region into this screen's coordinate space
1705 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1706 if (!dirtyRegion.isEmpty()) {
1707 // redraw the whole screen
1708 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001712 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001713
Alec Mouri8147b0e2018-10-09 20:57:19 -07001714 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715 }
1716 }
1717
David Sodmanfa9b2af2017-12-24 13:28:59 -08001718 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719
1720 if (mDebugRegion > 1) {
1721 usleep(mDebugRegion * 1000);
1722 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001723
Dominik Laskowski05275f12018-11-01 15:03:24 -07001724 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725}
1726
Adrian Roos1e1a1282017-11-01 19:05:31 +01001727void SurfaceFlinger::doTracing(const char* where) {
1728 ATRACE_CALL();
1729 ATRACE_NAME(where);
1730 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001731 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001732 }
1733}
1734
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001735void SurfaceFlinger::logLayerStats() {
1736 ATRACE_CALL();
1737 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001738 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001739 if (display->isPrimary()) {
1740 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001741 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001742 }
1743 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001744
1745 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001746 }
1747}
1748
David Sodman2b406362017-12-15 13:33:47 -08001749void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 ATRACE_CALL();
1752 ALOGV("preComposition");
1753
David Sodman2b406362017-12-15 13:33:47 -08001754 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1755
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001757 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001758 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759 needExtraInvalidate = true;
1760 }
Robert Carr2047fae2016-11-28 14:09:09 -08001761 });
1762
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763 if (needExtraInvalidate) {
1764 signalLayerUpdate();
1765 }
1766}
1767
Ana Krulece588e312018-09-18 12:32:24 -07001768void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1769 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001770 // Update queue of past composite+present times and determine the
1771 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001772 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001774 while (!getBE().mCompositePresentTimes.empty()) {
1775 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001776 // Cached values should have been updated before calling this method,
1777 // which helps avoid duplicate syscalls.
1778 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1779 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1780 break;
1781 }
1782 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001783 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784 }
1785
1786 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001787 while (getBE().mCompositePresentTimes.size() > 16) {
1788 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 }
1790
Ana Krulece588e312018-09-18 12:32:24 -07001791 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001792}
1793
Ana Krulece588e312018-09-18 12:32:24 -07001794void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1795 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 // Integer division and modulo round toward 0 not -inf, so we need to
1797 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001798 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1799 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1800 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801
Brian Andersond0010582017-03-07 13:20:31 -08001802 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1803 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001804 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001805 }
1806
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807 // Snap the latency to a value that removes scheduling jitter from the
1808 // composition and present times, which often have >1ms of jitter.
1809 // Reducing jitter is important if an app attempts to extrapolate
1810 // something (such as user input) to an accurate diasplay time.
1811 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1812 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001813 nsecs_t bias = stats.vsyncPeriod / 2;
1814 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1815 nsecs_t snappedCompositeToPresentLatency =
1816 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001817
David Sodman99974d22017-11-28 12:04:33 -08001818 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001819 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1820 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001821 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001822}
1823
David Sodman2b406362017-12-15 13:33:47 -08001824void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 ATRACE_CALL();
1827 ALOGV("postComposition");
1828
Brian Anderson3546a3f2016-07-14 11:51:14 -07001829 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001830 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001831 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001832 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001833 }
1834
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001835 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001836 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001839 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001840 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001841 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001842 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001843 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001844 } else {
1845 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1846 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001847
David Sodman73beded2017-11-15 11:56:06 -08001848 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001849 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001850 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001851 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001852 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001853
Ana Krulece588e312018-09-18 12:32:24 -07001854 DisplayStatInfo stats;
1855 if (mUseScheduler) {
1856 mScheduler->getDisplayStatInfo(&stats);
1857 } else {
1858 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1859 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1860 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861
David Sodman2b406362017-12-15 13:33:47 -08001862 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001863 // when we started doing work for this frame, but that should be okay
1864 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001865 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001866 CompositorTiming compositorTiming;
1867 {
David Sodman99974d22017-11-28 12:04:33 -08001868 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1869 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001870 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871
Robert Carr2047fae2016-11-28 14:09:09 -08001872 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001873 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1874 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001875 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001876 recordBufferingStats(layer->getName().string(),
1877 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001878 }
Robert Carr2047fae2016-11-28 14:09:09 -08001879 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001880
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001881 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001882 if (mUseScheduler) {
1883 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001884 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001885 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1886 enableHardwareVsync();
1887 } else {
1888 disableHardwareVsync(false);
1889 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001890 }
1891 }
1892
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001893 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001894 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001895 if (mUseScheduler) {
1896 mScheduler->enableHardwareVsync();
1897 } else {
1898 enableHardwareVsync();
1899 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001900 }
1901 }
1902
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001903 if (mAnimCompositionPending) {
1904 mAnimCompositionPending = false;
1905
Brian Anderson4e606e32017-03-16 15:34:57 -07001906 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001907 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001908 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001909 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001910 // The HWC doesn't support present fences, so use the refresh
1911 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001912 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001913 mAnimFrameTracker.setActualPresentTime(presentTime);
1914 }
1915 mAnimFrameTracker.advanceFrame();
1916 }
Dan Stozab90cf072015-03-05 11:05:59 -08001917
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001918 mTimeStats.incrementTotalFrames();
1919 if (mHadClientComposition) {
1920 mTimeStats.incrementClientCompositionFrames();
1921 }
1922
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001923 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1924
Dominik Laskowski075d3172018-05-24 15:50:06 -07001925 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001926 return;
1927 }
1928
1929 nsecs_t currentTime = systemTime();
1930 if (mHasPoweredOff) {
1931 mHasPoweredOff = false;
1932 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001933 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001934 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001935 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1936 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001937 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001938 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001939 }
David Sodman4a36e932017-11-07 14:29:47 -08001940 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001941 }
David Sodman4a36e932017-11-07 14:29:47 -08001942 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001943
1944 {
1945 std::lock_guard lock(mTexturePoolMutex);
1946 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1947 if (refillCount > 0) {
1948 const size_t offset = mTexturePool.size();
1949 mTexturePool.resize(mTexturePoolSize);
1950 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1951 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1952 }
1953 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954}
1955
1956void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 ATRACE_CALL();
1958 ALOGV("rebuildLayerStacks");
1959
Mathias Agopiancd60f992012-08-16 16:28:27 -07001960 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001961 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001962 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 mVisibleRegionsDirty = false;
1964 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001965
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001966 for (const auto& pair : mDisplays) {
1967 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001968 Region opaqueRegion;
1969 Region dirtyRegion;
1970 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001971 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001972 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001973 const Rect bounds = display->getBounds();
1974 if (display->isPoweredOn()) {
1975 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001976
Jeff Sharkey76488112017-02-27 14:15:18 -07001977 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001978 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07001979 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001981 Region drawRegion(tr.transform(
1982 layer->visibleNonTransparentRegion));
1983 drawRegion.andSelf(bounds);
1984 if (!drawRegion.isEmpty()) {
1985 layersSortedByZ.add(layer);
1986 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001987 // Clear out the HWC layer if this layer was
1988 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07001989 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07001990 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001991 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001992 // WM changes display->layerStack upon sleep/awake.
1993 // Here we make sure we delete the HWC layers even if
1994 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001995 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08001996 }
1997
1998 // If a layer is not going to get a release fence because
1999 // it is invisible, but it is also going to release its
2000 // old buffer, add it to the list of layers needing
2001 // fences.
2002 if (hwcLayerDestroyed) {
2003 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2004 mLayersWithQueuedFrames.cend(), layer);
2005 if (found != mLayersWithQueuedFrames.cend()) {
2006 layersNeedingFences.add(layer);
2007 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002008 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002009 });
2010 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011 display->setVisibleLayersSortedByZ(layersSortedByZ);
2012 display->setLayersNeedingFences(layersNeedingFences);
2013 display->undefinedRegion.set(bounds);
2014 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2015 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002016 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002017 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002019
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002021// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002022// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002023// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002024// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002025// The returned HDR data space is one of
2026// - Dataspace::UNKNOWN
2027// - Dataspace::BT2020_HLG
2028// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2030 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002031 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002032 *outHdrDataSpace = Dataspace::UNKNOWN;
2033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002034 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002035 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002036 case Dataspace::V0_SCRGB:
2037 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002038 case Dataspace::BT2020:
2039 case Dataspace::BT2020_ITU:
2040 case Dataspace::BT2020_LINEAR:
2041 case Dataspace::DISPLAY_BT2020:
2042 bestDataSpace = Dataspace::DISPLAY_BT2020;
2043 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002044 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002045 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047 case Dataspace::BT2020_PQ:
2048 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002049 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002050 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002051 case Dataspace::BT2020_HLG:
2052 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002053 // When there's mixed PQ content and HLG content, we set the HDR
2054 // data space to be BT2020_PQ and convert HLG to PQ.
2055 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2056 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002057 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 break;
2059 default:
2060 break;
2061 }
Romain Guy54f154a2017-10-24 21:40:32 +01002062 }
2063
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002064 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002065}
2066
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002067// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002068void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2069 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002070 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2071 *outMode = ColorMode::NATIVE;
2072 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002073 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002074 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002075 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002076
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002077 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002079
Peiyong Lindfde5112018-06-05 10:58:41 -07002080 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002081 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002082 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002083 if (isHdr) {
2084 bestDataSpace = hdrDataSpace;
2085 }
2086
Chia-I Wu0d711262018-05-21 15:19:35 -07002087 RenderIntent intent;
2088 switch (mDisplayColorSetting) {
2089 case DisplayColorSetting::MANAGED:
2090 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002091 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002092 break;
2093 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002094 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002095 break;
2096 default: // vendor display color setting
2097 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2098 break;
2099 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002102}
2103
David Sodmanfa9b2af2017-12-24 13:28:59 -08002104void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002105{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002106 bool dirty = !display->getDirtyRegion(false).isEmpty();
2107 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2108 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002109
David Sodmanfa9b2af2017-12-24 13:28:59 -08002110 // If nothing has changed (!dirty), don't recompose.
2111 // If something changed, but we don't currently have any visible layers,
2112 // and didn't when we last did a composition, then skip it this time.
2113 // The second rule does two things:
2114 // - When all layers are removed from a display, we'll emit one black
2115 // frame, then nothing more until we get new layers.
2116 // - When a display is created with a private layer stack, we won't
2117 // emit any black frames until a layer is added to the layer stack.
2118 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002119
Dominik Laskowski075d3172018-05-24 15:50:06 -07002120 const char flagPrefix[] = {'-', '+'};
2121 static_cast<void>(flagPrefix);
2122 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2123 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2124 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002125
David Sodmanfa9b2af2017-12-24 13:28:59 -08002126 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002127
David Sodmanfa9b2af2017-12-24 13:28:59 -08002128 if (mustRecompose) {
2129 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002130 }
2131}
2132
David Sodmanfa9b2af2017-12-24 13:28:59 -08002133void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002134{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 if (!display->isPoweredOn()) {
2136 return;
David Sodman2b406362017-12-15 13:33:47 -08002137 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138
Dominik Laskowski05275f12018-11-01 15:03:24 -07002139 status_t result = display->prepareFrame(getHwComposer(),
2140 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002141 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2142 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002143}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002144
David Sodmanfa9b2af2017-12-24 13:28:59 -08002145void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002146 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 ALOGV("doComposition");
2148
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149 if (display->isPoweredOn()) {
2150 // transform the dirty region into this screen's coordinate space
2151 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002152
David Sodmanfa9b2af2017-12-24 13:28:59 -08002153 // repaint the framebuffer (if needed)
2154 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002155
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156 display->dirtyRegion.clear();
2157 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002158 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002159 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002160}
2161
David Sodmanfa9b2af2017-12-24 13:28:59 -08002162void SurfaceFlinger::postFrame()
2163{
2164 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002165 const auto display = getDefaultDisplayDeviceLocked();
2166 if (display && getHwComposer().isConnected(*display->getId())) {
2167 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002168 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2169 logFrameStats();
2170 }
2171 }
2172}
2173
2174void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002175{
Mathias Agopian841cde52012-03-01 15:44:37 -08002176 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002177 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002178
David Sodmanfa9b2af2017-12-24 13:28:59 -08002179 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002180
David Sodmanfa9b2af2017-12-24 13:28:59 -08002181 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002182 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002183 if (displayId) {
2184 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002185 }
Alec Mouri8147b0e2018-10-09 20:57:19 -07002186 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002187 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002188 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002189
Chia-I Wu7b549592017-11-15 09:14:57 -08002190 // The layer buffer from the previous frame (if any) is released
2191 // by HWC only when the release fence from this frame (if any) is
2192 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002193 if (displayId && layer->hasHwcLayer(*displayId)) {
2194 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2195 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002196 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002197
2198 // If the layer was client composited in the previous frame, we
2199 // need to merge with the previous client target acquire fence.
2200 // Since we do not track that, always merge with the current
2201 // client target acquire fence when it is available, even though
2202 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002203 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002204 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002206 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002207
David Sodman15094112018-10-11 09:39:37 -07002208 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002209 }
Chia-I Wu83806892017-11-16 10:50:20 -08002210
2211 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002213 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002214 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 sp<Fence> presentFence =
2216 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002218 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002219 }
2220 }
2221
Dominik Laskowski075d3172018-05-24 15:50:06 -07002222 if (displayId) {
2223 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002224 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002225 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226}
2227
Mathias Agopian87baae12012-07-31 12:38:26 -07002228void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229{
Mathias Agopian841cde52012-03-01 15:44:37 -08002230 ATRACE_CALL();
2231
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002232 // here we keep a copy of the drawing state (that is the state that's
2233 // going to be overwritten by handleTransactionLocked()) outside of
2234 // mStateLock so that the side-effects of the State assignment
2235 // don't happen with mStateLock held (which can cause deadlocks).
2236 State drawingState(mDrawingState);
2237
Mathias Agopianca4d3602011-05-19 15:38:14 -07002238 Mutex::Autolock _l(mStateLock);
2239 const nsecs_t now = systemTime();
2240 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241
Mathias Agopianca4d3602011-05-19 15:38:14 -07002242 // Here we're guaranteed that some transaction flags are set
2243 // so we can call handleTransactionLocked() unconditionally.
2244 // We call getTransactionFlags(), which will also clear the flags,
2245 // with mStateLock held to guarantee that mCurrentState won't change
2246 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002247
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002248 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002249 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002250 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002251
Mathias Agopianca4d3602011-05-19 15:38:14 -07002252 mLastTransactionTime = systemTime() - now;
2253 mDebugInTransaction = 0;
2254 invalidateHwcGeometry();
2255 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002256}
2257
Lloyd Piqueba04e622017-12-14 17:11:26 -08002258void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2259 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002260 const std::optional<DisplayIdentificationInfo> info =
2261 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002262
Dominik Laskowski075d3172018-05-24 15:50:06 -07002263 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002264 continue;
2265 }
2266
Lloyd Piqueba04e622017-12-14 17:11:26 -08002267 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002268 if (!mPhysicalDisplayTokens.count(info->id)) {
2269 ALOGV("Creating display %" PRIu64, info->id);
2270 mPhysicalDisplayTokens[info->id] = new BBinder();
2271 DisplayDeviceState state;
2272 state.displayId = info->id;
2273 state.isSecure = true; // All physical displays are currently considered secure.
2274 state.displayName = info->name;
2275 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2276 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002277 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278 } else {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 ALOGV("Removing display %" PRIu64, info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002280
Dominik Laskowski075d3172018-05-24 15:50:06 -07002281 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2282 if (index >= 0) {
2283 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2284 mInterceptor->saveDisplayDeletion(state.sequenceId);
2285 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002286 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002287 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288 }
2289
2290 processDisplayChangesLocked();
2291 }
2292
2293 mPendingHotplugEvents.clear();
2294}
2295
Lloyd Pique99d3da52018-01-22 17:48:03 -08002296sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002297 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2298 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2299 const sp<IGraphicBufferProducer>& producer) {
2300 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2301 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002302 creationArgs.isSecure = state.isSecure;
2303 creationArgs.displaySurface = dispSurface;
2304 creationArgs.hasWideColorGamut = false;
2305 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306
Dominik Laskowski075d3172018-05-24 15:50:06 -07002307 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2308 creationArgs.isPrimary = isInternalDisplay;
2309
2310 if (useColorManagement && displayId) {
2311 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002313 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002314 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316
Dominik Laskowski7e045462018-05-30 13:02:02 -07002317 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002318 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002319 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320 }
tangrobin6753a022018-08-10 10:58:54 +08002321 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322
Dominik Laskowski075d3172018-05-24 15:50:06 -07002323 if (displayId) {
2324 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002325 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002326 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002327 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328
Lloyd Pique90c115d2018-09-18 21:39:42 -07002329 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002331 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
2333 /*
2334 * Create our display's surface
2335 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002336 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 renderSurface->setCritical(isInternalDisplay);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002338 renderSurface->setAsync(state.isVirtual());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002339 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340
2341 // Make sure that composition can never be stalled by a virtual display
2342 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri8147b0e2018-10-09 20:57:19 -07002343 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002344 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2346 }
2347
Dominik Laskowski075d3172018-05-24 15:50:06 -07002348 creationArgs.displayInstallOrientation =
2349 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002350
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002352 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353
Lloyd Pique90c115d2018-09-18 21:39:42 -07002354 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355
2356 if (maxFrameBufferAcquiredBuffers >= 3) {
2357 nativeWindowSurface->preallocateBuffers();
2358 }
2359
2360 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002362 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002364 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002367 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 if (!state.isVirtual()) {
2369 LOG_ALWAYS_FATAL_IF(!displayId);
2370 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002371 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002372
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002373 display->setLayerStack(state.layerStack);
2374 display->setProjection(state.orientation, state.viewport, state.frame);
2375 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002377 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378}
2379
Lloyd Pique347200f2017-12-14 17:00:15 -08002380void SurfaceFlinger::processDisplayChangesLocked() {
2381 // here we take advantage of Vector's copy-on-write semantics to
2382 // improve performance by skipping the transaction entirely when
2383 // know that the lists are identical
2384 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2385 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2386 if (!curr.isIdenticalTo(draw)) {
2387 mVisibleRegionsDirty = true;
2388 const size_t cc = curr.size();
2389 size_t dc = draw.size();
2390
2391 // find the displays that were removed
2392 // (ie: in drawing state but not in current state)
2393 // also handle displays that changed
2394 // (ie: displays that are in both lists)
2395 for (size_t i = 0; i < dc;) {
2396 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2397 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 // Save display IDs before disconnecting.
2399 const auto internalDisplayId = getInternalDisplayId();
2400 const auto externalDisplayId = getExternalDisplayId();
2401
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002403 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2404 display->disconnect(getHwComposer());
2405 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002407 if (mUseScheduler) {
2408 mScheduler->hotplugReceived(mAppConnectionHandle,
2409 EventThread::DisplayType::Primary, false);
2410 } else {
2411 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2412 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002414 if (mUseScheduler) {
2415 mScheduler->hotplugReceived(mAppConnectionHandle,
2416 EventThread::DisplayType::External, false);
2417 } else {
2418 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2419 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002420 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002421 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 } else {
2423 // this display is in both lists. see if something changed.
2424 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2427 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2428 if (state_binder != draw_binder) {
2429 // changing the surface is like destroying and
2430 // recreating the DisplayDevice, so we just remove it
2431 // from the drawing state, so that it get re-added
2432 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002433 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2434 display->disconnect(getHwComposer());
2435 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002436 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002437 mDrawingState.displays.removeItemsAt(i);
2438 dc--;
2439 // at this point we must loop to the next item
2440 continue;
2441 }
2442
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002446 }
2447 if ((state.orientation != draw[i].orientation) ||
2448 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 }
2451 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 }
2454 }
2455 }
2456 ++i;
2457 }
2458
2459 // find displays that were added
2460 // (ie: in current state but not in drawing state)
2461 for (size_t i = 0; i < cc; i++) {
2462 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2463 const DisplayDeviceState& state(curr[i]);
2464
2465 sp<DisplaySurface> dispSurface;
2466 sp<IGraphicBufferProducer> producer;
2467 sp<IGraphicBufferProducer> bqProducer;
2468 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002469 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002470
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002472 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002473 // Virtual displays without a surface are dormant:
2474 // they have external state (layer stack, projection,
2475 // etc.) but no internal state (i.e. a DisplayDevice).
2476 if (state.surface != nullptr) {
2477 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002478 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002479 int width = 0;
2480 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2481 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2482 int height = 0;
2483 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2484 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2485 int intFormat = 0;
2486 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2487 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002488 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002489
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 displayId =
2491 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492 }
2493
2494 // TODO: Plumb requested format back up to consumer
2495
2496 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 bqProducer, bqConsumer,
2499 state.displayName);
2500
2501 dispSurface = vds;
2502 producer = vds;
2503 }
2504 } else {
2505 ALOGE_IF(state.surface != nullptr,
2506 "adding a supported display, but rendering "
2507 "surface is provided (%p), ignoring it",
2508 state.surface.get());
2509
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 displayId = state.displayId;
2511 LOG_ALWAYS_FATAL_IF(!displayId);
2512 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002513 producer = bqProducer;
2514 }
2515
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002518 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002519 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002521 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 LOG_ALWAYS_FATAL_IF(!displayId);
2523
2524 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002525 if (mUseScheduler) {
2526 mScheduler->hotplugReceived(mAppConnectionHandle,
2527 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002528 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002529 } else {
2530 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2531 true);
2532 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002534 if (mUseScheduler) {
2535 mScheduler->hotplugReceived(mAppConnectionHandle,
2536 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002537 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002538 } else {
2539 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2540 true);
2541 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002542 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 }
2544 }
2545 }
2546 }
2547 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548
2549 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002550}
2551
Mathias Agopian87baae12012-07-31 12:38:26 -07002552void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002553{
Dan Stoza7dde5992015-05-22 09:51:44 -07002554 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002555 mCurrentState.traverseInZOrder([](Layer* layer) {
2556 layer->notifyAvailableFrames();
2557 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002558
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 /*
2560 * Traversal of the children
2561 * (perform the transaction for each of them if needed)
2562 */
2563
Mathias Agopian3559b072012-08-15 13:46:03 -07002564 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002565 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002567 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568
2569 const uint32_t flags = layer->doTransaction(0);
2570 if (flags & Layer::eVisibleRegion)
2571 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002572 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 }
2574
2575 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 */
2578
Mathias Agopiane57f2922012-08-09 16:29:12 -07002579 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002581 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002584 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002585 // The transform hint might have changed for some layers
2586 // (either because a display has changed, or because a layer
2587 // as changed).
2588 //
2589 // Walk through all the layers in currentLayers,
2590 // and update their transform hint.
2591 //
2592 // If a layer is visible only on a single display, then that
2593 // display is used to calculate the hint, otherwise we use the
2594 // default display.
2595 //
2596 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2597 // the hint is set before we acquire a buffer from the surface texture.
2598 //
2599 // NOTE: layer transactions have taken place already, so we use their
2600 // drawing state. However, SurfaceFlinger's own transaction has not
2601 // happened yet, so we must use the current state layer list
2602 // (soon to become the drawing state list).
2603 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002605 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002606 bool first = true;
2607 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002608 // NOTE: we rely on the fact that layers are sorted by
2609 // layerStack first (so we don't have to traverse the list
2610 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002611 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002612 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002613 currentlayerStack = layerStack;
2614 // figure out if this layerstack is mirrored
2615 // (more than one display) if so, pick the default display,
2616 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002617 hintDisplay = nullptr;
2618 for (const auto& [token, display] : mDisplays) {
2619 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2620 if (hintDisplay) {
2621 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002622 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002623 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002624 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002625 }
2626 }
2627 }
2628 }
Chet Haase91d25932013-04-11 15:24:55 -07002629
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002630 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002631 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2632 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002633
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002634 // could be null when this layer is using a layerStack
2635 // that is not visible on any display. Also can occur at
2636 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002637 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002638 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002639
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002640 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002641 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002642 if (hintDisplay) {
2643 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002644 }
Robert Carr2047fae2016-11-28 14:09:09 -08002645
2646 first = false;
2647 });
Mathias Agopian84300952012-11-21 16:02:13 -08002648 }
2649
2650
Mathias Agopian3559b072012-08-15 13:46:03 -07002651 /*
2652 * Perform our own transaction if needed
2653 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654
2655 if (mLayersAdded) {
2656 mLayersAdded = false;
2657 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002658 mVisibleRegionsDirty = true;
2659 }
2660
2661 // some layers might have been removed, so
2662 // we need to update the regions they're exposing.
2663 if (mLayersRemoved) {
2664 mLayersRemoved = false;
2665 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002666 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002668 // this layer is not visible anymore
2669 // TODO: we could traverse the tree from front to back and
2670 // compute the actual visible region
2671 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 Region visibleReg;
2673 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002674 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002675 }
Robert Carr2047fae2016-11-28 14:09:09 -08002676 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 }
2678
2679 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002680
2681 updateCursorAsync();
2682}
2683
2684void SurfaceFlinger::updateCursorAsync()
2685{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002687 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002688 continue;
2689 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002691 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2692 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002693 }
2694 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002695}
2696
2697void SurfaceFlinger::commitTransaction()
2698{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002699 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 for (const auto& l : mLayersPendingRemoval) {
2702 recordBufferingStats(l->getName().string(),
2703 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002704
2705 // We need to release the HWC layers when the Layer is removed
2706 // from the current state otherwise the HWC layer just continues
2707 // showing at its last configured state until we eventually
2708 // abandon the buffer queue.
2709 if (l->isRemovedFromCurrentState()) {
2710 l->destroyAllHwcLayers();
2711 l->releasePendingBuffer(systemTime());
2712 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 }
2714 mLayersPendingRemoval.clear();
2715 }
2716
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002717 // If this transaction is part of a window animation then the next frame
2718 // we composite should be considered an animation as well.
2719 mAnimCompositionPending = mAnimTransactionPending;
2720
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002722 // clear the "changed" flags in current state
2723 mCurrentState.colorMatrixChanged = false;
2724
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 mDrawingState.traverseInZOrder([](Layer* layer) {
2726 layer->commitChildList();
2727 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002728 mTransactionPending = false;
2729 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731}
2732
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002733void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2734 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002735 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 Region aboveOpaqueLayers;
2739 Region aboveCoveredLayers;
2740 Region dirty;
2741
Mathias Agopian87baae12012-07-31 12:38:26 -07002742 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
Robert Carr2047fae2016-11-28 14:09:09 -08002744 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002746 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Jesse Hall01e29052013-02-19 16:13:35 -08002748 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002750 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002751 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002752
Mathias Agopianab028732010-03-16 16:41:46 -07002753 /*
2754 * opaqueRegion: area of a surface that is fully opaque.
2755 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002757
2758 /*
2759 * visibleRegion: area of a surface that is visible on screen
2760 * and not fully transparent. This is essentially the layer's
2761 * footprint minus the opaque regions above it.
2762 * Areas covered by a translucent surface are considered visible.
2763 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002765
2766 /*
2767 * coveredRegion: area of a surface that is covered by all
2768 * visible regions above it (which includes the translucent areas).
2769 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002771
Jesse Halla8026d22012-09-25 13:25:04 -07002772 /*
2773 * transparentRegion: area of a surface that is hinted to be completely
2774 * transparent. This is only used to tell when the layer has no visible
2775 * non-transparent regions and can be removed from the layer list. It
2776 * does not affect the visibleRegion of this layer or any layers
2777 * beneath it. The hint may not be correct if apps don't respect the
2778 * SurfaceView restrictions (which, sadly, some don't).
2779 */
2780 Region transparentRegion;
2781
Mathias Agopianab028732010-03-16 16:41:46 -07002782
2783 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002784 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002785 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002788 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002789 if (!visibleRegion.isEmpty()) {
2790 // Remove the transparent area from the visible region
2791 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002792 if (tr.preserveRects()) {
2793 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002794 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002796 // transformation too complex, can't do the
2797 // transparent region optimization.
2798 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 }
Mathias Agopianab028732010-03-16 16:41:46 -07002800 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801
Mathias Agopianab028732010-03-16 16:41:46 -07002802 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002804 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002805 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002806 // the opaque region is the layer's footprint
2807 opaqueRegion = visibleRegion;
2808 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 }
2810 }
2811
Robert Carre5f4f692018-01-12 13:12:28 -08002812 if (visibleRegion.isEmpty()) {
2813 layer->clearVisibilityRegions();
2814 return;
2815 }
2816
Mathias Agopianab028732010-03-16 16:41:46 -07002817 // Clip the covered region to the visible region
2818 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2819
2820 // Update aboveCoveredLayers for next (lower) layer
2821 aboveCoveredLayers.orSelf(visibleRegion);
2822
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823 // subtract the opaque region covered by the layers above us
2824 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825
2826 // compute this layer's dirty region
2827 if (layer->contentDirty) {
2828 // we need to invalidate the whole region
2829 dirty = visibleRegion;
2830 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 layer->contentDirty = false;
2833 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002834 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002835 * the exposed region consists of two components:
2836 * 1) what's VISIBLE now and was COVERED before
2837 * 2) what's EXPOSED now less what was EXPOSED before
2838 *
2839 * note that (1) is conservative, we start with the whole
2840 * visible region but only keep what used to be covered by
2841 * something -- which mean it may have been exposed.
2842 *
2843 * (2) handles areas that were not covered by anything but got
2844 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002845 */
Mathias Agopianab028732010-03-16 16:41:46 -07002846 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 const Region oldVisibleRegion = layer->visibleRegion;
2848 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002849 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2850 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 }
2852 dirty.subtractSelf(aboveOpaqueLayers);
2853
2854 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002855 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856
Mathias Agopianab028732010-03-16 16:41:46 -07002857 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002859
Jesse Halla8026d22012-09-25 13:25:04 -07002860 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 layer->setVisibleRegion(visibleRegion);
2862 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002863 layer->setVisibleNonTransparentRegion(
2864 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002865 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866
Mathias Agopian87baae12012-07-31 12:38:26 -07002867 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868}
2869
Chia-I Wuab0c3192017-08-01 11:29:00 -07002870void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2873 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002874 }
2875 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002876}
2877
Dan Stoza6b9454d2014-11-07 16:00:59 -08002878bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 ALOGV("handlePageFlip");
2881
Brian Andersond6927fb2016-07-23 23:37:30 -07002882 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883
Mathias Agopian4fec8732012-06-29 14:12:52 -07002884 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002886 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002887
2888 // Store the set of layers that need updates. This set must not change as
2889 // buffers are being latched, as this could result in a deadlock.
2890 // Example: Two producers share the same command stream and:
2891 // 1.) Layer 0 is latched
2892 // 2.) Layer 0 gets a new frame
2893 // 2.) Layer 1 gets a new frame
2894 // 3.) Layer 1 is latched.
2895 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2896 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002897 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002898 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002899 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002900 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2901 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002902 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002903 } else {
2904 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002906 } else {
2907 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908 }
Robert Carr2047fae2016-11-28 14:09:09 -08002909 });
2910
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002912 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002913 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002914 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002915 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002916 newDataLatched = true;
2917 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002919
Alec Mouri86770e52018-09-24 22:40:58 +00002920 // Clear the renderengine fence here...
2921 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2922 // clear instead of sp::clear.
2923 getBE().flushFence = Fence::NO_FENCE;
2924
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002925 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002926
2927 // If we will need to wake up at some time in the future to deal with a
2928 // queued frame that shouldn't be displayed during this vsync period, wake
2929 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002930 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002931 signalLayerUpdate();
2932 }
2933
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002934 // enter boot animation on first buffer latch
2935 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2936 ALOGI("Enter boot animation");
2937 mBootStage = BootStage::BOOTANIMATION;
2938 }
2939
Dan Stoza6b9454d2014-11-07 16:00:59 -08002940 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002941 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942}
2943
Mathias Agopianad456f92011-01-13 17:53:01 -08002944void SurfaceFlinger::invalidateHwcGeometry()
2945{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002947}
2948
Alec Mouri8147b0e2018-10-09 20:57:19 -07002949void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002950 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002951 // We only need to actually compose the display if:
2952 // 1) It is being handled by hardware composer, which may need this to
2953 // keep its virtual display state machine in sync, or
2954 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002955 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002956 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002958 return;
2959 }
2960
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002962 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002963
2964 // swap buffers (presentation)
Alec Mouri8147b0e2018-10-09 20:57:19 -07002965 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966}
2967
Alec Mouri8147b0e2018-10-09 20:57:19 -07002968bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002970
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002971 const Region bounds(display->bounds());
2972 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002973 const auto displayId = display->getId();
2974 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002975 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002976
Peiyong Lind3788632018-09-18 16:01:31 -07002977 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002978 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002979 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002980
Alec Mouri8147b0e2018-10-09 20:57:19 -07002981 // Framebuffer will live in this scope for GPU composition.
2982 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
2983
Dan Stoza9e56aa02015-11-02 13:00:03 -08002984 if (hasClientComposition) {
2985 ALOGV("hasClientComposition");
2986
Alec Mouri8147b0e2018-10-09 20:57:19 -07002987 sp<GraphicBuffer> buf = display->dequeueBuffer();
2988
2989 if (buf == nullptr) {
2990 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
2991 "client composition for this frame",
2992 display->getDisplayName().c_str());
2993 return false;
2994 }
2995
2996 // Bind the framebuffer in this scope.
2997 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
2998 buf->getNativeBuffer());
2999
3000 if (fbo->getStatus() != NO_ERROR) {
3001 ALOGW("Binding buffer for display [%s] failed with status: %d",
3002 display->getDisplayName().c_str(), fbo->getStatus());
3003 return false;
3004 }
3005
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003006 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003007 if (display->hasWideColorGamut()) {
3008 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003009 }
3010 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003011 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003012 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003013
Dominik Laskowski7e045462018-05-30 13:02:02 -07003014 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003015 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3016 HWC2::Capability::SkipClientColorTransform);
3017
Peiyong Lind3788632018-09-18 16:01:31 -07003018 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003019 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3020 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003021 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003022 }
3023
Chia-I Wud49d6692018-06-27 07:17:41 +08003024 // The current enhanced saturation matrix is designed to enhance Display P3,
3025 // thus we only apply this matrix when the render intent is not colorimetric
3026 // and the output color space is Display P3.
3027 needsEnhancedColorMatrix =
3028 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3029 outputDataspace == Dataspace::DISPLAY_P3);
3030 if (needsEnhancedColorMatrix) {
3031 colorMatrix *= mEnhancedSaturationMatrix;
3032 }
3033
Alec Mouri8147b0e2018-10-09 20:57:19 -07003034 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003035
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003036 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003037 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003038 // when using overlays, we assume a fully transparent framebuffer
3039 // NOTE: we could reduce how much we need to clear, for instance
3040 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003041 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003042 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003043 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003044 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003045 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003046 // we're left with the letterbox region
3047 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003049
3050 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003051 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003052
Mathias Agopianb9494d52012-04-18 02:28:45 -07003053 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003054 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003055 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003056 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003057 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003058 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003059
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003060 const Rect& bounds = display->getBounds();
3061 const Rect& scissor = display->getScissor();
3062 if (scissor != bounds) {
3063 // scissor doesn't match the screen's dimensions, so we
3064 // need to clear everything outside of it and enable
3065 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003066
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003067 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003068 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003069 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003070 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003071
Mathias Agopian85d751c2012-08-29 16:59:24 -07003072 /*
3073 * and then, render the layers targeted at the framebuffer
3074 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003075
Dan Stoza9e56aa02015-11-02 13:00:03 -08003076 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003077 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003078 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003079 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003080 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003081 displayTransform.transform(layer->visibleRegion)));
3082 ALOGV("Layer: %s", layer->getName().string());
3083 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003084 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003085 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003086 case HWC2::Composition::Cursor:
3087 case HWC2::Composition::Device:
3088 case HWC2::Composition::Sideband:
3089 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003090 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003091 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003092 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003093 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3094 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003095 // never clear the very first layer since we're
3096 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003097 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003098 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003100 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003102 if (layer->hasColorTransform()) {
3103 mat4 tmpMatrix;
3104 if (applyColorMatrix) {
3105 tmpMatrix = mDrawingState.colorMatrix;
3106 }
3107 tmpMatrix *= layer->getColorTransform();
3108 if (needsEnhancedColorMatrix) {
3109 tmpMatrix *= mEnhancedSaturationMatrix;
3110 }
3111 getRenderEngine().setColorTransform(tmpMatrix);
3112 } else {
3113 getRenderEngine().setColorTransform(colorMatrix);
3114 }
David Sodmanc1498e62018-09-12 14:36:26 -07003115 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003116 break;
3117 }
3118 default:
3119 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003120 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003121 } else {
3122 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003123 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003124 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003125 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003126
Alec Mouri8147b0e2018-10-09 20:57:19 -07003127 // Perform some cleanup steps if we used client composition.
3128 if (hasClientComposition) {
3129 getRenderEngine().setColorTransform(mat4());
3130 getBE().mRenderEngine->disableScissor();
3131 display->finishBuffer();
3132 // Clear out error flags here so that we don't wait until next
3133 // composition to log.
3134 getRenderEngine().checkErrors();
3135 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003136 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137}
3138
Chia-I Wu28e3a252018-09-07 12:05:02 -07003139void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003140 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003141 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142}
3143
Dan Stoza7d89d062015-04-30 13:29:25 -07003144status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003145 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003146 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 const sp<Layer>& lbc,
3148 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003149{
Dan Stoza7d89d062015-04-30 13:29:25 -07003150 // add this layer to the current state list
3151 {
3152 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003153 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003154 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3155 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003156 return NO_MEMORY;
3157 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 if (parent == nullptr) {
3159 mCurrentState.layersSortedByZ.add(lbc);
3160 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003161 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003162 ALOGE("addClientLayer called with a removed parent");
3163 return NAME_NOT_FOUND;
3164 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 parent->addChild(lbc);
3166 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003167
Yiwei Zhang243b3782018-05-15 17:40:04 -07003168 if (gbc != nullptr) {
3169 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3170 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3171 mMaxGraphicBufferProducerListSize,
3172 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3173 mGraphicBufferProducerList.size(),
3174 mMaxGraphicBufferProducerListSize, mNumLayers);
3175 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003177 }
3178
Mathias Agopian96f08192010-06-02 23:28:45 -07003179 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003180 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003181
Dan Stoza7d89d062015-04-30 13:29:25 -07003182 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003183}
3184
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003185status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003186 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003187 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3188}
Robert Carr7f9b8992017-03-10 11:08:39 -08003189
Robert Carr2e102c92018-10-23 12:11:15 -07003190status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003191 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003192 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003193 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003194 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003195 if (topLevelOnly) {
3196 return NO_ERROR;
3197 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003198 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003199 } else {
3200 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003201 }
3202
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003203 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003204
3205 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003206 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003209uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003210 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003211}
3212
Mathias Agopian3f844832013-08-07 21:24:32 -07003213uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003214 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215}
3216
Mathias Agopian3f844832013-08-07 21:24:32 -07003217uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003218 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003219}
3220
3221uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003222 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003223 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003224 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003226 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 }
3228 return old;
3229}
3230
chaviwca27f252018-02-06 16:46:39 -08003231bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3232 for (const ComposerState& state : states) {
3233 // Here we need to check that the interface we're given is indeed
3234 // one of our own. A malicious client could give us a nullptr
3235 // IInterface, or one of its own or even one of our own but a
3236 // different type. All these situations would cause us to crash.
3237 if (state.client == nullptr) {
3238 return true;
3239 }
3240
3241 sp<IBinder> binder = IInterface::asBinder(state.client);
3242 if (binder == nullptr) {
3243 return true;
3244 }
3245
3246 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3247 return true;
3248 }
3249 }
3250 return false;
3251}
3252
Mathias Agopian8b33f032012-07-24 20:43:54 -07003253void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003254 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003255 const Vector<DisplayState>& displays,
3256 uint32_t flags)
3257{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003258 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003259 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003260 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003261
chaviwca27f252018-02-06 16:46:39 -08003262 if (containsAnyInvalidClientState(states)) {
3263 return;
3264 }
3265
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003266 if (flags & eAnimation) {
3267 // For window updates that are part of an animation we must wait for
3268 // previous animation "frames" to be handled.
3269 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003270 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003271 if (CC_UNLIKELY(err != NO_ERROR)) {
3272 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003273 // caller after a few seconds.
3274 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3275 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003276 mAnimTransactionPending = false;
3277 break;
3278 }
3279 }
3280 }
3281
chaviwca27f252018-02-06 16:46:39 -08003282 for (const DisplayState& display : displays) {
3283 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003284 }
3285
chaviwca27f252018-02-06 16:46:39 -08003286 for (const ComposerState& state : states) {
3287 transactionFlags |= setClientStateLocked(state);
3288 }
3289
3290 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3291 // as destroyed should only occur after setting all other states. This is to allow for a
3292 // child re-parent to happen before marking its original parent as destroyed (which would
3293 // then mark the child as destroyed).
3294 for (const ComposerState& state : states) {
3295 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003296 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003297
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003298 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3299 // anyway. This can be used as a flush mechanism for previous async transactions.
3300 // Empty animation transaction can be used to simulate back-pressure, so also force a
3301 // transaction for empty animation transactions.
3302 if (transactionFlags == 0 &&
3303 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003304 transactionFlags = eTransactionNeeded;
3305 }
3306
Mathias Agopian386aa982011-11-07 21:58:03 -08003307 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003308 if (mInterceptor->isEnabled()) {
3309 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003310 }
Irvel468051e2016-06-13 16:44:44 -07003311
Mathias Agopian386aa982011-11-07 21:58:03 -08003312 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003313 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3314 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003315 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003316
3317 // if this is a synchronous transaction, wait for it to take effect
3318 // before returning.
3319 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003320 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003321 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003322 if (flags & eAnimation) {
3323 mAnimTransactionPending = true;
3324 }
3325 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003326 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3327 if (CC_UNLIKELY(err != NO_ERROR)) {
3328 // just in case something goes wrong in SF, return to the
3329 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003330 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3331 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003332 break;
3333 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003334 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335 }
3336}
3337
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003338uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3339 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3340 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003341
Mathias Agopiane57f2922012-08-09 16:29:12 -07003342 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003343 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3344
3345 const uint32_t what = s.what;
3346 if (what & DisplayState::eSurfaceChanged) {
3347 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3348 state.surface = s.surface;
3349 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003350 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003351 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003352 if (what & DisplayState::eLayerStackChanged) {
3353 if (state.layerStack != s.layerStack) {
3354 state.layerStack = s.layerStack;
3355 flags |= eDisplayTransactionNeeded;
3356 }
3357 }
3358 if (what & DisplayState::eDisplayProjectionChanged) {
3359 if (state.orientation != s.orientation) {
3360 state.orientation = s.orientation;
3361 flags |= eDisplayTransactionNeeded;
3362 }
3363 if (state.frame != s.frame) {
3364 state.frame = s.frame;
3365 flags |= eDisplayTransactionNeeded;
3366 }
3367 if (state.viewport != s.viewport) {
3368 state.viewport = s.viewport;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 }
3372 if (what & DisplayState::eDisplaySizeChanged) {
3373 if (state.width != s.width) {
3374 state.width = s.width;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 if (state.height != s.height) {
3378 state.height = s.height;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 }
3382
Mathias Agopiane57f2922012-08-09 16:29:12 -07003383 return flags;
3384}
3385
Robert Carrd4ae7f32018-06-07 16:10:57 -07003386bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3387 IPCThreadState* ipc = IPCThreadState::self();
3388 const int pid = ipc->getCallingPid();
3389 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003390 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003391 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003392 return false;
3393 }
3394 return true;
3395}
3396
chaviwca27f252018-02-06 16:46:39 -08003397uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3398 const layer_state_t& s = composerState.state;
3399 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3400
Mathias Agopian13127d82013-03-05 17:47:11 -08003401 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003402 if (layer == nullptr) {
3403 return 0;
3404 }
3405
chaviw8b3871a2017-11-01 17:41:01 -07003406 uint32_t flags = 0;
3407
3408 const uint32_t what = s.what;
3409 bool geometryAppliesWithResize =
3410 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003411
3412 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3413 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003414 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003415 layer->pushPendingState();
3416 }
3417
chaviw8b3871a2017-11-01 17:41:01 -07003418 if (what & layer_state_t::ePositionChanged) {
3419 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3420 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003421 }
chaviw8b3871a2017-11-01 17:41:01 -07003422 }
3423 if (what & layer_state_t::eLayerChanged) {
3424 // NOTE: index needs to be calculated before we update the state
3425 const auto& p = layer->getParent();
3426 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003427 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003428 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003429 mCurrentState.layersSortedByZ.removeAt(idx);
3430 mCurrentState.layersSortedByZ.add(layer);
3431 // we need traversal (state changed)
3432 // AND transaction (list changed)
3433 flags |= eTransactionNeeded|eTraversalNeeded;
3434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 } else {
3436 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003437 flags |= eTransactionNeeded|eTraversalNeeded;
3438 }
3439 }
chaviw8b3871a2017-11-01 17:41:01 -07003440 }
3441 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003442 // NOTE: index needs to be calculated before we update the state
3443 const auto& p = layer->getParent();
3444 if (p == nullptr) {
3445 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3446 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3447 mCurrentState.layersSortedByZ.removeAt(idx);
3448 mCurrentState.layersSortedByZ.add(layer);
3449 // we need traversal (state changed)
3450 // AND transaction (list changed)
3451 flags |= eTransactionNeeded|eTraversalNeeded;
3452 }
3453 } else {
3454 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3455 flags |= eTransactionNeeded|eTraversalNeeded;
3456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 }
3458 }
3459 if (what & layer_state_t::eSizeChanged) {
3460 if (layer->setSize(s.w, s.h)) {
3461 flags |= eTraversalNeeded;
3462 }
3463 }
3464 if (what & layer_state_t::eAlphaChanged) {
3465 if (layer->setAlpha(s.alpha))
3466 flags |= eTraversalNeeded;
3467 }
3468 if (what & layer_state_t::eColorChanged) {
3469 if (layer->setColor(s.color))
3470 flags |= eTraversalNeeded;
3471 }
Peiyong Lind3788632018-09-18 16:01:31 -07003472 if (what & layer_state_t::eColorTransformChanged) {
3473 if (layer->setColorTransform(s.colorTransform)) {
3474 flags |= eTraversalNeeded;
3475 }
3476 }
chaviw8b3871a2017-11-01 17:41:01 -07003477 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003478 // TODO: b/109894387
3479 //
3480 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3481 // rotation. To see the problem observe that if we have a square parent, and a child
3482 // of the same size, then we rotate the child 45 degrees around it's center, the child
3483 // must now be cropped to a non rectangular 8 sided region.
3484 //
3485 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3486 // private API, and the WindowManager only uses rotation in one case, which is on a top
3487 // level layer in which cropping is not an issue.
3488 //
3489 // However given that abuse of rotation matrices could lead to surfaces extending outside
3490 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3491 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3492 // transformations.
3493 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003494 flags |= eTraversalNeeded;
3495 }
3496 if (what & layer_state_t::eTransparentRegionChanged) {
3497 if (layer->setTransparentRegionHint(s.transparentRegion))
3498 flags |= eTraversalNeeded;
3499 }
3500 if (what & layer_state_t::eFlagsChanged) {
3501 if (layer->setFlags(s.flags, s.mask))
3502 flags |= eTraversalNeeded;
3503 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003504 if (what & layer_state_t::eCropChanged_legacy) {
3505 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003506 flags |= eTraversalNeeded;
3507 }
chaviw8b3871a2017-11-01 17:41:01 -07003508 if (what & layer_state_t::eLayerStackChanged) {
3509 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3510 // We only allow setting layer stacks for top level layers,
3511 // everything else inherits layer stack from its parent.
3512 if (layer->hasParent()) {
3513 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3514 layer->getName().string());
3515 } else if (idx < 0) {
3516 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3517 "that also does not appear in the top level layer list. Something"
3518 " has gone wrong.", layer->getName().string());
3519 } else if (layer->setLayerStack(s.layerStack)) {
3520 mCurrentState.layersSortedByZ.removeAt(idx);
3521 mCurrentState.layersSortedByZ.add(layer);
3522 // we need traversal (state changed)
3523 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003524 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003525 }
3526 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003527 if (what & layer_state_t::eDeferTransaction_legacy) {
3528 if (s.barrierHandle_legacy != nullptr) {
3529 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3530 } else if (s.barrierGbp_legacy != nullptr) {
3531 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003532 if (authenticateSurfaceTextureLocked(gbp)) {
3533 const auto& otherLayer =
3534 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003535 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003536 } else {
3537 ALOGE("Attempt to defer transaction to to an"
3538 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003539 }
3540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 // We don't trigger a traversal here because if no other state is
3542 // changed, we don't want this to cause any more work
3543 }
3544 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003545 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003546 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003547 if (!hadParent) {
3548 mCurrentState.layersSortedByZ.remove(layer);
3549 }
chaviw8b3871a2017-11-01 17:41:01 -07003550 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003551 }
chaviw8b3871a2017-11-01 17:41:01 -07003552 }
3553 if (what & layer_state_t::eReparentChildren) {
3554 if (layer->reparentChildren(s.reparentHandle)) {
3555 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003556 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 if (what & layer_state_t::eDetachChildren) {
3559 layer->detachChildren();
3560 }
3561 if (what & layer_state_t::eOverrideScalingModeChanged) {
3562 layer->setOverrideScalingMode(s.overrideScalingMode);
3563 // We don't trigger a traversal here because if no other state is
3564 // changed, we don't want this to cause any more work
3565 }
Marissa Wall61c58622018-07-18 10:12:20 -07003566 if (what & layer_state_t::eTransformChanged) {
3567 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3568 }
3569 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3570 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3571 flags |= eTraversalNeeded;
3572 }
3573 if (what & layer_state_t::eCropChanged) {
3574 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3575 }
3576 if (what & layer_state_t::eBufferChanged) {
3577 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3578 }
3579 if (what & layer_state_t::eAcquireFenceChanged) {
3580 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3581 }
3582 if (what & layer_state_t::eDataspaceChanged) {
3583 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3584 }
3585 if (what & layer_state_t::eHdrMetadataChanged) {
3586 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3587 }
3588 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3589 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eApiChanged) {
3592 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3593 }
3594 if (what & layer_state_t::eSidebandStreamChanged) {
3595 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3596 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003597 return flags;
3598}
3599
chaviwca27f252018-02-06 16:46:39 -08003600void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3601 const layer_state_t& state = composerState.state;
3602 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3603
3604 sp<Layer> layer(client->getLayerUser(state.surface));
3605 if (layer == nullptr) {
3606 return;
3607 }
3608
chaviwca27f252018-02-06 16:46:39 -08003609 if (state.what & layer_state_t::eDestroySurface) {
3610 removeLayerLocked(mStateLock, layer);
3611 }
3612}
3613
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003615 const String8& name,
3616 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003618 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003619 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003620{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003621 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003622 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003623 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003625 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003626
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 status_t result = NO_ERROR;
3628
3629 sp<Layer> layer;
3630
Cody Northropbc755282017-03-31 12:00:08 -06003631 String8 uniqueName = getUniqueLayerName(name);
3632
Mathias Agopian3165cc22012-08-08 19:42:09 -07003633 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003634 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003635 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3636 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003639 case ISurfaceComposerClient::eFXSurfaceBufferState:
3640 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3641 break;
chaviw13fdc492017-06-27 12:40:18 -07003642 case ISurfaceComposerClient::eFXSurfaceColor:
3643 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003644 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003645 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003647 case ISurfaceComposerClient::eFXSurfaceContainer:
3648 result = createContainerLayer(client,
3649 uniqueName, w, h, flags,
3650 handle, &layer);
3651 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003652 default:
3653 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654 break;
3655 }
3656
Dan Stoza7d89d062015-04-30 13:29:25 -07003657 if (result != NO_ERROR) {
3658 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003659 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003660
Chia-I Wuab0c3192017-08-01 11:29:00 -07003661 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3662 // TODO b/64227542
3663 if (windowType == 441731) {
3664 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3665 layer->setPrimaryDisplayOnly();
3666 }
3667
Albert Chaulk479c60c2017-01-27 14:21:34 -05003668 layer->setInfo(windowType, ownerUid);
3669
Robert Carr1f0a16a2016-10-24 16:27:39 -07003670 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003671 if (result != NO_ERROR) {
3672 return result;
3673 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003674 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003675
3676 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003677 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678}
3679
Cody Northropbc755282017-03-31 12:00:08 -06003680String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3681{
3682 bool matchFound = true;
3683 uint32_t dupeCounter = 0;
3684
3685 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3686 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3687
Dan Stoza436ccf32018-06-21 12:10:12 -07003688 // Grab the state lock since we're accessing mCurrentState
3689 Mutex::Autolock lock(mStateLock);
3690
Cody Northropbc755282017-03-31 12:00:08 -06003691 // Loop over layers until we're sure there is no matching name
3692 while (matchFound) {
3693 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003694 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003695 if (layer->getName() == uniqueName) {
3696 matchFound = true;
3697 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3698 }
3699 });
3700 }
3701
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003702 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3703 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003704
3705 return uniqueName;
3706}
3707
Marissa Wallfd668622018-05-10 10:21:13 -07003708status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3709 uint32_t w, uint32_t h, uint32_t flags,
3710 PixelFormat& format, sp<IBinder>* handle,
3711 sp<IGraphicBufferProducer>* gbp,
3712 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003714 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 case PIXEL_FORMAT_TRANSPARENT:
3716 case PIXEL_FORMAT_TRANSLUCENT:
3717 format = PIXEL_FORMAT_RGBA_8888;
3718 break;
3719 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003720 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003721 break;
3722 }
3723
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003724 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003725 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003726 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003727 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003728 *handle = layer->getHandle();
3729 *gbp = layer->getProducer();
3730 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003732
Marissa Wallfd668622018-05-10 10:21:13 -07003733 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003734 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003735}
3736
Marissa Wall61c58622018-07-18 10:12:20 -07003737status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3738 uint32_t w, uint32_t h, uint32_t flags,
3739 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003740 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003741 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003742 *handle = layer->getHandle();
3743 *outLayer = layer;
3744
3745 return NO_ERROR;
3746}
3747
chaviw13fdc492017-06-27 12:40:18 -07003748status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003749 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003750 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003751{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003752 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003753 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003754 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003755}
3756
Robert Carr6b3f6c52018-08-13 13:05:17 -07003757status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3758 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3759 sp<IBinder>* handle, sp<Layer>* outLayer)
3760{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003761 *outLayer =
3762 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003763 *handle = (*outLayer)->getHandle();
3764 return NO_ERROR;
3765}
3766
3767
Mathias Agopianac9fa422013-02-11 16:40:36 -08003768status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769{
Robert Carr9524cb32017-02-13 11:32:32 -08003770 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003771 status_t err = NO_ERROR;
3772 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003773 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003774 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003775 err = removeLayer(l);
3776 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3777 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003778 }
3779 return err;
3780}
3781
Robert Carr2e102c92018-10-23 12:11:15 -07003782void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3783 mLayersPendingRemoval.add(layer);
3784 mLayersRemoved = true;
3785 setTransactionFlags(eTransactionNeeded);
3786}
3787
3788void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003789{
Robert Carr2e102c92018-10-23 12:11:15 -07003790 Mutex::Autolock lock(mStateLock);
3791 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003792}
3793
Mathias Agopianb60314a2012-04-10 22:09:54 -07003794// ---------------------------------------------------------------------------
3795
Andy McFadden13a082e2012-08-24 10:16:42 -07003796void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003797 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003798 if (!displayToken) return;
3799
Jesse Hall01e29052013-02-19 16:13:35 -08003800 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003801 Vector<ComposerState> state;
3802 Vector<DisplayState> displays;
3803 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003804 d.what = DisplayState::eDisplayProjectionChanged |
3805 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003806 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003807 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003808 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003809 d.frame.makeInvalid();
3810 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003811 d.width = 0;
3812 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003813 displays.add(d);
3814 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003815
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003816 const auto display = getDisplayDevice(displayToken);
3817 if (!display) return;
3818
3819 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3820
Dominik Laskowski075d3172018-05-24 15:50:06 -07003821 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003822 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003823 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003824
Brian Andersond0010582017-03-07 13:20:31 -08003825 // Use phase of 0 since phase is not known.
3826 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003827 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3828 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003829}
3830
3831void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003832 // Async since we may be called from the main thread.
3833 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003834}
3835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003836void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3837 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003838 if (display->isVirtual()) {
3839 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003840 return;
3841 }
3842
Dominik Laskowski075d3172018-05-24 15:50:06 -07003843 const auto displayId = display->getId();
3844 LOG_ALWAYS_FATAL_IF(!displayId);
3845
3846 ALOGD("Setting power mode %d on display %" PRIu64, mode, *displayId);
3847
3848 int currentMode = display->getPowerMode();
3849 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003850 return;
3851 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003853 display->setPowerMode(mode);
3854
Lloyd Pique4dccc412018-01-22 17:21:36 -08003855 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003856 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003857 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003858 if (idx < 0) {
3859 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3860 return;
3861 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003862 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003863 }
3864
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003865 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003866 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003867 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003868 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003869 if (mUseScheduler) {
3870 mScheduler->onScreenAcquired(mAppConnectionHandle);
3871 } else {
3872 mEventThread->onScreenAcquired();
3873 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003874 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003875 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003876
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003877 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003878 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003879 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003880
3881 struct sched_param param = {0};
3882 param.sched_priority = 1;
3883 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3884 ALOGW("Couldn't set SCHED_FIFO on display on");
3885 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003886 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003887 // Turn off the display
3888 struct sched_param param = {0};
3889 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3890 ALOGW("Couldn't set SCHED_OTHER on display off");
3891 }
3892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003893 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003894 if (mUseScheduler) {
3895 mScheduler->disableHardwareVsync(true);
3896 } else {
3897 disableHardwareVsync(true); // also cancels any in-progress resync
3898 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003899 if (mUseScheduler) {
3900 mScheduler->onScreenReleased(mAppConnectionHandle);
3901 } else {
3902 mEventThread->onScreenReleased();
3903 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003904 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003905
Dominik Laskowski075d3172018-05-24 15:50:06 -07003906 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003907 mVisibleRegionsDirty = true;
3908 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003909 } else if (mode == HWC_POWER_MODE_DOZE ||
3910 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003911 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003912 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003913 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003914 if (mUseScheduler) {
3915 mScheduler->onScreenAcquired(mAppConnectionHandle);
3916 } else {
3917 mEventThread->onScreenAcquired();
3918 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003919 resyncToHardwareVsync(true);
3920 }
3921 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3922 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003923 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003924 if (mUseScheduler) {
3925 mScheduler->disableHardwareVsync(true);
3926 } else {
3927 disableHardwareVsync(true); // also cancels any in-progress resync
3928 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003929 if (mUseScheduler) {
3930 mScheduler->onScreenReleased(mAppConnectionHandle);
3931 } else {
3932 mEventThread->onScreenReleased();
3933 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003934 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003935 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003936 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003937 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003938 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003939 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003940
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003941 if (display->isPrimary()) {
3942 mTimeStats.setPowerMode(mode);
3943 }
3944
Dominik Laskowski075d3172018-05-24 15:50:06 -07003945 ALOGD("Finished setting power mode %d on display %" PRIu64, mode, *displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003946}
3947
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003948void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003949 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003950 const auto display = getDisplayDevice(displayToken);
3951 if (!display) {
3952 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3953 displayToken.get());
3954 } else if (display->isVirtual()) {
3955 ALOGW("Attempt to set power mode %d for virtual display", mode);
3956 } else {
3957 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003958 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003959 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003960}
3961
3962// ---------------------------------------------------------------------------
3963
Lloyd Pique755e3192018-01-31 16:46:15 -08003964status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3965 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003967
Mathias Agopianbd115332013-04-18 16:41:04 -07003968 IPCThreadState* ipc = IPCThreadState::self();
3969 const int pid = ipc->getCallingPid();
3970 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003971
Mathias Agopianbd115332013-04-18 16:41:04 -07003972 if ((uid != AID_SHELL) &&
3973 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003974 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003975 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003976 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003977 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003978 // (this would indicate SF is stuck, but we want to be able to
3979 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003980 status_t err = mStateLock.timedLock(s2ns(1));
3981 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003982 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003983 result.appendFormat(
3984 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3985 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003986 }
3987
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003988 bool dumpAll = true;
3989 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003990 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003991
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003992 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003993 if ((index < numArgs) &&
3994 (args[index] == String16("--list"))) {
3995 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003996 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003997 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003998 }
3999
4000 if ((index < numArgs) &&
4001 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004002 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004003 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004004 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004005 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004006
4007 if ((index < numArgs) &&
4008 (args[index] == String16("--latency-clear"))) {
4009 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004010 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004011 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004012 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004013
4014 if ((index < numArgs) &&
4015 (args[index] == String16("--dispsync"))) {
4016 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004017 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004018 dumpAll = false;
4019 }
Dan Stozab90cf072015-03-05 11:05:59 -08004020
4021 if ((index < numArgs) &&
4022 (args[index] == String16("--static-screen"))) {
4023 index++;
4024 dumpStaticScreenStats(result);
4025 dumpAll = false;
4026 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004027
4028 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004029 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004030 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004031 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004032 dumpAll = false;
4033 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004034
4035 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4036 index++;
4037 dumpWideColorInfo(result);
4038 dumpAll = false;
4039 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004040
4041 if ((index < numArgs) &&
4042 (args[index] == String16("--enable-layer-stats"))) {
4043 index++;
4044 mLayerStats.enable();
4045 dumpAll = false;
4046 }
4047
4048 if ((index < numArgs) &&
4049 (args[index] == String16("--disable-layer-stats"))) {
4050 index++;
4051 mLayerStats.disable();
4052 dumpAll = false;
4053 }
4054
4055 if ((index < numArgs) &&
4056 (args[index] == String16("--clear-layer-stats"))) {
4057 index++;
4058 mLayerStats.clear();
4059 dumpAll = false;
4060 }
4061
4062 if ((index < numArgs) &&
4063 (args[index] == String16("--dump-layer-stats"))) {
4064 index++;
4065 mLayerStats.dump(result);
4066 dumpAll = false;
4067 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004068
4069 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004070 (args[index] == String16("--frame-composition"))) {
4071 index++;
4072 dumpFrameCompositionInfo(result);
4073 dumpAll = false;
4074 }
4075
4076 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004077 (args[index] == String16("--display-identification"))) {
4078 index++;
4079 dumpDisplayIdentificationData(result);
4080 dumpAll = false;
4081 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004082
4083 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4084 index++;
4085 mTimeStats.parseArgs(asProto, args, index, result);
4086 dumpAll = false;
4087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004089
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004090 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004091 if (asProto) {
4092 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4093 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4094 } else {
4095 dumpAllLocked(args, index, result);
4096 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004097 }
4098
Mathias Agopian9795c422009-08-26 16:36:26 -07004099 if (locked) {
4100 mStateLock.unlock();
4101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102 }
4103 write(fd, result.string(), result.size());
4104 return NO_ERROR;
4105}
4106
Dan Stozac7014012014-02-14 15:03:43 -08004107void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4108 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004109{
Robert Carr2047fae2016-11-28 14:09:09 -08004110 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004111 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004112 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004113}
4114
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004115void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004116 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004117{
4118 String8 name;
4119 if (index < args.size()) {
4120 name = String8(args[index]);
4121 index++;
4122 }
4123
Dominik Laskowski075d3172018-05-24 15:50:06 -07004124 if (const auto displayId = getInternalDisplayId();
4125 displayId && getHwComposer().isConnected(*displayId)) {
4126 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004127 const nsecs_t period = activeConfig->getVsyncPeriod();
4128 result.appendFormat("%" PRId64 "\n", period);
4129 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004130
4131 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004132 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004133 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004134 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004135 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004136 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004137 }
Robert Carr2047fae2016-11-28 14:09:09 -08004138 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004139 }
4140}
4141
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004142void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004143 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144{
4145 String8 name;
4146 if (index < args.size()) {
4147 name = String8(args[index]);
4148 index++;
4149 }
4150
Robert Carr2047fae2016-11-28 14:09:09 -08004151 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004152 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004153 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004154 }
Robert Carr2047fae2016-11-28 14:09:09 -08004155 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004156
Svetoslavd85084b2014-03-20 10:28:31 -07004157 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004158}
4159
Jamie Gennis6547ff42013-07-16 20:12:42 -07004160// This should only be called from the main thread. Otherwise it would need
4161// the lock and should use mCurrentState rather than mDrawingState.
4162void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004163 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004164 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004165 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004166
4167 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4168}
4169
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004170void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004171{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004172 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004173
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004174 if (isLayerTripleBufferingDisabled())
4175 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004176
4177 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004178 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004179 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004180 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004181 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4182 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004183 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004184}
4185
Dan Stozab90cf072015-03-05 11:05:59 -08004186void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4187{
4188 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004189 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4190 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004191 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004192 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004193 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4194 b + 1, bucketTimeSec, percent);
4195 }
David Sodman4a36e932017-11-07 14:29:47 -08004196 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004197 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004198 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004199 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004200 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004201}
4202
Dan Stozae77c7662016-05-13 11:37:28 -07004203void SurfaceFlinger::recordBufferingStats(const char* layerName,
4204 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004205 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4206 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004207 for (const auto& segment : history) {
4208 if (!segment.usedThirdBuffer) {
4209 stats.twoBufferTime += segment.totalTime;
4210 }
4211 if (segment.occupancyAverage < 1.0f) {
4212 stats.doubleBufferedTime += segment.totalTime;
4213 } else if (segment.occupancyAverage < 2.0f) {
4214 stats.tripleBufferedTime += segment.totalTime;
4215 }
4216 ++stats.numSegments;
4217 stats.totalTime += segment.totalTime;
4218 }
4219}
4220
Brian Andersond6927fb2016-07-23 23:37:30 -07004221void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4222 result.appendFormat("Layer frame timestamps:\n");
4223
4224 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4225 const size_t count = currentLayers.size();
4226 for (size_t i=0 ; i<count ; i++) {
4227 currentLayers[i]->dumpFrameEvents(result);
4228 }
4229}
4230
Dan Stozae77c7662016-05-13 11:37:28 -07004231void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4232 result.append("Buffering stats:\n");
4233 result.append(" [Layer name] <Active time> <Two buffer> "
4234 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004235 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004236 typedef std::tuple<std::string, float, float, float> BufferTuple;
4237 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004238 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004239 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004240 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004241 if (stats.numSegments == 0) {
4242 continue;
4243 }
4244 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4245 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4246 stats.totalTime;
4247 float doubleBufferRatio = static_cast<float>(
4248 stats.doubleBufferedTime) / stats.totalTime;
4249 float tripleBufferRatio = static_cast<float>(
4250 stats.tripleBufferedTime) / stats.totalTime;
4251 sorted.insert({activeTime, {name, twoBufferRatio,
4252 doubleBufferRatio, tripleBufferRatio}});
4253 }
4254 for (const auto& sortedPair : sorted) {
4255 float activeTime = sortedPair.first;
4256 const BufferTuple& values = sortedPair.second;
4257 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4258 std::get<0>(values).c_str(), activeTime,
4259 std::get<1>(values), std::get<2>(values),
4260 std::get<3>(values));
4261 }
4262 result.append("\n");
4263}
4264
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004265void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004266 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004267 const auto displayId = display->getId();
4268 if (!displayId) {
4269 continue;
4270 }
4271 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004272 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004273 continue;
4274 }
4275
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 result.appendFormat("Display %" PRIu64 " (HWC display %" PRIu64 "): ", *displayId,
4277 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004278 uint8_t port;
4279 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004280 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004281 result.append("no identification data\n");
4282 continue;
4283 }
4284
4285 if (!isEdid(data)) {
4286 result.append("unknown identification data: ");
4287 for (uint8_t byte : data) {
4288 result.appendFormat("%x ", byte);
4289 }
4290 result.append("\n");
4291 continue;
4292 }
4293
4294 const auto edid = parseEdid(data);
4295 if (!edid) {
4296 result.append("invalid EDID: ");
4297 for (uint8_t byte : data) {
4298 result.appendFormat("%x ", byte);
4299 }
4300 result.append("\n");
4301 continue;
4302 }
4303
4304 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4305 result.append(edid->displayName.data(), edid->displayName.length());
4306 result.append("\"\n");
4307 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004308}
4309
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004310void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004311 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4312 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004313 result.appendFormat("DisplayColorSetting: %s\n",
4314 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004315
4316 // TODO: print out if wide-color mode is active or not
4317
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004318 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004319 const auto displayId = display->getId();
4320 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004321 continue;
4322 }
4323
Dominik Laskowski075d3172018-05-24 15:50:06 -07004324 result.appendFormat("Display %" PRIu64 " color modes:\n", *displayId);
4325 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004326 for (auto&& mode : modes) {
4327 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4328 }
4329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004330 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004331 result.appendFormat(" Current color mode: %s (%d)\n",
4332 decodeColorMode(currentMode).c_str(), currentMode);
4333 }
4334 result.append("\n");
4335}
4336
David Sodman7e4ae112018-02-09 15:02:28 -08004337void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4338 std::string stringResult;
4339
4340 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004341 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4342 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004343 continue;
4344 }
4345
Dominik Laskowski05275f12018-11-01 15:03:24 -07004346 const auto& compositionInfoList = it->second;
4347 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004348 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4349 for (const auto& compositionInfo : compositionInfoList) {
4350 compositionInfo.dump(stringResult, nullptr);
4351 stringResult += base::StringPrintf("\n");
4352 }
4353 }
4354
4355 result.append(stringResult.c_str());
4356}
4357
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004358LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004359 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004360 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4361 const State& state = useDrawing ? mDrawingState : mCurrentState;
4362 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004363 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004364 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004365 });
4366
4367 return layersProto;
4368}
4369
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004370LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004371 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004372
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004373 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004374 resolution->set_w(display.getWidth());
4375 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004377 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4378 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4379 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004380
Dominik Laskowski075d3172018-05-24 15:50:06 -07004381 const auto displayId = display.getId();
4382 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004383 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004384 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004385 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004386 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004387 }
4388 });
4389
4390 return layersProto;
4391}
4392
Mathias Agopian74d211a2013-04-22 16:55:35 +02004393void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4394 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004396 bool colorize = false;
4397 if (index < args.size()
4398 && (args[index] == String16("--color"))) {
4399 colorize = true;
4400 index++;
4401 }
4402
4403 Colorizer colorizer(colorize);
4404
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405 // figure out if we're stuck somewhere
4406 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004407 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4409
4410 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004411 * Dump library configuration.
4412 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413
4414 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004415 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004417 appendSfConfigString(result);
4418 appendUiConfigString(result);
4419 appendGuiConfigString(result);
4420 result.append("\n");
4421
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004422 result.append("\nDisplay identification data:\n");
4423 dumpDisplayIdentificationData(result);
4424
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004425 result.append("\nWide-Color information:\n");
4426 dumpWideColorInfo(result);
4427
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004429 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004430 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004431 result.append(SyncFeatures::getInstance().toString());
4432 result.append("\n");
4433
Andy McFadden41d67d72014-04-25 16:58:34 -07004434 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004435 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004436 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004437
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004438 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4439 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 if (const auto displayId = getInternalDisplayId();
4441 displayId && getHwComposer().isConnected(*displayId)) {
4442 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
4443 result.appendFormat("Display %" PRIu64 ": app phase %" PRId64 " ns, "
4444 "sf phase %" PRId64 " ns, "
4445 "early app phase %" PRId64 " ns, "
4446 "early sf phase %" PRId64 " ns, "
4447 "early app gl phase %" PRId64 " ns, "
4448 "early sf gl phase %" PRId64 " ns, "
4449 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4450 *displayId, vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset,
4451 sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4452 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004453 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004454 result.append("\n");
4455
Dan Stozab90cf072015-03-05 11:05:59 -08004456 // Dump static screen stats
4457 result.append("\n");
4458 dumpStaticScreenStats(result);
4459 result.append("\n");
4460
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004461 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4462
Dan Stozae77c7662016-05-13 11:37:28 -07004463 dumpBufferingStats(result);
4464
Andy McFadden4803b742012-09-24 19:07:20 -07004465 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004466 * Dump the visible layer list
4467 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004468 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004469 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004470 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4471 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004472 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004473
Chia-I Wu2f884132018-09-13 15:17:58 -07004474 {
4475 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4476 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4477 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4478 result.append("\n");
4479 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004480
David Sodman7e4ae112018-02-09 15:02:28 -08004481 result.append("\nFrame-Composition information:\n");
4482 dumpFrameCompositionInfo(result);
4483 result.append("\n");
4484
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004485 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004486 * Dump Display state
4487 */
4488
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004489 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004490 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004491 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004492 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004493 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004494 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004495 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004496
4497 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004498 * Dump SurfaceFlinger global state
4499 */
4500
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004501 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004502 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004503 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504
David Sodmanbc815282017-11-05 18:57:52 -08004505 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004506
Dominik Laskowski075d3172018-05-24 15:50:06 -07004507 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004508 display->undefinedRegion.dump(result, "undefinedRegion");
4509 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4510 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004511 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004512 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004513 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004514 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004515
Dominik Laskowski075d3172018-05-24 15:50:06 -07004516 if (const auto displayId = getInternalDisplayId();
4517 displayId && getHwComposer().isConnected(*displayId)) {
4518 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004519 result.appendFormat(" refresh-rate : %f fps\n"
4520 " x-dpi : %f\n"
4521 " y-dpi : %f\n",
4522 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4523 activeConfig->getDpiY());
4524 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004525
Mathias Agopian74d211a2013-04-22 16:55:35 +02004526 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004527 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004528
Ana Krulec98b5b242018-08-10 15:03:23 -07004529 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004530 /*
4531 * VSYNC state
4532 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004533 if (mUseScheduler) {
4534 mScheduler->dump(mAppConnectionHandle, result);
4535 } else {
4536 mEventThread->dump(result);
4537 }
Dan Stozae22aec72016-08-01 13:20:59 -07004538 result.append("\n");
4539
4540 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004541 * Tracing state
4542 */
4543 mTracing.dump(result);
4544 result.append("\n");
4545
4546 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004547 * HWC layer minidump
4548 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004549 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004550 const auto displayId = display->getId();
4551 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004552 continue;
4553 }
4554
Dominik Laskowski075d3172018-05-24 15:50:06 -07004555 result.appendFormat("Display %" PRIu64 " HWC layers:\n", *displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004556 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004557 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004558 result.append("\n");
4559 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560
4561 /*
4562 * Dump HWComposer state
4563 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004564 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004565 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004566 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004567 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004568 result.appendFormat(" h/w composer %s\n",
4569 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004570 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004571
4572 /*
4573 * Dump gralloc state
4574 */
4575 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4576 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004577
4578 /*
4579 * Dump VrFlinger state if in use.
4580 */
4581 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4582 result.append("VrFlinger state:\n");
4583 result.append(mVrFlinger->Dump().c_str());
4584 result.append("\n");
4585 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004586}
4587
Dominik Laskowski075d3172018-05-24 15:50:06 -07004588const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004589 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004590 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004591 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004592 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004593 }
4594 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004595
Dominik Laskowski075d3172018-05-24 15:50:06 -07004596 ALOGE("%s: Invalid display %" PRIu64, __FUNCTION__, displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004597 static const Vector<sp<Layer>> empty;
4598 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004599}
4600
Keun young Park63f165f2012-08-31 10:53:36 -07004601bool SurfaceFlinger::startDdmConnection()
4602{
4603 void* libddmconnection_dso =
4604 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4605 if (!libddmconnection_dso) {
4606 return false;
4607 }
4608 void (*DdmConnection_start)(const char* name);
4609 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004610 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004611 if (!DdmConnection_start) {
4612 dlclose(libddmconnection_dso);
4613 return false;
4614 }
4615 (*DdmConnection_start)(getServiceName());
4616 return true;
4617}
4618
Chia-I Wu28f320b2018-05-03 11:02:56 -07004619void SurfaceFlinger::updateColorMatrixLocked() {
4620 mat4 colorMatrix;
4621 if (mGlobalSaturationFactor != 1.0f) {
4622 // Rec.709 luma coefficients
4623 float3 luminance{0.213f, 0.715f, 0.072f};
4624 luminance *= 1.0f - mGlobalSaturationFactor;
4625 mat4 saturationMatrix = mat4(
4626 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4627 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4628 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4629 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4630 );
4631 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4632 } else {
4633 colorMatrix = mClientColorMatrix * mDaltonizer();
4634 }
4635
4636 if (mCurrentState.colorMatrix != colorMatrix) {
4637 mCurrentState.colorMatrix = colorMatrix;
4638 mCurrentState.colorMatrixChanged = true;
4639 setTransactionFlags(eTransactionNeeded);
4640 }
4641}
4642
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004643status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004644#pragma clang diagnostic push
4645#pragma clang diagnostic error "-Wswitch-enum"
4646 switch (static_cast<ISurfaceComposerTag>(code)) {
4647 // These methods should at minimum make sure that the client requested
4648 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004649 case BOOT_FINISHED:
4650 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004651 case CREATE_CONNECTION:
4652 case CREATE_DISPLAY:
4653 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004654 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004655 case GET_ACTIVE_COLOR_MODE:
4656 case GET_ANIMATION_FRAME_STATS:
4657 case GET_HDR_CAPABILITIES:
4658 case SET_ACTIVE_CONFIG:
4659 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004660 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004661 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004662 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4663 IPCThreadState* ipc = IPCThreadState::self();
4664 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4665 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004666 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004667 }
Robert Carr1db73f62016-12-21 12:58:51 -08004668 return OK;
4669 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004670 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004671 IPCThreadState* ipc = IPCThreadState::self();
4672 const int pid = ipc->getCallingPid();
4673 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004674 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4675 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004676 return PERMISSION_DENIED;
4677 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004678 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004680 // Used by apps to hook Choreographer to SurfaceFlinger.
4681 case CREATE_DISPLAY_EVENT_CONNECTION:
4682 // The following calls are currently used by clients that do not
4683 // request necessary permissions. However, they do not expose any secret
4684 // information, so it is OK to pass them.
4685 case AUTHENTICATE_SURFACE:
4686 case GET_ACTIVE_CONFIG:
4687 case GET_BUILT_IN_DISPLAY:
4688 case GET_DISPLAY_COLOR_MODES:
4689 case GET_DISPLAY_CONFIGS:
4690 case GET_DISPLAY_STATS:
4691 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4692 // Calling setTransactionState is safe, because you need to have been
4693 // granted a reference to Client* and Handle* to do anything with it.
4694 case SET_TRANSACTION_STATE:
4695 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004696 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004697 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004698 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004699 return OK;
4700 }
4701 case CAPTURE_LAYERS:
4702 case CAPTURE_SCREEN: {
4703 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004704 IPCThreadState* ipc = IPCThreadState::self();
4705 const int pid = ipc->getCallingPid();
4706 const int uid = ipc->getCallingUid();
4707 if ((uid != AID_GRAPHICS) &&
4708 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4709 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4710 return PERMISSION_DENIED;
4711 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004712 return OK;
4713 }
4714 // The following codes are deprecated and should never be allowed to access SF.
4715 case CONNECT_DISPLAY_UNUSED:
4716 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4717 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4718 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004720 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004721
4722 // These codes are used for the IBinder protocol to either interrogate the recipient
4723 // side of the transaction for its canonical interface descriptor or to dump its state.
4724 // We let them pass by default.
4725 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4726 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4727 code == IBinder::SYSPROPS_TRANSACTION) {
4728 return OK;
4729 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004730 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004732 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004733 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4734 return OK;
4735 }
4736 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4737 return PERMISSION_DENIED;
4738#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004739}
4740
Ana Krulec13be8ad2018-08-21 02:43:56 +00004741status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4742 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004743 status_t credentialCheck = CheckTransactCodeCredentials(code);
4744 if (credentialCheck != OK) {
4745 return credentialCheck;
4746 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004747
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004748 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4749 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004750 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004751 IPCThreadState* ipc = IPCThreadState::self();
4752 const int uid = ipc->getCallingUid();
4753 if (CC_UNLIKELY(uid != AID_SYSTEM
4754 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004755 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004756 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004757 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 return PERMISSION_DENIED;
4759 }
4760 int n;
4761 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004762 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004763 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004764 return NO_ERROR;
4765 case 1002: // SHOW_UPDATES
4766 n = data.readInt32();
4767 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004768 invalidateHwcGeometry();
4769 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004770 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004772 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004773 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004775 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004776 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004777 setTransactionFlags(
4778 eTransactionNeeded|
4779 eDisplayTransactionNeeded|
4780 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004781 return NO_ERROR;
4782 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004783 case 1006:{ // send empty update
4784 signalRefresh();
4785 return NO_ERROR;
4786 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004787 case 1008: // toggle use of hw composer
4788 n = data.readInt32();
4789 mDebugDisableHWC = n ? 1 : 0;
4790 invalidateHwcGeometry();
4791 repaintEverything();
4792 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004793 case 1009: // toggle use of transform hint
4794 n = data.readInt32();
4795 mDebugDisableTransformHint = n ? 1 : 0;
4796 invalidateHwcGeometry();
4797 repaintEverything();
4798 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004800 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004801 reply->writeInt32(0);
4802 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004803 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004804 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004805 return NO_ERROR;
4806 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004807 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004808 if (!display) {
4809 return NAME_NOT_FOUND;
4810 }
4811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004812 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004813 return NO_ERROR;
4814 }
4815 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004816 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004817 // daltonize
4818 n = data.readInt32();
4819 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004820 case 1:
4821 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4822 break;
4823 case 2:
4824 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4825 break;
4826 case 3:
4827 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4828 break;
4829 default:
4830 mDaltonizer.setType(ColorBlindnessType::None);
4831 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004832 }
4833 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004834 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004835 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004836 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004837 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838
4839 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004840 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004841 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004842 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004843 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004844 // apply a color matrix
4845 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004846 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004847 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004848 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004849 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004850 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004851 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004852 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004853 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004854 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004855 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004856
4857 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4858 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004859 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004860 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4861 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4862 }
4863
Chia-I Wu28f320b2018-05-03 11:02:56 -07004864 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 return NO_ERROR;
4866 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004867 // This is an experimental interface
4868 // Needs to be shifted to proper binder interface when we productize
4869 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004870 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004871 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004872 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004873 return NO_ERROR;
4874 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004875 case 1017: {
4876 n = data.readInt32();
4877 mForceFullDamage = static_cast<bool>(n);
4878 return NO_ERROR;
4879 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004880 case 1018: { // Modify Choreographer's phase offset
4881 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004882 if (mUseScheduler) {
4883 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4884 } else {
4885 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4886 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004887 return NO_ERROR;
4888 }
4889 case 1019: { // Modify SurfaceFlinger's phase offset
4890 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004891 if (mUseScheduler) {
4892 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4893 } else {
4894 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4895 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004896 return NO_ERROR;
4897 }
Irvel468051e2016-06-13 16:44:44 -07004898 case 1020: { // Layer updates interceptor
4899 n = data.readInt32();
4900 if (n) {
4901 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004902 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004903 }
4904 else{
4905 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004906 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004907 }
4908 return NO_ERROR;
4909 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004910 case 1021: { // Disable HWC virtual displays
4911 n = data.readInt32();
4912 mUseHwcVirtualDisplays = !n;
4913 return NO_ERROR;
4914 }
Romain Guy0147a172017-06-01 13:53:56 -07004915 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004916 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004917 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004918
Chia-I Wu28f320b2018-05-03 11:02:56 -07004919 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004920 return NO_ERROR;
4921 }
Romain Guy54f154a2017-10-24 21:40:32 +01004922 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004923 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004924 invalidateHwcGeometry();
4925 repaintEverything();
4926 return NO_ERROR;
4927 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004928 // Deprecate, use 1030 to check whether the device is color managed.
4929 case 1024: {
4930 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004931 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004932 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004933 n = data.readInt32();
4934 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004935 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004936 mTracing.enable();
4937 doTracing("tracing.enable");
4938 reply->writeInt32(NO_ERROR);
4939 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004940 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004941 status_t err = mTracing.disable();
4942 reply->writeInt32(err);
4943 }
4944 return NO_ERROR;
4945 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004946 case 1026: { // Get layer tracing status
4947 reply->writeBool(mTracing.isEnabled());
4948 return NO_ERROR;
4949 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004950 // Is a DisplayColorSetting supported?
4951 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004952 const auto display = getDefaultDisplayDevice();
4953 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004954 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004955 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004956
4957 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4958 switch (setting) {
4959 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004960 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004961 break;
4962 case DisplayColorSetting::UNMANAGED:
4963 reply->writeBool(true);
4964 break;
4965 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004966 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004967 break;
4968 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004969 reply->writeBool(
4970 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004971 break;
4972 }
4973 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004974 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004975 // Is VrFlinger active?
4976 case 1028: {
4977 Mutex::Autolock _l(mStateLock);
4978 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4979 return NO_ERROR;
4980 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004981 // Is device color managed?
4982 case 1030: {
4983 reply->writeBool(useColorManagement);
4984 return NO_ERROR;
4985 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004986 // Override default composition data space
4987 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4988 // && adb shell stop zygote && adb shell start zygote
4989 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4990 // adb shell stop zygote && adb shell start zygote
4991 case 1031: {
4992 Mutex::Autolock _l(mStateLock);
4993 n = data.readInt32();
4994 if (n) {
4995 n = data.readInt32();
4996 if (n) {
4997 Dataspace dataspace = static_cast<Dataspace>(n);
4998 if (!validateCompositionDataspace(dataspace)) {
4999 return BAD_VALUE;
5000 }
5001 mDefaultCompositionDataspace = dataspace;
5002 }
5003 n = data.readInt32();
5004 if (n) {
5005 Dataspace dataspace = static_cast<Dataspace>(n);
5006 if (!validateCompositionDataspace(dataspace)) {
5007 return BAD_VALUE;
5008 }
5009 mWideColorGamutCompositionDataspace = dataspace;
5010 }
5011 } else {
5012 // restore composition data space.
5013 mDefaultCompositionDataspace = defaultCompositionDataspace;
5014 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5015 }
5016 return NO_ERROR;
5017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 }
5019 }
5020 return err;
5021}
5022
Steven Thomas6d8110b2017-08-31 18:24:21 -07005023void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005024 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005025 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005026}
5027
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005028// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5029class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005030public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005031 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5032 ~WindowDisconnector() {
5033 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005034 }
5035
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036private:
5037 ANativeWindow* mWindow;
5038 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005039};
5040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005041status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005042 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5043 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005044 uint32_t reqWidth, uint32_t reqHeight,
5045 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005046 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005047 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005049 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005050
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005051 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5052
Chia-I Wu20261cb2018-08-23 12:55:44 -07005053 sp<DisplayDevice> display;
5054 {
5055 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005056
Chia-I Wu20261cb2018-08-23 12:55:44 -07005057 display = getDisplayDeviceLocked(displayToken);
5058 if (!display) return BAD_VALUE;
5059
Chia-I Wucb023152018-08-28 12:57:23 -07005060 // set the requested width/height to the logical display viewport size
5061 // by default
5062 if (reqWidth == 0 || reqHeight == 0) {
5063 reqWidth = uint32_t(display->getViewport().width());
5064 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005065 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005066 }
5067
Peiyong Lin0e003c92018-09-17 11:09:51 -07005068 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5069 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005070
5071 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005072 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005073 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5074 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005075}
5076
5077status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005078 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5079 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005080 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005081 ATRACE_CALL();
5082
5083 class LayerRenderArea : public RenderArea {
5084 public:
Robert Carr578038f2018-03-09 12:25:24 -08005085 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005086 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5087 bool childrenOnly)
5088 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005089 mLayer(layer),
5090 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005091 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005092 mFlinger(flinger),
5093 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005094 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005095 Rect getBounds() const override {
5096 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005097 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005098 }
Marissa Wall61c58622018-07-18 10:12:20 -07005099 int getHeight() const override {
5100 return mLayer->getActiveHeight(mLayer->getDrawingState());
5101 }
5102 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005103 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005104 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005105 Rect getSourceCrop() const override {
5106 if (mCrop.isEmpty()) {
5107 return getBounds();
5108 } else {
5109 return mCrop;
5110 }
5111 }
Robert Carr578038f2018-03-09 12:25:24 -08005112 class ReparentForDrawing {
5113 public:
5114 const sp<Layer>& oldParent;
5115 const sp<Layer>& newParent;
5116
5117 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5118 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005119 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005120 }
Robert Carr15eae092018-03-23 13:43:53 -07005121 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005122 };
5123
5124 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005125 const Rect sourceCrop = getSourceCrop();
5126 // no need to check rotation because there is none
5127 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5128 sourceCrop.height() != getReqHeight();
5129
Robert Carr578038f2018-03-09 12:25:24 -08005130 if (!mChildrenOnly) {
5131 mTransform = mLayer->getTransform().inverse();
5132 drawLayers();
5133 } else {
5134 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005135 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005136 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5137 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005138
5139 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5140 drawLayers();
5141 }
5142 }
chaviwa76b2712017-09-20 12:02:26 -07005143
chaviwa76b2712017-09-20 12:02:26 -07005144 private:
chaviw7206d492017-11-10 16:16:12 -08005145 const sp<Layer> mLayer;
5146 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005147
5148 // In the "childrenOnly" case we reparent the children to a screenshot
5149 // layer which has no properties set and which does not draw.
5150 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005151 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005152 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005153
5154 SurfaceFlinger* mFlinger;
5155 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005156 };
5157
5158 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5159 auto parent = layerHandle->owner.promote();
5160
Robert Carr2e102c92018-10-23 12:11:15 -07005161 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005162 ALOGE("captureLayers called with a removed parent");
5163 return NAME_NOT_FOUND;
5164 }
5165
Robert Carr578038f2018-03-09 12:25:24 -08005166 const int uid = IPCThreadState::self()->getCallingUid();
5167 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5168 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5169 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5170 return PERMISSION_DENIED;
5171 }
5172
chaviw7206d492017-11-10 16:16:12 -08005173 Rect crop(sourceCrop);
5174 if (sourceCrop.width() <= 0) {
5175 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005176 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005177 }
5178
5179 if (sourceCrop.height() <= 0) {
5180 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005181 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005182 }
5183
5184 int32_t reqWidth = crop.width() * frameScale;
5185 int32_t reqHeight = crop.height() * frameScale;
5186
Chia-I Wu20261cb2018-08-23 12:55:44 -07005187 // really small crop or frameScale
5188 if (reqWidth <= 0) {
5189 reqWidth = 1;
5190 }
5191 if (reqHeight <= 0) {
5192 reqHeight = 1;
5193 }
5194
Peiyong Lin0e003c92018-09-17 11:09:51 -07005195 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005196
Robert Carr578038f2018-03-09 12:25:24 -08005197 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005198 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5199 if (!layer->isVisible()) {
5200 return;
Robert Carr578038f2018-03-09 12:25:24 -08005201 } else if (childrenOnly && layer == parent.get()) {
5202 return;
chaviwa76b2712017-09-20 12:02:26 -07005203 }
5204 visitor(layer);
5205 });
5206 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005207 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005208}
5209
5210status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5211 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005212 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005213 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005214 bool useIdentityTransform) {
5215 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005216
Peiyong Lin0e003c92018-09-17 11:09:51 -07005217 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005218 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5219 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005220 *outBuffer =
5221 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5222 static_cast<android_pixel_format>(reqPixelFormat), 1,
5223 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005224
5225 // This mutex protects syncFd and captureResult for communication of the return values from the
5226 // main thread back to this Binder thread
5227 std::mutex captureMutex;
5228 std::condition_variable captureCondition;
5229 std::unique_lock<std::mutex> captureLock(captureMutex);
5230 int syncFd = -1;
5231 std::optional<status_t> captureResult;
5232
Robert Carr03480e22018-01-04 16:02:06 -08005233 const int uid = IPCThreadState::self()->getCallingUid();
5234 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5235
Dominik Laskowski8c001672018-05-30 16:52:06 -07005236 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005237 // If there is a refresh pending, bug out early and tell the binder thread to try again
5238 // after the refresh.
5239 if (mRefreshPending) {
5240 ATRACE_NAME("Skipping screenshot for now");
5241 std::unique_lock<std::mutex> captureLock(captureMutex);
5242 captureResult = std::make_optional<status_t>(EAGAIN);
5243 captureCondition.notify_one();
5244 return;
5245 }
5246
5247 status_t result = NO_ERROR;
5248 int fd = -1;
5249 {
5250 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005251 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005252 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5253 useIdentityTransform, forSystem, &fd);
5254 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005255 }
5256
5257 {
5258 std::unique_lock<std::mutex> captureLock(captureMutex);
5259 syncFd = fd;
5260 captureResult = std::make_optional<status_t>(result);
5261 captureCondition.notify_one();
5262 }
5263 });
5264
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005265 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005266 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005267 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005268 while (*captureResult == EAGAIN) {
5269 captureResult.reset();
5270 result = postMessageAsync(message);
5271 if (result != NO_ERROR) {
5272 return result;
5273 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005274 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005275 }
5276 result = *captureResult;
5277 }
5278
5279 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005280 sync_wait(syncFd, -1);
5281 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005282 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005283
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005284 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005285}
5286
chaviwa76b2712017-09-20 12:02:26 -07005287void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005288 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005289 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005290 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005291
Lloyd Pique144e1162017-12-20 16:44:52 -08005292 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005293
chaviwa76b2712017-09-20 12:02:26 -07005294 const auto reqWidth = renderArea.getReqWidth();
5295 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005296 const auto sourceCrop = renderArea.getSourceCrop();
5297 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005298
Peiyong Lin0e003c92018-09-17 11:09:51 -07005299 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005300 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005301
Mathias Agopian180f10d2013-04-10 22:55:41 -07005302 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005303 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005304
5305 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005306 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005307 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005308
chaviw50da5042018-04-09 13:49:37 -07005309 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005310 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005311 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005312
chaviwa76b2712017-09-20 12:02:26 -07005313 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005314 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005315 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005316 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005317 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005318}
5319
chaviwa76b2712017-09-20 12:02:26 -07005320status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5321 TraverseLayersFunction traverseLayers,
5322 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005323 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005324 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005325 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005326 ATRACE_CALL();
5327
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005328 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005329
5330 traverseLayers([&](Layer* layer) {
5331 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5332 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005333
Robert Carr03480e22018-01-04 16:02:06 -08005334 // We allow the system server to take screenshots of secure layers for
5335 // use in situations like the Screen-rotation animation and place
5336 // the impetus on WindowManager to not persist them.
5337 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005338 ALOGW("FB is protected: PERMISSION_DENIED");
5339 return PERMISSION_DENIED;
5340 }
5341
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005342 // this binds the given EGLImage as a framebuffer for the
5343 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005344 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005345 if (bufferBond.getStatus() != NO_ERROR) {
5346 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005347 return INVALID_OPERATION;
5348 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005349
Dan Stozaabcda352017-06-01 14:37:39 -07005350 // this will in fact render into our dequeued buffer
5351 // via an FBO, which means we didn't have to create
5352 // an EGLSurface and therefore we're not
5353 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005354 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005355
Alec Mouri492bc572018-09-11 21:40:04 +00005356 base::unique_fd syncFd = getRenderEngine().flush();
5357 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005358 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005359 }
Alec Mouri492bc572018-09-11 21:40:04 +00005360 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005361
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005362 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005363}
5364
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005365// ---------------------------------------------------------------------------
5366
Dan Stoza412903f2017-04-27 13:42:17 -07005367void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5368 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005369}
5370
Dan Stoza412903f2017-04-27 13:42:17 -07005371void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5372 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005373}
5374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005375void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005376 const LayerVector::Visitor& visitor) {
5377 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005378 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005379 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005380 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005381 continue;
5382 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005383 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005384 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005385 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005386 return;
5387 }
chaviwa76b2712017-09-20 12:02:26 -07005388 if (!layer->isVisible()) {
5389 return;
5390 }
5391 visitor(layer);
5392 });
5393 }
5394}
5395
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005396}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005397
Lloyd Pique074e8122018-07-26 12:57:23 -07005398
Mathias Agopian3f844832013-08-07 21:24:32 -07005399#if defined(__gl_h_)
5400#error "don't include gl/gl.h in this file"
5401#endif
5402
5403#if defined(__gl2_h_)
5404#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005405#endif