blob: 7696758e99b859bac3704664b026ad749a12f832 [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
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333 // Make sure that composition can never be stalled by a virtual display
2334 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri8147b0e2018-10-09 20:57:19 -07002335 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002336 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2338 }
2339
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 creationArgs.displayInstallOrientation =
2341 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002342
Lloyd Pique99d3da52018-01-22 17:48:03 -08002343 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002344 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345
Lloyd Pique90c115d2018-09-18 21:39:42 -07002346 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347
2348 if (maxFrameBufferAcquiredBuffers >= 3) {
2349 nativeWindowSurface->preallocateBuffers();
2350 }
2351
2352 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002353 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002354 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002356 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002359 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002360 if (!state.isVirtual()) {
2361 LOG_ALWAYS_FATAL_IF(!displayId);
2362 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002363 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365 display->setLayerStack(state.layerStack);
2366 display->setProjection(state.orientation, state.viewport, state.frame);
2367 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002369 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370}
2371
Lloyd Pique347200f2017-12-14 17:00:15 -08002372void SurfaceFlinger::processDisplayChangesLocked() {
2373 // here we take advantage of Vector's copy-on-write semantics to
2374 // improve performance by skipping the transaction entirely when
2375 // know that the lists are identical
2376 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2377 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2378 if (!curr.isIdenticalTo(draw)) {
2379 mVisibleRegionsDirty = true;
2380 const size_t cc = curr.size();
2381 size_t dc = draw.size();
2382
2383 // find the displays that were removed
2384 // (ie: in drawing state but not in current state)
2385 // also handle displays that changed
2386 // (ie: displays that are in both lists)
2387 for (size_t i = 0; i < dc;) {
2388 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2389 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 // Save display IDs before disconnecting.
2391 const auto internalDisplayId = getInternalDisplayId();
2392 const auto externalDisplayId = getExternalDisplayId();
2393
Lloyd Pique347200f2017-12-14 17:00:15 -08002394 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002395 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2396 display->disconnect(getHwComposer());
2397 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002399 if (mUseScheduler) {
2400 mScheduler->hotplugReceived(mAppConnectionHandle,
2401 EventThread::DisplayType::Primary, false);
2402 } else {
2403 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2404 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002406 if (mUseScheduler) {
2407 mScheduler->hotplugReceived(mAppConnectionHandle,
2408 EventThread::DisplayType::External, false);
2409 } else {
2410 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2411 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002412 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002413 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002414 } else {
2415 // this display is in both lists. see if something changed.
2416 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002417 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002418 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2419 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2420 if (state_binder != draw_binder) {
2421 // changing the surface is like destroying and
2422 // recreating the DisplayDevice, so we just remove it
2423 // from the drawing state, so that it get re-added
2424 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2426 display->disconnect(getHwComposer());
2427 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002428 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002429 mDrawingState.displays.removeItemsAt(i);
2430 dc--;
2431 // at this point we must loop to the next item
2432 continue;
2433 }
2434
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002435 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002436 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 }
2439 if ((state.orientation != draw[i].orientation) ||
2440 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 }
2443 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 }
2446 }
2447 }
2448 ++i;
2449 }
2450
2451 // find displays that were added
2452 // (ie: in current state but not in drawing state)
2453 for (size_t i = 0; i < cc; i++) {
2454 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2455 const DisplayDeviceState& state(curr[i]);
2456
2457 sp<DisplaySurface> dispSurface;
2458 sp<IGraphicBufferProducer> producer;
2459 sp<IGraphicBufferProducer> bqProducer;
2460 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002461 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002462
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002464 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 // Virtual displays without a surface are dormant:
2466 // they have external state (layer stack, projection,
2467 // etc.) but no internal state (i.e. a DisplayDevice).
2468 if (state.surface != nullptr) {
2469 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002470 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002471 int width = 0;
2472 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2473 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2474 int height = 0;
2475 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2476 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2477 int intFormat = 0;
2478 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2479 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002480 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002481
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 displayId =
2483 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002484 }
2485
2486 // TODO: Plumb requested format back up to consumer
2487
2488 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002490 bqProducer, bqConsumer,
2491 state.displayName);
2492
2493 dispSurface = vds;
2494 producer = vds;
2495 }
2496 } else {
2497 ALOGE_IF(state.surface != nullptr,
2498 "adding a supported display, but rendering "
2499 "surface is provided (%p), ignoring it",
2500 state.surface.get());
2501
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 displayId = state.displayId;
2503 LOG_ALWAYS_FATAL_IF(!displayId);
2504 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002505 producer = bqProducer;
2506 }
2507
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002510 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002511 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002512 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002513 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002514 LOG_ALWAYS_FATAL_IF(!displayId);
2515
2516 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002517 if (mUseScheduler) {
2518 mScheduler->hotplugReceived(mAppConnectionHandle,
2519 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002520 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002521 } else {
2522 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2523 true);
2524 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002526 if (mUseScheduler) {
2527 mScheduler->hotplugReceived(mAppConnectionHandle,
2528 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002529 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002530 } else {
2531 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2532 true);
2533 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002534 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002535 }
2536 }
2537 }
2538 }
2539 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002540
2541 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002542}
2543
Mathias Agopian87baae12012-07-31 12:38:26 -07002544void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002545{
Dan Stoza7dde5992015-05-22 09:51:44 -07002546 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002547 mCurrentState.traverseInZOrder([](Layer* layer) {
2548 layer->notifyAvailableFrames();
2549 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 /*
2552 * Traversal of the children
2553 * (perform the transaction for each of them if needed)
2554 */
2555
Mathias Agopian3559b072012-08-15 13:46:03 -07002556 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002557 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002559 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560
2561 const uint32_t flags = layer->doTransaction(0);
2562 if (flags & Layer::eVisibleRegion)
2563 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002564 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 }
2566
2567 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002568 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 */
2570
Mathias Agopiane57f2922012-08-09 16:29:12 -07002571 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002572 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002573 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002574 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002576 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002577 // The transform hint might have changed for some layers
2578 // (either because a display has changed, or because a layer
2579 // as changed).
2580 //
2581 // Walk through all the layers in currentLayers,
2582 // and update their transform hint.
2583 //
2584 // If a layer is visible only on a single display, then that
2585 // display is used to calculate the hint, otherwise we use the
2586 // default display.
2587 //
2588 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2589 // the hint is set before we acquire a buffer from the surface texture.
2590 //
2591 // NOTE: layer transactions have taken place already, so we use their
2592 // drawing state. However, SurfaceFlinger's own transaction has not
2593 // happened yet, so we must use the current state layer list
2594 // (soon to become the drawing state list).
2595 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002596 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002597 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002598 bool first = true;
2599 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002600 // NOTE: we rely on the fact that layers are sorted by
2601 // layerStack first (so we don't have to traverse the list
2602 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002604 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002605 currentlayerStack = layerStack;
2606 // figure out if this layerstack is mirrored
2607 // (more than one display) if so, pick the default display,
2608 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002609 hintDisplay = nullptr;
2610 for (const auto& [token, display] : mDisplays) {
2611 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2612 if (hintDisplay) {
2613 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002614 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002616 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002617 }
2618 }
2619 }
2620 }
Chet Haase91d25932013-04-11 15:24:55 -07002621
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002622 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002623 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2624 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002625
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002626 // could be null when this layer is using a layerStack
2627 // that is not visible on any display. Also can occur at
2628 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002630 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002631
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002632 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002633 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002634 if (hintDisplay) {
2635 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002636 }
Robert Carr2047fae2016-11-28 14:09:09 -08002637
2638 first = false;
2639 });
Mathias Agopian84300952012-11-21 16:02:13 -08002640 }
2641
2642
Mathias Agopian3559b072012-08-15 13:46:03 -07002643 /*
2644 * Perform our own transaction if needed
2645 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646
2647 if (mLayersAdded) {
2648 mLayersAdded = false;
2649 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002650 mVisibleRegionsDirty = true;
2651 }
2652
2653 // some layers might have been removed, so
2654 // we need to update the regions they're exposing.
2655 if (mLayersRemoved) {
2656 mLayersRemoved = false;
2657 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002658 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002660 // this layer is not visible anymore
2661 // TODO: we could traverse the tree from front to back and
2662 // compute the actual visible region
2663 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 Region visibleReg;
2665 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002666 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002667 }
Robert Carr2047fae2016-11-28 14:09:09 -08002668 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 }
2670
2671 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002672
2673 updateCursorAsync();
2674}
2675
2676void SurfaceFlinger::updateCursorAsync()
2677{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002679 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002680 continue;
2681 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2684 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002685 }
2686 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002687}
2688
2689void SurfaceFlinger::commitTransaction()
2690{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002691 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002692 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 for (const auto& l : mLayersPendingRemoval) {
2694 recordBufferingStats(l->getName().string(),
2695 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002696
2697 // We need to release the HWC layers when the Layer is removed
2698 // from the current state otherwise the HWC layer just continues
2699 // showing at its last configured state until we eventually
2700 // abandon the buffer queue.
2701 if (l->isRemovedFromCurrentState()) {
2702 l->destroyAllHwcLayers();
2703 l->releasePendingBuffer(systemTime());
2704 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 }
2706 mLayersPendingRemoval.clear();
2707 }
2708
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002709 // If this transaction is part of a window animation then the next frame
2710 // we composite should be considered an animation as well.
2711 mAnimCompositionPending = mAnimTransactionPending;
2712
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002714 // clear the "changed" flags in current state
2715 mCurrentState.colorMatrixChanged = false;
2716
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 mDrawingState.traverseInZOrder([](Layer* layer) {
2718 layer->commitChildList();
2719 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002720 mTransactionPending = false;
2721 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002722 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723}
2724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2726 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002727 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002728 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 Region aboveOpaqueLayers;
2731 Region aboveCoveredLayers;
2732 Region dirty;
2733
Mathias Agopian87baae12012-07-31 12:38:26 -07002734 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735
Robert Carr2047fae2016-11-28 14:09:09 -08002736 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002738 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739
Jesse Hall01e29052013-02-19 16:13:35 -08002740 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002741 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002742 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002743 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002744
Mathias Agopianab028732010-03-16 16:41:46 -07002745 /*
2746 * opaqueRegion: area of a surface that is fully opaque.
2747 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002749
2750 /*
2751 * visibleRegion: area of a surface that is visible on screen
2752 * and not fully transparent. This is essentially the layer's
2753 * footprint minus the opaque regions above it.
2754 * Areas covered by a translucent surface are considered visible.
2755 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002757
2758 /*
2759 * coveredRegion: area of a surface that is covered by all
2760 * visible regions above it (which includes the translucent areas).
2761 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002763
Jesse Halla8026d22012-09-25 13:25:04 -07002764 /*
2765 * transparentRegion: area of a surface that is hinted to be completely
2766 * transparent. This is only used to tell when the layer has no visible
2767 * non-transparent regions and can be removed from the layer list. It
2768 * does not affect the visibleRegion of this layer or any layers
2769 * beneath it. The hint may not be correct if apps don't respect the
2770 * SurfaceView restrictions (which, sadly, some don't).
2771 */
2772 Region transparentRegion;
2773
Mathias Agopianab028732010-03-16 16:41:46 -07002774
2775 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002776 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002777 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002778 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002780 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002781 if (!visibleRegion.isEmpty()) {
2782 // Remove the transparent area from the visible region
2783 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002784 if (tr.preserveRects()) {
2785 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002786 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002787 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002788 // transformation too complex, can't do the
2789 // transparent region optimization.
2790 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002791 }
Mathias Agopianab028732010-03-16 16:41:46 -07002792 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793
Mathias Agopianab028732010-03-16 16:41:46 -07002794 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002796 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002797 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002798 // the opaque region is the layer's footprint
2799 opaqueRegion = visibleRegion;
2800 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 }
2802 }
2803
Robert Carre5f4f692018-01-12 13:12:28 -08002804 if (visibleRegion.isEmpty()) {
2805 layer->clearVisibilityRegions();
2806 return;
2807 }
2808
Mathias Agopianab028732010-03-16 16:41:46 -07002809 // Clip the covered region to the visible region
2810 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2811
2812 // Update aboveCoveredLayers for next (lower) layer
2813 aboveCoveredLayers.orSelf(visibleRegion);
2814
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 // subtract the opaque region covered by the layers above us
2816 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
2818 // compute this layer's dirty region
2819 if (layer->contentDirty) {
2820 // we need to invalidate the whole region
2821 dirty = visibleRegion;
2822 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002823 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 layer->contentDirty = false;
2825 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002826 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002827 * the exposed region consists of two components:
2828 * 1) what's VISIBLE now and was COVERED before
2829 * 2) what's EXPOSED now less what was EXPOSED before
2830 *
2831 * note that (1) is conservative, we start with the whole
2832 * visible region but only keep what used to be covered by
2833 * something -- which mean it may have been exposed.
2834 *
2835 * (2) handles areas that were not covered by anything but got
2836 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002837 */
Mathias Agopianab028732010-03-16 16:41:46 -07002838 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002839 const Region oldVisibleRegion = layer->visibleRegion;
2840 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002841 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2842 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 }
2844 dirty.subtractSelf(aboveOpaqueLayers);
2845
2846 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002847 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848
Mathias Agopianab028732010-03-16 16:41:46 -07002849 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002851
Jesse Halla8026d22012-09-25 13:25:04 -07002852 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 layer->setVisibleRegion(visibleRegion);
2854 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002855 layer->setVisibleNonTransparentRegion(
2856 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002857 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858
Mathias Agopian87baae12012-07-31 12:38:26 -07002859 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860}
2861
Chia-I Wuab0c3192017-08-01 11:29:00 -07002862void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002864 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2865 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002866 }
2867 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002868}
2869
Dan Stoza6b9454d2014-11-07 16:00:59 -08002870bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002872 ALOGV("handlePageFlip");
2873
Brian Andersond6927fb2016-07-23 23:37:30 -07002874 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875
Mathias Agopian4fec8732012-06-29 14:12:52 -07002876 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002877 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002878 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002879
2880 // Store the set of layers that need updates. This set must not change as
2881 // buffers are being latched, as this could result in a deadlock.
2882 // Example: Two producers share the same command stream and:
2883 // 1.) Layer 0 is latched
2884 // 2.) Layer 0 gets a new frame
2885 // 2.) Layer 1 gets a new frame
2886 // 3.) Layer 1 is latched.
2887 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2888 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002889 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002890 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002891 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002892 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2893 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002894 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002895 } else {
2896 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002897 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002898 } else {
2899 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002900 }
Robert Carr2047fae2016-11-28 14:09:09 -08002901 });
2902
Dan Stoza9e56aa02015-11-02 13:00:03 -08002903 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002904 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002905 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002906 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002907 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002908 newDataLatched = true;
2909 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002911
Alec Mouri86770e52018-09-24 22:40:58 +00002912 // Clear the renderengine fence here...
2913 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2914 // clear instead of sp::clear.
2915 getBE().flushFence = Fence::NO_FENCE;
2916
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002917 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002918
2919 // If we will need to wake up at some time in the future to deal with a
2920 // queued frame that shouldn't be displayed during this vsync period, wake
2921 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002922 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002923 signalLayerUpdate();
2924 }
2925
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002926 // enter boot animation on first buffer latch
2927 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2928 ALOGI("Enter boot animation");
2929 mBootStage = BootStage::BOOTANIMATION;
2930 }
2931
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002933 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934}
2935
Mathias Agopianad456f92011-01-13 17:53:01 -08002936void SurfaceFlinger::invalidateHwcGeometry()
2937{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002939}
2940
Alec Mouri8147b0e2018-10-09 20:57:19 -07002941void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002942 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002943 // We only need to actually compose the display if:
2944 // 1) It is being handled by hardware composer, which may need this to
2945 // keep its virtual display state machine in sync, or
2946 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002947 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002948 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002950 return;
2951 }
2952
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002954 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002955
2956 // swap buffers (presentation)
Alec Mouri8147b0e2018-10-09 20:57:19 -07002957 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958}
2959
Alec Mouri8147b0e2018-10-09 20:57:19 -07002960bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002962
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002963 const Region bounds(display->bounds());
2964 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002965 const auto displayId = display->getId();
2966 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002967 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002968
Peiyong Lind3788632018-09-18 16:01:31 -07002969 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002970 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002971 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002972
Alec Mouri8147b0e2018-10-09 20:57:19 -07002973 // Framebuffer will live in this scope for GPU composition.
2974 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
2975
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 if (hasClientComposition) {
2977 ALOGV("hasClientComposition");
2978
Alec Mouri8147b0e2018-10-09 20:57:19 -07002979 sp<GraphicBuffer> buf = display->dequeueBuffer();
2980
2981 if (buf == nullptr) {
2982 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
2983 "client composition for this frame",
2984 display->getDisplayName().c_str());
2985 return false;
2986 }
2987
2988 // Bind the framebuffer in this scope.
2989 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
2990 buf->getNativeBuffer());
2991
2992 if (fbo->getStatus() != NO_ERROR) {
2993 ALOGW("Binding buffer for display [%s] failed with status: %d",
2994 display->getDisplayName().c_str(), fbo->getStatus());
2995 return false;
2996 }
2997
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002998 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999 if (display->hasWideColorGamut()) {
3000 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003001 }
3002 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003003 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003004 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003005
Dominik Laskowski7e045462018-05-30 13:02:02 -07003006 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003007 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3008 HWC2::Capability::SkipClientColorTransform);
3009
Peiyong Lind3788632018-09-18 16:01:31 -07003010 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003011 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3012 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003013 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003014 }
3015
Chia-I Wud49d6692018-06-27 07:17:41 +08003016 // The current enhanced saturation matrix is designed to enhance Display P3,
3017 // thus we only apply this matrix when the render intent is not colorimetric
3018 // and the output color space is Display P3.
3019 needsEnhancedColorMatrix =
3020 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3021 outputDataspace == Dataspace::DISPLAY_P3);
3022 if (needsEnhancedColorMatrix) {
3023 colorMatrix *= mEnhancedSaturationMatrix;
3024 }
3025
Alec Mouri8147b0e2018-10-09 20:57:19 -07003026 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003027
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003028 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003029 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003030 // when using overlays, we assume a fully transparent framebuffer
3031 // NOTE: we could reduce how much we need to clear, for instance
3032 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003033 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003034 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003035 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003036 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003037 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003038 // we're left with the letterbox region
3039 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003040 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003041
3042 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003044
Mathias Agopianb9494d52012-04-18 02:28:45 -07003045 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003046 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003047 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003048 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003049 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003050 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003051
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003052 const Rect& bounds = display->getBounds();
3053 const Rect& scissor = display->getScissor();
3054 if (scissor != bounds) {
3055 // scissor doesn't match the screen's dimensions, so we
3056 // need to clear everything outside of it and enable
3057 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003058
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003059 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003060 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003061 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003062 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003063
Mathias Agopian85d751c2012-08-29 16:59:24 -07003064 /*
3065 * and then, render the layers targeted at the framebuffer
3066 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003067
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003069 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003070 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003071 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003072 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003073 displayTransform.transform(layer->visibleRegion)));
3074 ALOGV("Layer: %s", layer->getName().string());
3075 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003076 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003077 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003078 case HWC2::Composition::Cursor:
3079 case HWC2::Composition::Device:
3080 case HWC2::Composition::Sideband:
3081 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003082 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003083 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003084 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003085 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3086 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003087 // never clear the very first layer since we're
3088 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003089 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003090 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003091 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003092 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003094 if (layer->hasColorTransform()) {
3095 mat4 tmpMatrix;
3096 if (applyColorMatrix) {
3097 tmpMatrix = mDrawingState.colorMatrix;
3098 }
3099 tmpMatrix *= layer->getColorTransform();
3100 if (needsEnhancedColorMatrix) {
3101 tmpMatrix *= mEnhancedSaturationMatrix;
3102 }
3103 getRenderEngine().setColorTransform(tmpMatrix);
3104 } else {
3105 getRenderEngine().setColorTransform(colorMatrix);
3106 }
David Sodmanc1498e62018-09-12 14:36:26 -07003107 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003108 break;
3109 }
3110 default:
3111 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003112 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 } else {
3114 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003115 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003116 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003117 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003118
Alec Mouri8147b0e2018-10-09 20:57:19 -07003119 // Perform some cleanup steps if we used client composition.
3120 if (hasClientComposition) {
3121 getRenderEngine().setColorTransform(mat4());
3122 getBE().mRenderEngine->disableScissor();
3123 display->finishBuffer();
3124 // Clear out error flags here so that we don't wait until next
3125 // composition to log.
3126 getRenderEngine().checkErrors();
3127 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003128 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129}
3130
Chia-I Wu28e3a252018-09-07 12:05:02 -07003131void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003132 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003133 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Dan Stoza7d89d062015-04-30 13:29:25 -07003136status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003137 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003138 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003139 const sp<Layer>& lbc,
3140 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003141{
Dan Stoza7d89d062015-04-30 13:29:25 -07003142 // add this layer to the current state list
3143 {
3144 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003146 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3147 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003148 return NO_MEMORY;
3149 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 if (parent == nullptr) {
3151 mCurrentState.layersSortedByZ.add(lbc);
3152 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003153 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003154 ALOGE("addClientLayer called with a removed parent");
3155 return NAME_NOT_FOUND;
3156 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003157 parent->addChild(lbc);
3158 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003159
Yiwei Zhang243b3782018-05-15 17:40:04 -07003160 if (gbc != nullptr) {
3161 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3162 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3163 mMaxGraphicBufferProducerListSize,
3164 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3165 mGraphicBufferProducerList.size(),
3166 mMaxGraphicBufferProducerListSize, mNumLayers);
3167 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003169 }
3170
Mathias Agopian96f08192010-06-02 23:28:45 -07003171 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003172 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003173
Dan Stoza7d89d062015-04-30 13:29:25 -07003174 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003175}
3176
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003177status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003178 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003179 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3180}
Robert Carr7f9b8992017-03-10 11:08:39 -08003181
Robert Carr2e102c92018-10-23 12:11:15 -07003182status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003183 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003185 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003186 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003187 if (topLevelOnly) {
3188 return NO_ERROR;
3189 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003190 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003191 } else {
3192 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003193 }
3194
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003195 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003196
3197 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003198 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199}
3200
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003201uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003202 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003203}
3204
Mathias Agopian3f844832013-08-07 21:24:32 -07003205uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003206 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Mathias Agopian3f844832013-08-07 21:24:32 -07003209uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003210 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003211}
3212
3213uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003214 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003215 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003216 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003218 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 }
3220 return old;
3221}
3222
chaviwca27f252018-02-06 16:46:39 -08003223bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3224 for (const ComposerState& state : states) {
3225 // Here we need to check that the interface we're given is indeed
3226 // one of our own. A malicious client could give us a nullptr
3227 // IInterface, or one of its own or even one of our own but a
3228 // different type. All these situations would cause us to crash.
3229 if (state.client == nullptr) {
3230 return true;
3231 }
3232
3233 sp<IBinder> binder = IInterface::asBinder(state.client);
3234 if (binder == nullptr) {
3235 return true;
3236 }
3237
3238 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3239 return true;
3240 }
3241 }
3242 return false;
3243}
3244
Mathias Agopian8b33f032012-07-24 20:43:54 -07003245void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003246 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003247 const Vector<DisplayState>& displays,
3248 uint32_t flags)
3249{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003250 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003251 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003252 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003253
chaviwca27f252018-02-06 16:46:39 -08003254 if (containsAnyInvalidClientState(states)) {
3255 return;
3256 }
3257
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003258 if (flags & eAnimation) {
3259 // For window updates that are part of an animation we must wait for
3260 // previous animation "frames" to be handled.
3261 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003262 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 if (CC_UNLIKELY(err != NO_ERROR)) {
3264 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003265 // caller after a few seconds.
3266 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3267 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003268 mAnimTransactionPending = false;
3269 break;
3270 }
3271 }
3272 }
3273
chaviwca27f252018-02-06 16:46:39 -08003274 for (const DisplayState& display : displays) {
3275 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003276 }
3277
chaviwca27f252018-02-06 16:46:39 -08003278 for (const ComposerState& state : states) {
3279 transactionFlags |= setClientStateLocked(state);
3280 }
3281
3282 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3283 // as destroyed should only occur after setting all other states. This is to allow for a
3284 // child re-parent to happen before marking its original parent as destroyed (which would
3285 // then mark the child as destroyed).
3286 for (const ComposerState& state : states) {
3287 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003288 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003289
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003290 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3291 // anyway. This can be used as a flush mechanism for previous async transactions.
3292 // Empty animation transaction can be used to simulate back-pressure, so also force a
3293 // transaction for empty animation transactions.
3294 if (transactionFlags == 0 &&
3295 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003296 transactionFlags = eTransactionNeeded;
3297 }
3298
Mathias Agopian386aa982011-11-07 21:58:03 -08003299 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003300 if (mInterceptor->isEnabled()) {
3301 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003302 }
Irvel468051e2016-06-13 16:44:44 -07003303
Mathias Agopian386aa982011-11-07 21:58:03 -08003304 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003305 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3306 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003307 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003308
3309 // if this is a synchronous transaction, wait for it to take effect
3310 // before returning.
3311 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003312 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003313 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003314 if (flags & eAnimation) {
3315 mAnimTransactionPending = true;
3316 }
3317 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003318 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3319 if (CC_UNLIKELY(err != NO_ERROR)) {
3320 // just in case something goes wrong in SF, return to the
3321 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003322 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3323 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003324 break;
3325 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003326 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003327 }
3328}
3329
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003330uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3331 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3332 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003333
Mathias Agopiane57f2922012-08-09 16:29:12 -07003334 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003335 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3336
3337 const uint32_t what = s.what;
3338 if (what & DisplayState::eSurfaceChanged) {
3339 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3340 state.surface = s.surface;
3341 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003342 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003343 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003344 if (what & DisplayState::eLayerStackChanged) {
3345 if (state.layerStack != s.layerStack) {
3346 state.layerStack = s.layerStack;
3347 flags |= eDisplayTransactionNeeded;
3348 }
3349 }
3350 if (what & DisplayState::eDisplayProjectionChanged) {
3351 if (state.orientation != s.orientation) {
3352 state.orientation = s.orientation;
3353 flags |= eDisplayTransactionNeeded;
3354 }
3355 if (state.frame != s.frame) {
3356 state.frame = s.frame;
3357 flags |= eDisplayTransactionNeeded;
3358 }
3359 if (state.viewport != s.viewport) {
3360 state.viewport = s.viewport;
3361 flags |= eDisplayTransactionNeeded;
3362 }
3363 }
3364 if (what & DisplayState::eDisplaySizeChanged) {
3365 if (state.width != s.width) {
3366 state.width = s.width;
3367 flags |= eDisplayTransactionNeeded;
3368 }
3369 if (state.height != s.height) {
3370 state.height = s.height;
3371 flags |= eDisplayTransactionNeeded;
3372 }
3373 }
3374
Mathias Agopiane57f2922012-08-09 16:29:12 -07003375 return flags;
3376}
3377
Robert Carrd4ae7f32018-06-07 16:10:57 -07003378bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3379 IPCThreadState* ipc = IPCThreadState::self();
3380 const int pid = ipc->getCallingPid();
3381 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003382 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003383 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003384 return false;
3385 }
3386 return true;
3387}
3388
chaviwca27f252018-02-06 16:46:39 -08003389uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3390 const layer_state_t& s = composerState.state;
3391 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3392
Mathias Agopian13127d82013-03-05 17:47:11 -08003393 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003394 if (layer == nullptr) {
3395 return 0;
3396 }
3397
chaviw8b3871a2017-11-01 17:41:01 -07003398 uint32_t flags = 0;
3399
3400 const uint32_t what = s.what;
3401 bool geometryAppliesWithResize =
3402 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003403
3404 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3405 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003406 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003407 layer->pushPendingState();
3408 }
3409
chaviw8b3871a2017-11-01 17:41:01 -07003410 if (what & layer_state_t::ePositionChanged) {
3411 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3412 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003413 }
chaviw8b3871a2017-11-01 17:41:01 -07003414 }
3415 if (what & layer_state_t::eLayerChanged) {
3416 // NOTE: index needs to be calculated before we update the state
3417 const auto& p = layer->getParent();
3418 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003419 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003421 mCurrentState.layersSortedByZ.removeAt(idx);
3422 mCurrentState.layersSortedByZ.add(layer);
3423 // we need traversal (state changed)
3424 // AND transaction (list changed)
3425 flags |= eTransactionNeeded|eTraversalNeeded;
3426 }
chaviw8b3871a2017-11-01 17:41:01 -07003427 } else {
3428 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003429 flags |= eTransactionNeeded|eTraversalNeeded;
3430 }
3431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 }
3433 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003434 // NOTE: index needs to be calculated before we update the state
3435 const auto& p = layer->getParent();
3436 if (p == nullptr) {
3437 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3438 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3439 mCurrentState.layersSortedByZ.removeAt(idx);
3440 mCurrentState.layersSortedByZ.add(layer);
3441 // we need traversal (state changed)
3442 // AND transaction (list changed)
3443 flags |= eTransactionNeeded|eTraversalNeeded;
3444 }
3445 } else {
3446 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3447 flags |= eTransactionNeeded|eTraversalNeeded;
3448 }
chaviw8b3871a2017-11-01 17:41:01 -07003449 }
3450 }
3451 if (what & layer_state_t::eSizeChanged) {
3452 if (layer->setSize(s.w, s.h)) {
3453 flags |= eTraversalNeeded;
3454 }
3455 }
3456 if (what & layer_state_t::eAlphaChanged) {
3457 if (layer->setAlpha(s.alpha))
3458 flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eColorChanged) {
3461 if (layer->setColor(s.color))
3462 flags |= eTraversalNeeded;
3463 }
Peiyong Lind3788632018-09-18 16:01:31 -07003464 if (what & layer_state_t::eColorTransformChanged) {
3465 if (layer->setColorTransform(s.colorTransform)) {
3466 flags |= eTraversalNeeded;
3467 }
3468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003470 // TODO: b/109894387
3471 //
3472 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3473 // rotation. To see the problem observe that if we have a square parent, and a child
3474 // of the same size, then we rotate the child 45 degrees around it's center, the child
3475 // must now be cropped to a non rectangular 8 sided region.
3476 //
3477 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3478 // private API, and the WindowManager only uses rotation in one case, which is on a top
3479 // level layer in which cropping is not an issue.
3480 //
3481 // However given that abuse of rotation matrices could lead to surfaces extending outside
3482 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3483 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3484 // transformations.
3485 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eTransparentRegionChanged) {
3489 if (layer->setTransparentRegionHint(s.transparentRegion))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eFlagsChanged) {
3493 if (layer->setFlags(s.flags, s.mask))
3494 flags |= eTraversalNeeded;
3495 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003496 if (what & layer_state_t::eCropChanged_legacy) {
3497 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003498 flags |= eTraversalNeeded;
3499 }
chaviw8b3871a2017-11-01 17:41:01 -07003500 if (what & layer_state_t::eLayerStackChanged) {
3501 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3502 // We only allow setting layer stacks for top level layers,
3503 // everything else inherits layer stack from its parent.
3504 if (layer->hasParent()) {
3505 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3506 layer->getName().string());
3507 } else if (idx < 0) {
3508 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3509 "that also does not appear in the top level layer list. Something"
3510 " has gone wrong.", layer->getName().string());
3511 } else if (layer->setLayerStack(s.layerStack)) {
3512 mCurrentState.layersSortedByZ.removeAt(idx);
3513 mCurrentState.layersSortedByZ.add(layer);
3514 // we need traversal (state changed)
3515 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003516 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003517 }
3518 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003519 if (what & layer_state_t::eDeferTransaction_legacy) {
3520 if (s.barrierHandle_legacy != nullptr) {
3521 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3522 } else if (s.barrierGbp_legacy != nullptr) {
3523 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003524 if (authenticateSurfaceTextureLocked(gbp)) {
3525 const auto& otherLayer =
3526 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003527 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003528 } else {
3529 ALOGE("Attempt to defer transaction to to an"
3530 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003531 }
3532 }
chaviw8b3871a2017-11-01 17:41:01 -07003533 // We don't trigger a traversal here because if no other state is
3534 // changed, we don't want this to cause any more work
3535 }
3536 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003537 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003538 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003539 if (!hadParent) {
3540 mCurrentState.layersSortedByZ.remove(layer);
3541 }
chaviw8b3871a2017-11-01 17:41:01 -07003542 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 }
3545 if (what & layer_state_t::eReparentChildren) {
3546 if (layer->reparentChildren(s.reparentHandle)) {
3547 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003548 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003549 }
chaviw8b3871a2017-11-01 17:41:01 -07003550 if (what & layer_state_t::eDetachChildren) {
3551 layer->detachChildren();
3552 }
3553 if (what & layer_state_t::eOverrideScalingModeChanged) {
3554 layer->setOverrideScalingMode(s.overrideScalingMode);
3555 // We don't trigger a traversal here because if no other state is
3556 // changed, we don't want this to cause any more work
3557 }
Marissa Wall61c58622018-07-18 10:12:20 -07003558 if (what & layer_state_t::eTransformChanged) {
3559 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3560 }
3561 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3562 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3563 flags |= eTraversalNeeded;
3564 }
3565 if (what & layer_state_t::eCropChanged) {
3566 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eBufferChanged) {
3569 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3570 }
3571 if (what & layer_state_t::eAcquireFenceChanged) {
3572 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eDataspaceChanged) {
3575 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eHdrMetadataChanged) {
3578 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3581 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3582 }
3583 if (what & layer_state_t::eApiChanged) {
3584 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eSidebandStreamChanged) {
3587 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3588 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003589 return flags;
3590}
3591
chaviwca27f252018-02-06 16:46:39 -08003592void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3593 const layer_state_t& state = composerState.state;
3594 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3595
3596 sp<Layer> layer(client->getLayerUser(state.surface));
3597 if (layer == nullptr) {
3598 return;
3599 }
3600
chaviwca27f252018-02-06 16:46:39 -08003601 if (state.what & layer_state_t::eDestroySurface) {
3602 removeLayerLocked(mStateLock, layer);
3603 }
3604}
3605
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003607 const String8& name,
3608 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003610 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003611 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003613 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003614 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003615 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003617 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003618
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619 status_t result = NO_ERROR;
3620
3621 sp<Layer> layer;
3622
Cody Northropbc755282017-03-31 12:00:08 -06003623 String8 uniqueName = getUniqueLayerName(name);
3624
Mathias Agopian3165cc22012-08-08 19:42:09 -07003625 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003626 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003627 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3628 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003629
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003631 case ISurfaceComposerClient::eFXSurfaceBufferState:
3632 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3633 break;
chaviw13fdc492017-06-27 12:40:18 -07003634 case ISurfaceComposerClient::eFXSurfaceColor:
3635 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003636 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003637 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003639 case ISurfaceComposerClient::eFXSurfaceContainer:
3640 result = createContainerLayer(client,
3641 uniqueName, w, h, flags,
3642 handle, &layer);
3643 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 default:
3645 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 break;
3647 }
3648
Dan Stoza7d89d062015-04-30 13:29:25 -07003649 if (result != NO_ERROR) {
3650 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003652
Chia-I Wuab0c3192017-08-01 11:29:00 -07003653 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3654 // TODO b/64227542
3655 if (windowType == 441731) {
3656 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3657 layer->setPrimaryDisplayOnly();
3658 }
3659
Albert Chaulk479c60c2017-01-27 14:21:34 -05003660 layer->setInfo(windowType, ownerUid);
3661
Robert Carr1f0a16a2016-10-24 16:27:39 -07003662 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003663 if (result != NO_ERROR) {
3664 return result;
3665 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003666 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003667
3668 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003669 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003670}
3671
Cody Northropbc755282017-03-31 12:00:08 -06003672String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3673{
3674 bool matchFound = true;
3675 uint32_t dupeCounter = 0;
3676
3677 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3678 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3679
Dan Stoza436ccf32018-06-21 12:10:12 -07003680 // Grab the state lock since we're accessing mCurrentState
3681 Mutex::Autolock lock(mStateLock);
3682
Cody Northropbc755282017-03-31 12:00:08 -06003683 // Loop over layers until we're sure there is no matching name
3684 while (matchFound) {
3685 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003686 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003687 if (layer->getName() == uniqueName) {
3688 matchFound = true;
3689 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3690 }
3691 });
3692 }
3693
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003694 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3695 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003696
3697 return uniqueName;
3698}
3699
Marissa Wallfd668622018-05-10 10:21:13 -07003700status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3701 uint32_t w, uint32_t h, uint32_t flags,
3702 PixelFormat& format, sp<IBinder>* handle,
3703 sp<IGraphicBufferProducer>* gbp,
3704 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003706 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 case PIXEL_FORMAT_TRANSPARENT:
3708 case PIXEL_FORMAT_TRANSLUCENT:
3709 format = PIXEL_FORMAT_RGBA_8888;
3710 break;
3711 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003712 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713 break;
3714 }
3715
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003716 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003717 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003718 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003720 *handle = layer->getHandle();
3721 *gbp = layer->getProducer();
3722 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003724
Marissa Wallfd668622018-05-10 10:21:13 -07003725 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727}
3728
Marissa Wall61c58622018-07-18 10:12:20 -07003729status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3730 uint32_t w, uint32_t h, uint32_t flags,
3731 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003732 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003733 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003734 *handle = layer->getHandle();
3735 *outLayer = layer;
3736
3737 return NO_ERROR;
3738}
3739
chaviw13fdc492017-06-27 12:40:18 -07003740status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003742 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003744 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003747}
3748
Robert Carr6b3f6c52018-08-13 13:05:17 -07003749status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3750 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3751 sp<IBinder>* handle, sp<Layer>* outLayer)
3752{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003753 *outLayer =
3754 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003755 *handle = (*outLayer)->getHandle();
3756 return NO_ERROR;
3757}
3758
3759
Mathias Agopianac9fa422013-02-11 16:40:36 -08003760status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003761{
Robert Carr9524cb32017-02-13 11:32:32 -08003762 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003763 status_t err = NO_ERROR;
3764 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003765 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003766 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003767 err = removeLayer(l);
3768 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3769 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003770 }
3771 return err;
3772}
3773
Robert Carr2e102c92018-10-23 12:11:15 -07003774void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3775 mLayersPendingRemoval.add(layer);
3776 mLayersRemoved = true;
3777 setTransactionFlags(eTransactionNeeded);
3778}
3779
3780void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003781{
Robert Carr2e102c92018-10-23 12:11:15 -07003782 Mutex::Autolock lock(mStateLock);
3783 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003784}
3785
Mathias Agopianb60314a2012-04-10 22:09:54 -07003786// ---------------------------------------------------------------------------
3787
Andy McFadden13a082e2012-08-24 10:16:42 -07003788void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003789 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003790 if (!displayToken) return;
3791
Jesse Hall01e29052013-02-19 16:13:35 -08003792 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003793 Vector<ComposerState> state;
3794 Vector<DisplayState> displays;
3795 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003796 d.what = DisplayState::eDisplayProjectionChanged |
3797 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003798 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003799 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003800 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003801 d.frame.makeInvalid();
3802 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003803 d.width = 0;
3804 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003805 displays.add(d);
3806 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003807
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003808 const auto display = getDisplayDevice(displayToken);
3809 if (!display) return;
3810
3811 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3812
Dominik Laskowski075d3172018-05-24 15:50:06 -07003813 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003814 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003815 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003816
Brian Andersond0010582017-03-07 13:20:31 -08003817 // Use phase of 0 since phase is not known.
3818 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003819 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3820 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003821}
3822
3823void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003824 // Async since we may be called from the main thread.
3825 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003826}
3827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003828void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3829 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003830 if (display->isVirtual()) {
3831 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003832 return;
3833 }
3834
Dominik Laskowski075d3172018-05-24 15:50:06 -07003835 const auto displayId = display->getId();
3836 LOG_ALWAYS_FATAL_IF(!displayId);
3837
3838 ALOGD("Setting power mode %d on display %" PRIu64, mode, *displayId);
3839
3840 int currentMode = display->getPowerMode();
3841 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003842 return;
3843 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003844
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003845 display->setPowerMode(mode);
3846
Lloyd Pique4dccc412018-01-22 17:21:36 -08003847 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003848 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003849 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003850 if (idx < 0) {
3851 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3852 return;
3853 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003854 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003855 }
3856
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003858 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003859 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003860 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003861 if (mUseScheduler) {
3862 mScheduler->onScreenAcquired(mAppConnectionHandle);
3863 } else {
3864 mEventThread->onScreenAcquired();
3865 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003866 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003867 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003868
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003869 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003870 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003871 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003872
3873 struct sched_param param = {0};
3874 param.sched_priority = 1;
3875 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3876 ALOGW("Couldn't set SCHED_FIFO on display on");
3877 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003879 // Turn off the display
3880 struct sched_param param = {0};
3881 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3882 ALOGW("Couldn't set SCHED_OTHER on display off");
3883 }
3884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003885 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003886 if (mUseScheduler) {
3887 mScheduler->disableHardwareVsync(true);
3888 } else {
3889 disableHardwareVsync(true); // also cancels any in-progress resync
3890 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003891 if (mUseScheduler) {
3892 mScheduler->onScreenReleased(mAppConnectionHandle);
3893 } else {
3894 mEventThread->onScreenReleased();
3895 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003896 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003897
Dominik Laskowski075d3172018-05-24 15:50:06 -07003898 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003899 mVisibleRegionsDirty = true;
3900 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003901 } else if (mode == HWC_POWER_MODE_DOZE ||
3902 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003903 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003904 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003905 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003906 if (mUseScheduler) {
3907 mScheduler->onScreenAcquired(mAppConnectionHandle);
3908 } else {
3909 mEventThread->onScreenAcquired();
3910 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003911 resyncToHardwareVsync(true);
3912 }
3913 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3914 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003915 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003916 if (mUseScheduler) {
3917 mScheduler->disableHardwareVsync(true);
3918 } else {
3919 disableHardwareVsync(true); // also cancels any in-progress resync
3920 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003921 if (mUseScheduler) {
3922 mScheduler->onScreenReleased(mAppConnectionHandle);
3923 } else {
3924 mEventThread->onScreenReleased();
3925 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003926 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003927 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003928 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003929 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003930 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003931 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003932
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003933 if (display->isPrimary()) {
3934 mTimeStats.setPowerMode(mode);
3935 }
3936
Dominik Laskowski075d3172018-05-24 15:50:06 -07003937 ALOGD("Finished setting power mode %d on display %" PRIu64, mode, *displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003938}
3939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003940void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003941 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003942 const auto display = getDisplayDevice(displayToken);
3943 if (!display) {
3944 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3945 displayToken.get());
3946 } else if (display->isVirtual()) {
3947 ALOGW("Attempt to set power mode %d for virtual display", mode);
3948 } else {
3949 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003950 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003952}
3953
3954// ---------------------------------------------------------------------------
3955
Lloyd Pique755e3192018-01-31 16:46:15 -08003956status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3957 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003959
Mathias Agopianbd115332013-04-18 16:41:04 -07003960 IPCThreadState* ipc = IPCThreadState::self();
3961 const int pid = ipc->getCallingPid();
3962 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003963
Mathias Agopianbd115332013-04-18 16:41:04 -07003964 if ((uid != AID_SHELL) &&
3965 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003966 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003967 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003969 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003970 // (this would indicate SF is stuck, but we want to be able to
3971 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003972 status_t err = mStateLock.timedLock(s2ns(1));
3973 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003974 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003975 result.appendFormat(
3976 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3977 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003978 }
3979
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003980 bool dumpAll = true;
3981 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003982 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003983
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003984 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003985 if ((index < numArgs) &&
3986 (args[index] == String16("--list"))) {
3987 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003988 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003989 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003990 }
3991
3992 if ((index < numArgs) &&
3993 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003994 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003995 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003996 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003997 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003998
3999 if ((index < numArgs) &&
4000 (args[index] == String16("--latency-clear"))) {
4001 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004002 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004003 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004004 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004005
4006 if ((index < numArgs) &&
4007 (args[index] == String16("--dispsync"))) {
4008 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004009 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004010 dumpAll = false;
4011 }
Dan Stozab90cf072015-03-05 11:05:59 -08004012
4013 if ((index < numArgs) &&
4014 (args[index] == String16("--static-screen"))) {
4015 index++;
4016 dumpStaticScreenStats(result);
4017 dumpAll = false;
4018 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004019
4020 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004021 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004022 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004023 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004024 dumpAll = false;
4025 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004026
4027 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4028 index++;
4029 dumpWideColorInfo(result);
4030 dumpAll = false;
4031 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004032
4033 if ((index < numArgs) &&
4034 (args[index] == String16("--enable-layer-stats"))) {
4035 index++;
4036 mLayerStats.enable();
4037 dumpAll = false;
4038 }
4039
4040 if ((index < numArgs) &&
4041 (args[index] == String16("--disable-layer-stats"))) {
4042 index++;
4043 mLayerStats.disable();
4044 dumpAll = false;
4045 }
4046
4047 if ((index < numArgs) &&
4048 (args[index] == String16("--clear-layer-stats"))) {
4049 index++;
4050 mLayerStats.clear();
4051 dumpAll = false;
4052 }
4053
4054 if ((index < numArgs) &&
4055 (args[index] == String16("--dump-layer-stats"))) {
4056 index++;
4057 mLayerStats.dump(result);
4058 dumpAll = false;
4059 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004060
4061 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004062 (args[index] == String16("--frame-composition"))) {
4063 index++;
4064 dumpFrameCompositionInfo(result);
4065 dumpAll = false;
4066 }
4067
4068 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004069 (args[index] == String16("--display-identification"))) {
4070 index++;
4071 dumpDisplayIdentificationData(result);
4072 dumpAll = false;
4073 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004074
4075 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4076 index++;
4077 mTimeStats.parseArgs(asProto, args, index, result);
4078 dumpAll = false;
4079 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004081
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004082 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004083 if (asProto) {
4084 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4085 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4086 } else {
4087 dumpAllLocked(args, index, result);
4088 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004089 }
4090
Mathias Agopian9795c422009-08-26 16:36:26 -07004091 if (locked) {
4092 mStateLock.unlock();
4093 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 }
4095 write(fd, result.string(), result.size());
4096 return NO_ERROR;
4097}
4098
Dan Stozac7014012014-02-14 15:03:43 -08004099void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4100 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004101{
Robert Carr2047fae2016-11-28 14:09:09 -08004102 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004103 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004104 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004105}
4106
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004107void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004108 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004109{
4110 String8 name;
4111 if (index < args.size()) {
4112 name = String8(args[index]);
4113 index++;
4114 }
4115
Dominik Laskowski075d3172018-05-24 15:50:06 -07004116 if (const auto displayId = getInternalDisplayId();
4117 displayId && getHwComposer().isConnected(*displayId)) {
4118 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004119 const nsecs_t period = activeConfig->getVsyncPeriod();
4120 result.appendFormat("%" PRId64 "\n", period);
4121 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004122
4123 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004124 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004125 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004126 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004127 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004128 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004129 }
Robert Carr2047fae2016-11-28 14:09:09 -08004130 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131 }
4132}
4133
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004134void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004135 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004136{
4137 String8 name;
4138 if (index < args.size()) {
4139 name = String8(args[index]);
4140 index++;
4141 }
4142
Robert Carr2047fae2016-11-28 14:09:09 -08004143 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004145 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004146 }
Robert Carr2047fae2016-11-28 14:09:09 -08004147 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004148
Svetoslavd85084b2014-03-20 10:28:31 -07004149 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004150}
4151
Jamie Gennis6547ff42013-07-16 20:12:42 -07004152// This should only be called from the main thread. Otherwise it would need
4153// the lock and should use mCurrentState rather than mDrawingState.
4154void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004155 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004156 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004157 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004158
4159 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4160}
4161
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004162void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004163{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004164 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004165
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004166 if (isLayerTripleBufferingDisabled())
4167 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004168
4169 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004170 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004171 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004172 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004173 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4174 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004175 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004176}
4177
Dan Stozab90cf072015-03-05 11:05:59 -08004178void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4179{
4180 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004181 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4182 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004183 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004184 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004185 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4186 b + 1, bucketTimeSec, percent);
4187 }
David Sodman4a36e932017-11-07 14:29:47 -08004188 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004189 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004190 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004191 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004192 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004193}
4194
Dan Stozae77c7662016-05-13 11:37:28 -07004195void SurfaceFlinger::recordBufferingStats(const char* layerName,
4196 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004197 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4198 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004199 for (const auto& segment : history) {
4200 if (!segment.usedThirdBuffer) {
4201 stats.twoBufferTime += segment.totalTime;
4202 }
4203 if (segment.occupancyAverage < 1.0f) {
4204 stats.doubleBufferedTime += segment.totalTime;
4205 } else if (segment.occupancyAverage < 2.0f) {
4206 stats.tripleBufferedTime += segment.totalTime;
4207 }
4208 ++stats.numSegments;
4209 stats.totalTime += segment.totalTime;
4210 }
4211}
4212
Brian Andersond6927fb2016-07-23 23:37:30 -07004213void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4214 result.appendFormat("Layer frame timestamps:\n");
4215
4216 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4217 const size_t count = currentLayers.size();
4218 for (size_t i=0 ; i<count ; i++) {
4219 currentLayers[i]->dumpFrameEvents(result);
4220 }
4221}
4222
Dan Stozae77c7662016-05-13 11:37:28 -07004223void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4224 result.append("Buffering stats:\n");
4225 result.append(" [Layer name] <Active time> <Two buffer> "
4226 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004227 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004228 typedef std::tuple<std::string, float, float, float> BufferTuple;
4229 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004230 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004231 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004232 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004233 if (stats.numSegments == 0) {
4234 continue;
4235 }
4236 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4237 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4238 stats.totalTime;
4239 float doubleBufferRatio = static_cast<float>(
4240 stats.doubleBufferedTime) / stats.totalTime;
4241 float tripleBufferRatio = static_cast<float>(
4242 stats.tripleBufferedTime) / stats.totalTime;
4243 sorted.insert({activeTime, {name, twoBufferRatio,
4244 doubleBufferRatio, tripleBufferRatio}});
4245 }
4246 for (const auto& sortedPair : sorted) {
4247 float activeTime = sortedPair.first;
4248 const BufferTuple& values = sortedPair.second;
4249 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4250 std::get<0>(values).c_str(), activeTime,
4251 std::get<1>(values), std::get<2>(values),
4252 std::get<3>(values));
4253 }
4254 result.append("\n");
4255}
4256
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004257void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004258 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004259 const auto displayId = display->getId();
4260 if (!displayId) {
4261 continue;
4262 }
4263 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004264 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004265 continue;
4266 }
4267
Dominik Laskowski075d3172018-05-24 15:50:06 -07004268 result.appendFormat("Display %" PRIu64 " (HWC display %" PRIu64 "): ", *displayId,
4269 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004270 uint8_t port;
4271 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004272 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004273 result.append("no identification data\n");
4274 continue;
4275 }
4276
4277 if (!isEdid(data)) {
4278 result.append("unknown identification data: ");
4279 for (uint8_t byte : data) {
4280 result.appendFormat("%x ", byte);
4281 }
4282 result.append("\n");
4283 continue;
4284 }
4285
4286 const auto edid = parseEdid(data);
4287 if (!edid) {
4288 result.append("invalid EDID: ");
4289 for (uint8_t byte : data) {
4290 result.appendFormat("%x ", byte);
4291 }
4292 result.append("\n");
4293 continue;
4294 }
4295
4296 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4297 result.append(edid->displayName.data(), edid->displayName.length());
4298 result.append("\"\n");
4299 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004300}
4301
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004302void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004303 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4304 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004305 result.appendFormat("DisplayColorSetting: %s\n",
4306 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004307
4308 // TODO: print out if wide-color mode is active or not
4309
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004310 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311 const auto displayId = display->getId();
4312 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004313 continue;
4314 }
4315
Dominik Laskowski075d3172018-05-24 15:50:06 -07004316 result.appendFormat("Display %" PRIu64 " color modes:\n", *displayId);
4317 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004318 for (auto&& mode : modes) {
4319 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4320 }
4321
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004322 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004323 result.appendFormat(" Current color mode: %s (%d)\n",
4324 decodeColorMode(currentMode).c_str(), currentMode);
4325 }
4326 result.append("\n");
4327}
4328
David Sodman7e4ae112018-02-09 15:02:28 -08004329void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4330 std::string stringResult;
4331
4332 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004333 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4334 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004335 continue;
4336 }
4337
Dominik Laskowski05275f12018-11-01 15:03:24 -07004338 const auto& compositionInfoList = it->second;
4339 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004340 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4341 for (const auto& compositionInfo : compositionInfoList) {
4342 compositionInfo.dump(stringResult, nullptr);
4343 stringResult += base::StringPrintf("\n");
4344 }
4345 }
4346
4347 result.append(stringResult.c_str());
4348}
4349
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004350LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004351 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004352 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4353 const State& state = useDrawing ? mDrawingState : mCurrentState;
4354 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004355 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004356 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004357 });
4358
4359 return layersProto;
4360}
4361
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004362LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004363 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004364
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004365 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004366 resolution->set_w(display.getWidth());
4367 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004368
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004369 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4370 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4371 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004372
Dominik Laskowski075d3172018-05-24 15:50:06 -07004373 const auto displayId = display.getId();
4374 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004375 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004376 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004377 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004378 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004379 }
4380 });
4381
4382 return layersProto;
4383}
4384
Mathias Agopian74d211a2013-04-22 16:55:35 +02004385void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4386 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004388 bool colorize = false;
4389 if (index < args.size()
4390 && (args[index] == String16("--color"))) {
4391 colorize = true;
4392 index++;
4393 }
4394
4395 Colorizer colorizer(colorize);
4396
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397 // figure out if we're stuck somewhere
4398 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004399 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004400 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4401
4402 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004403 * Dump library configuration.
4404 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004405
4406 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004407 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004408 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004409 appendSfConfigString(result);
4410 appendUiConfigString(result);
4411 appendGuiConfigString(result);
4412 result.append("\n");
4413
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004414 result.append("\nDisplay identification data:\n");
4415 dumpDisplayIdentificationData(result);
4416
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004417 result.append("\nWide-Color information:\n");
4418 dumpWideColorInfo(result);
4419
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004420 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004421 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004422 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004423 result.append(SyncFeatures::getInstance().toString());
4424 result.append("\n");
4425
Andy McFadden41d67d72014-04-25 16:58:34 -07004426 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004427 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004428 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004429
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004430 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4431 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004432 if (const auto displayId = getInternalDisplayId();
4433 displayId && getHwComposer().isConnected(*displayId)) {
4434 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
4435 result.appendFormat("Display %" PRIu64 ": app phase %" PRId64 " ns, "
4436 "sf phase %" PRId64 " ns, "
4437 "early app phase %" PRId64 " ns, "
4438 "early sf phase %" PRId64 " ns, "
4439 "early app gl phase %" PRId64 " ns, "
4440 "early sf gl phase %" PRId64 " ns, "
4441 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4442 *displayId, vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset,
4443 sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4444 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004445 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004446 result.append("\n");
4447
Dan Stozab90cf072015-03-05 11:05:59 -08004448 // Dump static screen stats
4449 result.append("\n");
4450 dumpStaticScreenStats(result);
4451 result.append("\n");
4452
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004453 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4454
Dan Stozae77c7662016-05-13 11:37:28 -07004455 dumpBufferingStats(result);
4456
Andy McFadden4803b742012-09-24 19:07:20 -07004457 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004458 * Dump the visible layer list
4459 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004460 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004461 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004462 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4463 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004464 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004465
Chia-I Wu2f884132018-09-13 15:17:58 -07004466 {
4467 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4468 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4469 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4470 result.append("\n");
4471 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004472
David Sodman7e4ae112018-02-09 15:02:28 -08004473 result.append("\nFrame-Composition information:\n");
4474 dumpFrameCompositionInfo(result);
4475 result.append("\n");
4476
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004478 * Dump Display state
4479 */
4480
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004481 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004482 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004483 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004484 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004486 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004487 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004488
4489 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004490 * Dump SurfaceFlinger global state
4491 */
4492
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004493 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004494 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004495 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004496
David Sodmanbc815282017-11-05 18:57:52 -08004497 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004498
Dominik Laskowski075d3172018-05-24 15:50:06 -07004499 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004500 display->undefinedRegion.dump(result, "undefinedRegion");
4501 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4502 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004503 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004504 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004505 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004506 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004507
Dominik Laskowski075d3172018-05-24 15:50:06 -07004508 if (const auto displayId = getInternalDisplayId();
4509 displayId && getHwComposer().isConnected(*displayId)) {
4510 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004511 result.appendFormat(" refresh-rate : %f fps\n"
4512 " x-dpi : %f\n"
4513 " y-dpi : %f\n",
4514 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4515 activeConfig->getDpiY());
4516 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004517
Mathias Agopian74d211a2013-04-22 16:55:35 +02004518 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004519 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004520
Ana Krulec98b5b242018-08-10 15:03:23 -07004521 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004522 /*
4523 * VSYNC state
4524 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004525 if (mUseScheduler) {
4526 mScheduler->dump(mAppConnectionHandle, result);
4527 } else {
4528 mEventThread->dump(result);
4529 }
Dan Stozae22aec72016-08-01 13:20:59 -07004530 result.append("\n");
4531
4532 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004533 * Tracing state
4534 */
4535 mTracing.dump(result);
4536 result.append("\n");
4537
4538 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004539 * HWC layer minidump
4540 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004541 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004542 const auto displayId = display->getId();
4543 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004544 continue;
4545 }
4546
Dominik Laskowski075d3172018-05-24 15:50:06 -07004547 result.appendFormat("Display %" PRIu64 " HWC layers:\n", *displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004548 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004549 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004550 result.append("\n");
4551 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004552
4553 /*
4554 * Dump HWComposer state
4555 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004556 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004557 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004558 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004559 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004560 result.appendFormat(" h/w composer %s\n",
4561 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004562 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563
4564 /*
4565 * Dump gralloc state
4566 */
4567 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4568 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004569
4570 /*
4571 * Dump VrFlinger state if in use.
4572 */
4573 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4574 result.append("VrFlinger state:\n");
4575 result.append(mVrFlinger->Dump().c_str());
4576 result.append("\n");
4577 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004578}
4579
Dominik Laskowski075d3172018-05-24 15:50:06 -07004580const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004581 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004582 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004584 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004585 }
4586 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004587
Dominik Laskowski075d3172018-05-24 15:50:06 -07004588 ALOGE("%s: Invalid display %" PRIu64, __FUNCTION__, displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004589 static const Vector<sp<Layer>> empty;
4590 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004591}
4592
Keun young Park63f165f2012-08-31 10:53:36 -07004593bool SurfaceFlinger::startDdmConnection()
4594{
4595 void* libddmconnection_dso =
4596 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4597 if (!libddmconnection_dso) {
4598 return false;
4599 }
4600 void (*DdmConnection_start)(const char* name);
4601 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004602 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004603 if (!DdmConnection_start) {
4604 dlclose(libddmconnection_dso);
4605 return false;
4606 }
4607 (*DdmConnection_start)(getServiceName());
4608 return true;
4609}
4610
Chia-I Wu28f320b2018-05-03 11:02:56 -07004611void SurfaceFlinger::updateColorMatrixLocked() {
4612 mat4 colorMatrix;
4613 if (mGlobalSaturationFactor != 1.0f) {
4614 // Rec.709 luma coefficients
4615 float3 luminance{0.213f, 0.715f, 0.072f};
4616 luminance *= 1.0f - mGlobalSaturationFactor;
4617 mat4 saturationMatrix = mat4(
4618 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4619 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4620 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4621 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4622 );
4623 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4624 } else {
4625 colorMatrix = mClientColorMatrix * mDaltonizer();
4626 }
4627
4628 if (mCurrentState.colorMatrix != colorMatrix) {
4629 mCurrentState.colorMatrix = colorMatrix;
4630 mCurrentState.colorMatrixChanged = true;
4631 setTransactionFlags(eTransactionNeeded);
4632 }
4633}
4634
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004635status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004636#pragma clang diagnostic push
4637#pragma clang diagnostic error "-Wswitch-enum"
4638 switch (static_cast<ISurfaceComposerTag>(code)) {
4639 // These methods should at minimum make sure that the client requested
4640 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004641 case BOOT_FINISHED:
4642 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004643 case CREATE_CONNECTION:
4644 case CREATE_DISPLAY:
4645 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004646 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004647 case GET_ACTIVE_COLOR_MODE:
4648 case GET_ANIMATION_FRAME_STATS:
4649 case GET_HDR_CAPABILITIES:
4650 case SET_ACTIVE_CONFIG:
4651 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004652 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004653 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004654 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4655 IPCThreadState* ipc = IPCThreadState::self();
4656 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4657 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004658 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659 }
Robert Carr1db73f62016-12-21 12:58:51 -08004660 return OK;
4661 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004662 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004663 IPCThreadState* ipc = IPCThreadState::self();
4664 const int pid = ipc->getCallingPid();
4665 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004666 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4667 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004668 return PERMISSION_DENIED;
4669 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004670 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004672 // Used by apps to hook Choreographer to SurfaceFlinger.
4673 case CREATE_DISPLAY_EVENT_CONNECTION:
4674 // The following calls are currently used by clients that do not
4675 // request necessary permissions. However, they do not expose any secret
4676 // information, so it is OK to pass them.
4677 case AUTHENTICATE_SURFACE:
4678 case GET_ACTIVE_CONFIG:
4679 case GET_BUILT_IN_DISPLAY:
4680 case GET_DISPLAY_COLOR_MODES:
4681 case GET_DISPLAY_CONFIGS:
4682 case GET_DISPLAY_STATS:
4683 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4684 // Calling setTransactionState is safe, because you need to have been
4685 // granted a reference to Client* and Handle* to do anything with it.
4686 case SET_TRANSACTION_STATE:
4687 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004688 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004689 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004690 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004691 return OK;
4692 }
4693 case CAPTURE_LAYERS:
4694 case CAPTURE_SCREEN: {
4695 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004696 IPCThreadState* ipc = IPCThreadState::self();
4697 const int pid = ipc->getCallingPid();
4698 const int uid = ipc->getCallingUid();
4699 if ((uid != AID_GRAPHICS) &&
4700 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4701 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4702 return PERMISSION_DENIED;
4703 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704 return OK;
4705 }
4706 // The following codes are deprecated and should never be allowed to access SF.
4707 case CONNECT_DISPLAY_UNUSED:
4708 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4709 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4710 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004711 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004712 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004713
4714 // These codes are used for the IBinder protocol to either interrogate the recipient
4715 // side of the transaction for its canonical interface descriptor or to dump its state.
4716 // We let them pass by default.
4717 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4718 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4719 code == IBinder::SYSPROPS_TRANSACTION) {
4720 return OK;
4721 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004722 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004723 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004724 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004725 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4726 return OK;
4727 }
4728 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4729 return PERMISSION_DENIED;
4730#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004731}
4732
Ana Krulec13be8ad2018-08-21 02:43:56 +00004733status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4734 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004735 status_t credentialCheck = CheckTransactCodeCredentials(code);
4736 if (credentialCheck != OK) {
4737 return credentialCheck;
4738 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004739
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004740 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4741 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004742 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004743 IPCThreadState* ipc = IPCThreadState::self();
4744 const int uid = ipc->getCallingUid();
4745 if (CC_UNLIKELY(uid != AID_SYSTEM
4746 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004747 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004748 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004749 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004750 return PERMISSION_DENIED;
4751 }
4752 int n;
4753 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004754 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004755 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004756 return NO_ERROR;
4757 case 1002: // SHOW_UPDATES
4758 n = data.readInt32();
4759 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004760 invalidateHwcGeometry();
4761 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004762 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004763 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004764 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004765 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004766 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004767 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004768 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004769 setTransactionFlags(
4770 eTransactionNeeded|
4771 eDisplayTransactionNeeded|
4772 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004773 return NO_ERROR;
4774 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004775 case 1006:{ // send empty update
4776 signalRefresh();
4777 return NO_ERROR;
4778 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004779 case 1008: // toggle use of hw composer
4780 n = data.readInt32();
4781 mDebugDisableHWC = n ? 1 : 0;
4782 invalidateHwcGeometry();
4783 repaintEverything();
4784 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004785 case 1009: // toggle use of transform hint
4786 n = data.readInt32();
4787 mDebugDisableTransformHint = n ? 1 : 0;
4788 invalidateHwcGeometry();
4789 repaintEverything();
4790 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004791 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004792 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 reply->writeInt32(0);
4794 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004795 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004796 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004797 return NO_ERROR;
4798 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004799 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004800 if (!display) {
4801 return NAME_NOT_FOUND;
4802 }
4803
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004804 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004805 return NO_ERROR;
4806 }
4807 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004808 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004809 // daltonize
4810 n = data.readInt32();
4811 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004812 case 1:
4813 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4814 break;
4815 case 2:
4816 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4817 break;
4818 case 3:
4819 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4820 break;
4821 default:
4822 mDaltonizer.setType(ColorBlindnessType::None);
4823 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004824 }
4825 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004826 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004827 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004828 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004829 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004830
4831 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004832 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004834 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004835 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004836 // apply a color matrix
4837 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004838 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004839 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004840 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004841 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004842 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004843 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004844 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004845 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004846 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004847 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004848
4849 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4850 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004851 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004852 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4853 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4854 }
4855
Chia-I Wu28f320b2018-05-03 11:02:56 -07004856 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004857 return NO_ERROR;
4858 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004859 // This is an experimental interface
4860 // Needs to be shifted to proper binder interface when we productize
4861 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004862 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004863 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004864 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004865 return NO_ERROR;
4866 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004867 case 1017: {
4868 n = data.readInt32();
4869 mForceFullDamage = static_cast<bool>(n);
4870 return NO_ERROR;
4871 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004872 case 1018: { // Modify Choreographer's phase offset
4873 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004874 if (mUseScheduler) {
4875 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4876 } else {
4877 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4878 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004879 return NO_ERROR;
4880 }
4881 case 1019: { // Modify SurfaceFlinger's phase offset
4882 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004883 if (mUseScheduler) {
4884 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4885 } else {
4886 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4887 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004888 return NO_ERROR;
4889 }
Irvel468051e2016-06-13 16:44:44 -07004890 case 1020: { // Layer updates interceptor
4891 n = data.readInt32();
4892 if (n) {
4893 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004894 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004895 }
4896 else{
4897 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004898 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004899 }
4900 return NO_ERROR;
4901 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004902 case 1021: { // Disable HWC virtual displays
4903 n = data.readInt32();
4904 mUseHwcVirtualDisplays = !n;
4905 return NO_ERROR;
4906 }
Romain Guy0147a172017-06-01 13:53:56 -07004907 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004909 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004910
Chia-I Wu28f320b2018-05-03 11:02:56 -07004911 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004912 return NO_ERROR;
4913 }
Romain Guy54f154a2017-10-24 21:40:32 +01004914 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004915 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004916 invalidateHwcGeometry();
4917 repaintEverything();
4918 return NO_ERROR;
4919 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004920 // Deprecate, use 1030 to check whether the device is color managed.
4921 case 1024: {
4922 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004923 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004924 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004925 n = data.readInt32();
4926 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004927 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004928 mTracing.enable();
4929 doTracing("tracing.enable");
4930 reply->writeInt32(NO_ERROR);
4931 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004932 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004933 status_t err = mTracing.disable();
4934 reply->writeInt32(err);
4935 }
4936 return NO_ERROR;
4937 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004938 case 1026: { // Get layer tracing status
4939 reply->writeBool(mTracing.isEnabled());
4940 return NO_ERROR;
4941 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004942 // Is a DisplayColorSetting supported?
4943 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004944 const auto display = getDefaultDisplayDevice();
4945 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004946 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004947 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004948
4949 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4950 switch (setting) {
4951 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004952 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004953 break;
4954 case DisplayColorSetting::UNMANAGED:
4955 reply->writeBool(true);
4956 break;
4957 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004958 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004959 break;
4960 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004961 reply->writeBool(
4962 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004963 break;
4964 }
4965 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004966 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004967 // Is VrFlinger active?
4968 case 1028: {
4969 Mutex::Autolock _l(mStateLock);
4970 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4971 return NO_ERROR;
4972 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004973 // Is device color managed?
4974 case 1030: {
4975 reply->writeBool(useColorManagement);
4976 return NO_ERROR;
4977 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004978 // Override default composition data space
4979 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4980 // && adb shell stop zygote && adb shell start zygote
4981 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4982 // adb shell stop zygote && adb shell start zygote
4983 case 1031: {
4984 Mutex::Autolock _l(mStateLock);
4985 n = data.readInt32();
4986 if (n) {
4987 n = data.readInt32();
4988 if (n) {
4989 Dataspace dataspace = static_cast<Dataspace>(n);
4990 if (!validateCompositionDataspace(dataspace)) {
4991 return BAD_VALUE;
4992 }
4993 mDefaultCompositionDataspace = dataspace;
4994 }
4995 n = data.readInt32();
4996 if (n) {
4997 Dataspace dataspace = static_cast<Dataspace>(n);
4998 if (!validateCompositionDataspace(dataspace)) {
4999 return BAD_VALUE;
5000 }
5001 mWideColorGamutCompositionDataspace = dataspace;
5002 }
5003 } else {
5004 // restore composition data space.
5005 mDefaultCompositionDataspace = defaultCompositionDataspace;
5006 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5007 }
5008 return NO_ERROR;
5009 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005010 }
5011 }
5012 return err;
5013}
5014
Steven Thomas6d8110b2017-08-31 18:24:21 -07005015void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005016 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005017 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005018}
5019
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005020// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5021class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005022public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5024 ~WindowDisconnector() {
5025 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005026 }
5027
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005028private:
5029 ANativeWindow* mWindow;
5030 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005031};
5032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005033status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005034 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5035 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005036 uint32_t reqWidth, uint32_t reqHeight,
5037 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005038 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005039 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005041 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005042
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005043 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5044
Chia-I Wu20261cb2018-08-23 12:55:44 -07005045 sp<DisplayDevice> display;
5046 {
5047 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005048
Chia-I Wu20261cb2018-08-23 12:55:44 -07005049 display = getDisplayDeviceLocked(displayToken);
5050 if (!display) return BAD_VALUE;
5051
Chia-I Wucb023152018-08-28 12:57:23 -07005052 // set the requested width/height to the logical display viewport size
5053 // by default
5054 if (reqWidth == 0 || reqHeight == 0) {
5055 reqWidth = uint32_t(display->getViewport().width());
5056 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005057 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005058 }
5059
Peiyong Lin0e003c92018-09-17 11:09:51 -07005060 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5061 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005062
5063 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005064 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005065 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5066 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005067}
5068
5069status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005070 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5071 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005072 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005073 ATRACE_CALL();
5074
5075 class LayerRenderArea : public RenderArea {
5076 public:
Robert Carr578038f2018-03-09 12:25:24 -08005077 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005078 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5079 bool childrenOnly)
5080 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005081 mLayer(layer),
5082 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005083 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005084 mFlinger(flinger),
5085 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005086 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005087 Rect getBounds() const override {
5088 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005089 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005090 }
Marissa Wall61c58622018-07-18 10:12:20 -07005091 int getHeight() const override {
5092 return mLayer->getActiveHeight(mLayer->getDrawingState());
5093 }
5094 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005095 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005096 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005097 Rect getSourceCrop() const override {
5098 if (mCrop.isEmpty()) {
5099 return getBounds();
5100 } else {
5101 return mCrop;
5102 }
5103 }
Robert Carr578038f2018-03-09 12:25:24 -08005104 class ReparentForDrawing {
5105 public:
5106 const sp<Layer>& oldParent;
5107 const sp<Layer>& newParent;
5108
5109 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5110 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005111 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005112 }
Robert Carr15eae092018-03-23 13:43:53 -07005113 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005114 };
5115
5116 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005117 const Rect sourceCrop = getSourceCrop();
5118 // no need to check rotation because there is none
5119 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5120 sourceCrop.height() != getReqHeight();
5121
Robert Carr578038f2018-03-09 12:25:24 -08005122 if (!mChildrenOnly) {
5123 mTransform = mLayer->getTransform().inverse();
5124 drawLayers();
5125 } else {
5126 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005127 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005128 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5129 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005130
5131 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5132 drawLayers();
5133 }
5134 }
chaviwa76b2712017-09-20 12:02:26 -07005135
chaviwa76b2712017-09-20 12:02:26 -07005136 private:
chaviw7206d492017-11-10 16:16:12 -08005137 const sp<Layer> mLayer;
5138 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005139
5140 // In the "childrenOnly" case we reparent the children to a screenshot
5141 // layer which has no properties set and which does not draw.
5142 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005143 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005144 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005145
5146 SurfaceFlinger* mFlinger;
5147 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005148 };
5149
5150 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5151 auto parent = layerHandle->owner.promote();
5152
Robert Carr2e102c92018-10-23 12:11:15 -07005153 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005154 ALOGE("captureLayers called with a removed parent");
5155 return NAME_NOT_FOUND;
5156 }
5157
Robert Carr578038f2018-03-09 12:25:24 -08005158 const int uid = IPCThreadState::self()->getCallingUid();
5159 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5160 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5161 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5162 return PERMISSION_DENIED;
5163 }
5164
chaviw7206d492017-11-10 16:16:12 -08005165 Rect crop(sourceCrop);
5166 if (sourceCrop.width() <= 0) {
5167 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005168 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005169 }
5170
5171 if (sourceCrop.height() <= 0) {
5172 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005173 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005174 }
5175
5176 int32_t reqWidth = crop.width() * frameScale;
5177 int32_t reqHeight = crop.height() * frameScale;
5178
Chia-I Wu20261cb2018-08-23 12:55:44 -07005179 // really small crop or frameScale
5180 if (reqWidth <= 0) {
5181 reqWidth = 1;
5182 }
5183 if (reqHeight <= 0) {
5184 reqHeight = 1;
5185 }
5186
Peiyong Lin0e003c92018-09-17 11:09:51 -07005187 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005188
Robert Carr578038f2018-03-09 12:25:24 -08005189 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005190 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5191 if (!layer->isVisible()) {
5192 return;
Robert Carr578038f2018-03-09 12:25:24 -08005193 } else if (childrenOnly && layer == parent.get()) {
5194 return;
chaviwa76b2712017-09-20 12:02:26 -07005195 }
5196 visitor(layer);
5197 });
5198 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005199 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005200}
5201
5202status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5203 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005204 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005205 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005206 bool useIdentityTransform) {
5207 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005208
Peiyong Lin0e003c92018-09-17 11:09:51 -07005209 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005210 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5211 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005212 *outBuffer =
5213 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5214 static_cast<android_pixel_format>(reqPixelFormat), 1,
5215 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005216
5217 // This mutex protects syncFd and captureResult for communication of the return values from the
5218 // main thread back to this Binder thread
5219 std::mutex captureMutex;
5220 std::condition_variable captureCondition;
5221 std::unique_lock<std::mutex> captureLock(captureMutex);
5222 int syncFd = -1;
5223 std::optional<status_t> captureResult;
5224
Robert Carr03480e22018-01-04 16:02:06 -08005225 const int uid = IPCThreadState::self()->getCallingUid();
5226 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5227
Dominik Laskowski8c001672018-05-30 16:52:06 -07005228 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005229 // If there is a refresh pending, bug out early and tell the binder thread to try again
5230 // after the refresh.
5231 if (mRefreshPending) {
5232 ATRACE_NAME("Skipping screenshot for now");
5233 std::unique_lock<std::mutex> captureLock(captureMutex);
5234 captureResult = std::make_optional<status_t>(EAGAIN);
5235 captureCondition.notify_one();
5236 return;
5237 }
5238
5239 status_t result = NO_ERROR;
5240 int fd = -1;
5241 {
5242 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005243 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005244 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5245 useIdentityTransform, forSystem, &fd);
5246 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005247 }
5248
5249 {
5250 std::unique_lock<std::mutex> captureLock(captureMutex);
5251 syncFd = fd;
5252 captureResult = std::make_optional<status_t>(result);
5253 captureCondition.notify_one();
5254 }
5255 });
5256
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005257 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005259 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005260 while (*captureResult == EAGAIN) {
5261 captureResult.reset();
5262 result = postMessageAsync(message);
5263 if (result != NO_ERROR) {
5264 return result;
5265 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005266 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267 }
5268 result = *captureResult;
5269 }
5270
5271 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005272 sync_wait(syncFd, -1);
5273 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005274 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005275
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005276 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005277}
5278
chaviwa76b2712017-09-20 12:02:26 -07005279void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005280 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005281 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005282 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005283
Lloyd Pique144e1162017-12-20 16:44:52 -08005284 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005285
chaviwa76b2712017-09-20 12:02:26 -07005286 const auto reqWidth = renderArea.getReqWidth();
5287 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005288 const auto sourceCrop = renderArea.getSourceCrop();
5289 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005290
Peiyong Lin0e003c92018-09-17 11:09:51 -07005291 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005292 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005293
Mathias Agopian180f10d2013-04-10 22:55:41 -07005294 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005295 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005296
5297 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005298 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005299 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005300
chaviw50da5042018-04-09 13:49:37 -07005301 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005302 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005303 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005304
chaviwa76b2712017-09-20 12:02:26 -07005305 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005306 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005307 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005308 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005309 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005310}
5311
chaviwa76b2712017-09-20 12:02:26 -07005312status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5313 TraverseLayersFunction traverseLayers,
5314 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005315 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005316 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005317 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005318 ATRACE_CALL();
5319
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005320 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005321
5322 traverseLayers([&](Layer* layer) {
5323 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5324 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005325
Robert Carr03480e22018-01-04 16:02:06 -08005326 // We allow the system server to take screenshots of secure layers for
5327 // use in situations like the Screen-rotation animation and place
5328 // the impetus on WindowManager to not persist them.
5329 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005330 ALOGW("FB is protected: PERMISSION_DENIED");
5331 return PERMISSION_DENIED;
5332 }
5333
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005334 // this binds the given EGLImage as a framebuffer for the
5335 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005336 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005337 if (bufferBond.getStatus() != NO_ERROR) {
5338 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005339 return INVALID_OPERATION;
5340 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005341
Dan Stozaabcda352017-06-01 14:37:39 -07005342 // this will in fact render into our dequeued buffer
5343 // via an FBO, which means we didn't have to create
5344 // an EGLSurface and therefore we're not
5345 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005346 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005347
Alec Mouri492bc572018-09-11 21:40:04 +00005348 base::unique_fd syncFd = getRenderEngine().flush();
5349 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005350 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005351 }
Alec Mouri492bc572018-09-11 21:40:04 +00005352 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005353
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005354 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005355}
5356
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005357// ---------------------------------------------------------------------------
5358
Dan Stoza412903f2017-04-27 13:42:17 -07005359void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5360 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005361}
5362
Dan Stoza412903f2017-04-27 13:42:17 -07005363void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5364 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005365}
5366
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005367void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005368 const LayerVector::Visitor& visitor) {
5369 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005370 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005371 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005372 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005373 continue;
5374 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005375 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005376 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005377 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005378 return;
5379 }
chaviwa76b2712017-09-20 12:02:26 -07005380 if (!layer->isVisible()) {
5381 return;
5382 }
5383 visitor(layer);
5384 });
5385 }
5386}
5387
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005388}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005389
Lloyd Pique074e8122018-07-26 12:57:23 -07005390
Mathias Agopian3f844832013-08-07 21:24:32 -07005391#if defined(__gl_h_)
5392#error "don't include gl/gl.h in this file"
5393#endif
5394
5395#if defined(__gl2_h_)
5396#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005397#endif