blob: 35ba39100d56104ac2886892ea28674c7103b9a5 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700128 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700144ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
145 switch (rotation) {
146 case ISurfaceComposer::eRotateNone:
147 return ui::Transform::ROT_0;
148 case ISurfaceComposer::eRotate90:
149 return ui::Transform::ROT_90;
150 case ISurfaceComposer::eRotate180:
151 return ui::Transform::ROT_180;
152 case ISurfaceComposer::eRotate270:
153 return ui::Transform::ROT_270;
154 }
155 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
156 return ui::Transform::ROT_0;
157}
158
Peiyong Linfca547f2018-07-09 13:03:33 -0700159#pragma clang diagnostic pop
160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161class ConditionalLock {
162public:
163 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
164 if (lock) {
165 mMutex.lock();
166 }
167 }
168 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
169private:
170 Mutex& mMutex;
171 bool mLocked;
172};
Peiyong Linfca547f2018-07-09 13:03:33 -0700173
Peiyong Lin9d846a52018-11-05 13:18:20 -0800174// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
175bool validateCompositionDataspace(Dataspace dataspace) {
176 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
177}
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179} // namespace anonymous
180
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181// ---------------------------------------------------------------------------
182
Mathias Agopian99b49842011-06-27 16:05:52 -0700183const String16 sHardwareTest("android.permission.HARDWARE_TEST");
184const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
185const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
186const String16 sDump("android.permission.DUMP");
187
188// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800189int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
190int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700191int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700192bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800193uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800194bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800195bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800196int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600197bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700198int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700199bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700200bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700201Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
202ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
203Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
204ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700205
Kalle Raitaa099a242017-01-11 11:17:29 -0800206std::string getHwcServiceName() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.hwc_service_name", value, "default");
209 ALOGI("Using HWComposer service: '%s'", value);
210 return std::string(value);
211}
212
213bool useTrebleTestingOverride() {
214 char value[PROPERTY_VALUE_MAX] = {};
215 property_get("debug.sf.treble_testing_override", value, "false");
216 ALOGI("Treble testing override: '%s'", value);
217 return std::string(value) == "true";
218}
219
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
221 switch(displayColorSetting) {
222 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Enhanced");
228 default:
229 return std::string("Unknown ") +
230 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800232}
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Pique90c115d2018-09-18 21:39:42 -0700243SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
244 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700246 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800253 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800254 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800255 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700257 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700258 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700259 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700260 mDebugInTransaction(0),
261 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700262 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700263 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700264 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800265 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800266 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700268 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700269 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800270
Lloyd Pique90c115d2018-09-18 21:39:42 -0700271SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
272 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
275 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
276 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
277
278 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
280
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800281 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700284 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
286
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700287 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
289
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800290 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
292
Steven Thomas050b2c82017-03-06 11:45:16 -0800293 // Vr flinger is only enabled on Daydream ready devices.
294 useVrFlinger = getBool< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::useVrFlinger>(false);
296
Fabien Sanglard1971b632017-03-10 14:50:03 -0800297 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
299
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600300 hasWideColorDisplay =
301 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700302 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700303 getBool<V1_2::ISurfaceFlingerConfigs,
304 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
305
306 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
307 if (surfaceFlingerConfigsServiceV1_2) {
308 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700309 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
310 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
311 defaultCompositionDataspace = tmpDefaultDataspace;
312 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
313 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
314 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
315 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700316 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800317 mDefaultCompositionDataspace = defaultCompositionDataspace;
318 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600319
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320 useContextPriority = getBool<ISurfaceFlingerConfigs,
321 &ISurfaceFlingerConfigs::useContextPriority>(true);
322
Iris Chang7501ed62018-04-30 14:45:42 +0800323 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700324 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
325 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation::ORIENTATION_0);
327
328 switch (primaryDisplayOrientation) {
329 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800343
Lloyd Pique90c115d2018-09-18 21:39:42 -0700344 mPrimaryDispSync =
345 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
346 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 // debugging stuff...
349 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopianb4b17302013-03-20 18:36:41 -0700351 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700352 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 property_get("debug.sf.showupdates", value, "0");
355 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700357 property_get("debug.sf.ddms", value, "0");
358 mDebugDDMS = atoi(value);
359 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700360 if (!startDdmConnection()) {
361 // start failed, and DDMS debugging not enabled
362 mDebugDDMS = 0;
363 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700365 ALOGI_IF(mDebugRegion, "showupdates enabled");
366 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700367
368 property_get("debug.sf.disable_backpressure", value, "0");
369 mPropagateBackpressure = !atoi(value);
370 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700371
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800372 property_get("debug.sf.enable_hwc_vds", value, "0");
373 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800374 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 property_get("ro.sf.disable_triple_buffer", value, "1");
377 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700379
Yiwei Zhang243b3782018-05-15 17:40:04 -0700380 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700381 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
382 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
383
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200384 property_get("debug.sf.early_phase_offset_ns", value, "-1");
385 const int earlySfOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
388 const int earlyGlSfOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
391 const int earlyAppOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
394 const int earlyGlAppOffsetNs = atoi(value);
395
Ana Krulec98b5b242018-08-10 15:03:23 -0700396 property_get("debug.sf.use_scheduler", value, "0");
397 mUseScheduler = atoi(value);
398
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200399 const VSyncModulator::Offsets earlyOffsets =
400 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
401 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
402 const VSyncModulator::Offsets earlyGlOffsets =
403 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
405 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
406 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700407
Romain Guy11d63f42017-07-20 12:47:14 -0700408 // We should be reading 'persist.sys.sf.color_saturation' here
409 // but since /data may be encrypted, we need to wait until after vold
410 // comes online to attempt to read the property. The property is
411 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800412
413 if (useTrebleTestingOverride()) {
414 // Without the override SurfaceFlinger cannot connect to HIDL
415 // services that are not listed in the manifests. Considered
416 // deriving the setting from the set service name, but it
417 // would be brittle if the name that's not 'default' is used
418 // for production purposes later on.
419 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423void SurfaceFlinger::onFirstRef()
424{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800425 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428SurfaceFlinger::~SurfaceFlinger()
429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Dan Stozac7014012014-02-14 15:03:43 -0800432void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433{
434 // the window manager died on us. prepare its eulogy.
435
Andy McFadden13a082e2012-08-24 10:16:42 -0700436 // restore initial conditions (default device unblank, etc)
437 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438
439 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441}
442
Robert Carr1db73f62016-12-21 12:58:51 -0800443static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700444 status_t err = client->initCheck();
445 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return nullptr;
449}
450
451sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
452 return initClient(new Client(this));
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
456 const sp<IGraphicBufferProducer>& gbp) {
457 if (authenticateSurfaceTexture(gbp) == false) {
458 return nullptr;
459 }
460 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
461 if (layer == nullptr) {
462 return nullptr;
463 }
464
465 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800466}
467
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700468sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
469 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470{
471 class DisplayToken : public BBinder {
472 sp<SurfaceFlinger> flinger;
473 virtual ~DisplayToken() {
474 // no more references, this display must be terminated
475 Mutex::Autolock _l(flinger->mStateLock);
476 flinger->mCurrentState.displays.removeItem(this);
477 flinger->setTransactionFlags(eDisplayTransactionNeeded);
478 }
479 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700480 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 : flinger(flinger) {
482 }
483 };
484
485 sp<BBinder> token = new DisplayToken(this);
486
487 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 // Display ID is assigned when virtual display is allocated by HWC.
489 DisplayDeviceState state;
490 state.isSecure = secure;
491 state.displayName = displayName;
492 mCurrentState.displays.add(token, state);
493 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494 return token;
495}
496
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 Mutex::Autolock _l(mStateLock);
499
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
501 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700502 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 return;
504 }
505
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
507 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700508 ALOGE("destroyDisplay called for non-virtual display");
509 return;
510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 mInterceptor->saveDisplayDeletion(state.sequenceId);
512 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700513 setTransactionFlags(eDisplayTransactionNeeded);
514}
515
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 std::optional<DisplayId> displayId;
518
519 if (id == HWC_DISPLAY_PRIMARY) {
520 displayId = getInternalDisplayId();
521 } else if (id == HWC_DISPLAY_EXTERNAL) {
522 displayId = getExternalDisplayId();
523 }
524
525 if (!displayId) {
526 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800527 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700528 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700529
530 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700531}
532
Ady Abraham37965d42018-11-01 13:43:32 -0700533status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
534 if (!outGetColorManagement) {
535 return BAD_VALUE;
536 }
537 *outGetColorManagement = useColorManagement;
538 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700539}
540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541void SurfaceFlinger::bootFinished()
542{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700543 if (mStartPropertySetThread->join() != NO_ERROR) {
544 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 const nsecs_t now = systemTime();
547 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000548 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
550 // wait patiently for the window manager death
551 const String16 name("window");
552 sp<IBinder> window(defaultServiceManager()->getService(name));
553 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700554 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 }
556
Steven Thomas050b2c82017-03-06 11:45:16 -0800557 if (mVrFlinger) {
558 mVrFlinger->OnBootFinished();
559 }
560
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700562 // formerly we would just kill the process, but we now ask it to exit so it
563 // can choose where to stop the animation.
564 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700565
566 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
567 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
568 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700569
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 postMessageAsync(new LambdaMessage([this] {
571 readPersistentProperties();
572 mBootStage = BootStage::FINISHED;
573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700598 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700599}
600
Wei Wangf9b05ee2017-07-19 20:59:39 -0700601// Do not call property_set on main thread which will be blocked by init
602// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700604 ALOGI( "SurfaceFlinger's main thread ready to run. "
605 "Initializing graphics H/W...");
606
Thierry Strudel2924d012017-08-14 15:19:37 -0700607 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700612 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 mScheduler = getFactory().createScheduler([this](bool enabled) {
614 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
615 });
616
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700618 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 [this] { resyncWithRateLimit(); },
620 impl::EventThread::InterceptVSyncsCallback());
621 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700622 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700623 [this] { resyncWithRateLimit(); },
624 [this](nsecs_t timestamp) {
625 mInterceptor->saveVSyncEvent(timestamp);
626 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800627
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700629 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
630 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 } else {
632 mEventThreadSource =
633 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
634 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
635 mEventThread =
636 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
637 [this] { resyncWithRateLimit(); },
638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 [this](nsecs_t timestamp) {
648 mInterceptor->saveVSyncEvent(timestamp);
649 },
650 "sfEventThread");
651 mEventQueue->setEventThread(mSFEventThread.get());
652 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
Steven Thomasb02664d2017-07-26 18:48:28 -0700655 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700656 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700657 renderEngineFeature |= (useColorManagement ?
658 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700659 renderEngineFeature |= (useContextPriority ?
660 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700661
662 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
663 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700664 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
665 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800666 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700670 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700671 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Alec Mouri8d4f90a2018-11-14 22:33:24 +0000679 // make the default display GLContext current so that we can create textures
680 // when creating Layers (which may happens before we render something)
681 display->makeCurrent();
682
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 // This callback is called from the vr flinger dispatch thread. We
686 // need to call signalTransaction(), which requires holding
687 // mStateLock when we're not on the main thread. Acquiring
688 // mStateLock from the vr flinger dispatch thread might trigger a
689 // deadlock in surface flinger (see b/66916578), so post a message
690 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700692 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
693 mVrFlingerRequestsDisplay = requestDisplay;
694 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
698 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700699 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700700 .value_or(0),
701 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800702 if (!mVrFlinger) {
703 ALOGE("Failed to start vrflinger");
704 }
705 }
706
Lloyd Pique90c115d2018-09-18 21:39:42 -0700707 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700709
Mathias Agopian92a979a2012-08-02 18:32:23 -0700710 // initialize our drawing state
711 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700712
Andy McFadden13a082e2012-08-24 10:16:42 -0700713 // set initial conditions (e.g. unblank default device)
714 initializeDisplays();
715
David Sodmanbc815282017-11-05 18:57:52 -0800716 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700717
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700719
720 const bool presentFenceReliable =
721 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
722 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723
724 if (mStartPropertySetThread->Start() != NO_ERROR) {
725 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727
Chia-I Wud49d6692018-06-27 07:17:41 +0800728 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
729 // is used to saturate legacy sRGB content. However, to make sure the same color under
730 // Display P3 will be saturated to the same color, we intentionally break the API spec
731 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
732 // such saturation matrix on Display P3 is understood fully, the API should always return
733 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700734 mEnhancedSaturationMatrix =
735 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800736
737 // we will apply this on Display P3.
738 if (mEnhancedSaturationMatrix != mat4()) {
739 ColorSpace srgb(ColorSpace::sRGB());
740 ColorSpace displayP3(ColorSpace::DisplayP3());
741 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
742 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
743 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
744 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800745
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700747}
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 Mutex::Autolock _l(mStateLock);
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752 char value[PROPERTY_VALUE_MAX];
753
754 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700756 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800757 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100758
759 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700760 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700761}
762
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Start boot animation service by setting a property mailbox
765 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700768 if (mStartPropertySetThread->join() != NO_ERROR) {
769 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800770 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700771}
772
Mathias Agopian875d8e12013-06-07 15:35:48 -0700773size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800774 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700775}
776
Mathias Agopian875d8e12013-06-07 15:35:48 -0700777size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800778 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700779}
780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800781// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800782
Jamie Gennis582270d2011-08-17 18:19:00 -0700783bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800785 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800786 return authenticateSurfaceTextureLocked(bufferProducer);
787}
788
789bool SurfaceFlinger::authenticateSurfaceTextureLocked(
790 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800791 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800792 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800793}
794
Brian Anderson6b376712017-04-04 10:51:39 -0700795status_t SurfaceFlinger::getSupportedFrameTimestamps(
796 std::vector<FrameEvent>* outSupported) const {
797 *outSupported = {
798 FrameEvent::REQUESTED_PRESENT,
799 FrameEvent::ACQUIRE,
800 FrameEvent::LATCH,
801 FrameEvent::FIRST_REFRESH_START,
802 FrameEvent::LAST_REFRESH_START,
803 FrameEvent::GPU_COMPOSITION_DONE,
804 FrameEvent::DEQUEUE_READY,
805 FrameEvent::RELEASE,
806 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700807 ConditionalLock _l(mStateLock,
808 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700809 if (!getHwComposer().hasCapability(
810 HWC2::Capability::PresentFenceIsNotReliable)) {
811 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
812 }
813 return NO_ERROR;
814}
815
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700816status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
817 Vector<DisplayInfo>* configs) {
818 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 return BAD_VALUE;
820 }
821
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 const auto displayId = getPhysicalDisplayId(displayToken);
823 if (!displayId) {
824 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700825 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 // TODO: Not sure if display density should handled by SF any longer
828 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700831 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800832 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700833 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 }
835 return density;
836 }
837 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700840 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 return getDensityFromProperty("ro.sf.lcd_density"); }
842 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700848 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 DisplayInfo info = DisplayInfo();
850
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 float xdpi = hwConfig->getDpiX();
852 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700854 info.w = hwConfig->getWidth();
855 info.h = hwConfig->getHeight();
856 // Default display viewport to display width and height
857 info.viewportW = info.w;
858 info.viewportH = info.h;
859
Dominik Laskowski075d3172018-05-24 15:50:06 -0700860 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 // The density of the device is provided by a build property
862 float density = Density::getBuildDensity() / 160.0f;
863 if (density == 0) {
864 // the build doesn't provide a density -- this is wrong!
865 // use xdpi instead
866 ALOGE("ro.sf.lcd_density must be defined as a build property");
867 density = xdpi / 160.0f;
868 }
869 if (Density::getEmuDensity()) {
870 // if "qemu.sf.lcd_density" is specified, it overrides everything
871 xdpi = ydpi = density = Density::getEmuDensity();
872 density /= 160.0f;
873 }
874 info.density = density;
875
876 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877 const auto display = getDefaultDisplayDeviceLocked();
878 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700879
880 // This is for screenrecord
881 const Rect viewport = display->getViewport();
882 if (viewport.isValid()) {
883 info.viewportW = uint32_t(viewport.getWidth());
884 info.viewportH = uint32_t(viewport.getHeight());
885 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 } else {
887 // TODO: where should this value come from?
888 static const int TV_DENSITY = 213;
889 info.density = TV_DENSITY / 160.0f;
890 info.orientation = 0;
891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 info.xdpi = xdpi;
894 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900896 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897
Andy McFadden91b2ca82014-06-13 14:04:23 -0700898 // This is how far in advance a buffer must be queued for
899 // presentation at a given time. If you want a buffer to appear
900 // on the screen at time N, you must submit the buffer before
901 // (N - presentationDeadline).
902 //
903 // Normally it's one full refresh period (to give SF a chance to
904 // latch the buffer), but this can be reduced by configuring a
905 // DispSync offset. Any additional delays introduced by the hardware
906 // composer or panel must be accounted for here.
907 //
908 // We add an additional 1ms to allow for processing time and
909 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800911 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700912
913 // All non-virtual displays are currently considered secure.
914 info.secure = true;
915
Dominik Laskowski075d3172018-05-24 15:50:06 -0700916 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700917 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800918 std::swap(info.w, info.h);
919 }
920
Michael Wright28f24d02016-07-12 13:30:53 -0700921 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700922 }
923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 return NO_ERROR;
925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
928 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return BAD_VALUE;
930 }
931
Ana Krulece588e312018-09-18 12:32:24 -0700932 if (mUseScheduler) {
933 mScheduler->getDisplayStatInfo(stats);
934 } else {
935 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
936 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
937 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return NO_ERROR;
939}
940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
942 const auto display = getDisplayDevice(displayToken);
943 if (!display) {
944 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800945 return BAD_VALUE;
946 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700949}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700952 if (display->isVirtual()) {
953 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
954 return;
955 }
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 return;
960 }
961
Dominik Laskowski075d3172018-05-24 15:50:06 -0700962 const auto displayId = display->getId();
963 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700966 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967}
968
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700970 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 Vector<DisplayInfo> configs;
972 getDisplayConfigs(displayToken, &configs);
973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
975 configs.size());
976 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700977 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 const auto display = getDisplayDevice(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
981 displayToken.get());
982 } else if (display->isVirtual()) {
983 ALOGW("Attempt to set active config %d for virtual display", mode);
984 } else {
985 setActiveConfigInternal(display, mode);
986 }
987 }));
988
Mathias Agopian888c8222012-08-04 21:10:38 -0700989 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700990}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
993 Vector<ColorMode>* outColorModes) {
994 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700995 return BAD_VALUE;
996 }
997
Dominik Laskowski075d3172018-05-24 15:50:06 -0700998 const auto displayId = getPhysicalDisplayId(displayToken);
999 if (!displayId) {
1000 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001001 }
1002
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001004 {
1005 ConditionalLock _l(mStateLock,
1006 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001008 }
Michael Wright28f24d02016-07-12 13:30:53 -07001009 outColorModes->clear();
1010 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1011
1012 return NO_ERROR;
1013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1016 if (const auto display = getDisplayDevice(displayToken)) {
1017 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001018 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1023 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001024 if (display->isVirtual()) {
1025 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 ColorMode currentMode = display->getActiveColorMode();
1030 Dataspace currentDataSpace = display->getCompositionDataSpace();
1031 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001032
Peiyong Lin38e9a562018-04-10 16:24:20 -07001033 if (mode == currentMode && dataSpace == currentDataSpace &&
1034 renderIntent == currentRenderIntent) {
1035 return;
1036 }
1037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 display->setActiveColorMode(mode);
1039 display->setCompositionDataSpace(dataSpace);
1040 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001041
Dominik Laskowski075d3172018-05-24 15:50:06 -07001042 const auto displayId = display->getId();
1043 LOG_ALWAYS_FATAL_IF(!displayId);
1044 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1045
Dominik Laskowski34157762018-10-31 13:07:19 -07001046 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001048 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001052 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 Vector<ColorMode> modes;
1054 getDisplayColorModes(displayToken, &modes);
1055 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1056 if (mode < ColorMode::NATIVE || !exists) {
1057 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001060 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 const auto display = getDisplayDevice(displayToken);
1062 if (!display) {
1063 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1064 decodeColorMode(mode).c_str(), mode, displayToken.get());
1065 } else if (display->isVirtual()) {
1066 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1067 decodeColorMode(mode).c_str(), mode);
1068 } else {
1069 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1070 RenderIntent::COLORIMETRIC);
1071 }
1072 }));
1073
Michael Wright28f24d02016-07-12 13:30:53 -07001074 return NO_ERROR;
1075}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001076
Svetoslavd85084b2014-03-20 10:28:31 -07001077status_t SurfaceFlinger::clearAnimationFrameStats() {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.clearStats();
1080 return NO_ERROR;
1081}
1082
1083status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1084 Mutex::Autolock _l(mStateLock);
1085 mAnimFrameTracker.getStats(outStats);
1086 return NO_ERROR;
1087}
1088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001089status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1090 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001091 Mutex::Autolock _l(mStateLock);
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093 const auto display = getDisplayDeviceLocked(displayToken);
1094 if (!display) {
1095 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001096 return BAD_VALUE;
1097 }
1098
Peiyong Linfb069302018-04-25 14:34:31 -07001099 // At this point the DisplayDeivce should already be set up,
1100 // meaning the luminance information is already queried from
1101 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001103 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1104 capabilities.getDesiredMaxLuminance(),
1105 capabilities.getDesiredMaxAverageLuminance(),
1106 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001107
1108 return NO_ERROR;
1109}
1110
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001112 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001114
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (mInjectVSyncs == enable) {
1116 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118
Ana Krulec98b5b242018-08-10 15:03:23 -07001119 // TODO(akrulec): Part of the Injector should be refactored, so that it
1120 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 if (enable) {
1122 ALOGV("VSync Injections enabled");
1123 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001124 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001125 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001127 impl::EventThread::InterceptVSyncsCallback(),
1128 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001130 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 } else {
1132 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001133 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 }
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001137 }));
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 return NO_ERROR;
1140}
1141
1142status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 Mutex::Autolock _l(mStateLock);
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 if (!mInjectVSyncs) {
1146 ALOGE("VSync Injections not enabled");
1147 return BAD_VALUE;
1148 }
1149 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1150 ALOGV("Injecting VSync inside SurfaceFlinger");
1151 mVSyncInjector->onInjectSyncEvent(when);
1152 }
1153 return NO_ERROR;
1154}
1155
Lloyd Pique755e3192018-01-31 16:46:15 -08001156status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1157 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001158 // Try to acquire a lock for 1s, fail gracefully
1159 const status_t err = mStateLock.timedLock(s2ns(1));
1160 const bool locked = (err == NO_ERROR);
1161 if (!locked) {
1162 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1163 return TIMED_OUT;
1164 }
1165
1166 outLayers->clear();
1167 mCurrentState.traverseInZOrder([&](Layer* layer) {
1168 outLayers->push_back(layer->getLayerDebugInfo());
1169 });
1170
1171 mStateLock.unlock();
1172 return NO_ERROR;
1173}
1174
Peiyong Linc6780972018-10-28 15:24:08 -07001175status_t SurfaceFlinger::getCompositionPreference(
1176 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1177 Dataspace* outWideColorGamutDataspace,
1178 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001179 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001180 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001181 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001182 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001183 return NO_ERROR;
1184}
1185
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001186// ----------------------------------------------------------------------------
1187
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001188sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1189 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001190 if (mUseScheduler) {
1191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1193 } else {
1194 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001197 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1198 return mSFEventThread->createEventConnection();
1199 } else {
1200 return mEventThread->createEventConnection();
1201 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001202 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001203}
1204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206
1207void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209}
1210
1211void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213}
1214
1215void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001220 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001221 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001222}
1223
1224status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001225 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001230 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232 if (res == NO_ERROR) {
1233 msg->wait();
1234 }
1235 return res;
1236}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001238void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001239 do {
1240 waitForEvent();
1241 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242}
1243
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244void SurfaceFlinger::enableHardwareVsync() {
1245 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001246 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001247 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001250 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251}
1252
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 Mutex::Autolock _l(mHWVsyncLock);
1255
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (makeAvailable) {
1257 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001258 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1259 if (mUseScheduler) {
1260 mScheduler->makeHWSyncAvailable(true);
1261 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001262 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001263 // Hardware vsync is not currently available, so abort the resync
1264 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 return;
1266 }
1267
Dominik Laskowski075d3172018-05-24 15:50:06 -07001268 const auto displayId = getInternalDisplayId();
1269 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001270 return;
1271 }
1272
Dominik Laskowski075d3172018-05-24 15:50:06 -07001273 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275
Ana Krulece588e312018-09-18 12:32:24 -07001276 if (mUseScheduler) {
1277 mScheduler->setVsyncPeriod(period);
1278 } else {
1279 mPrimaryDispSync->reset();
1280 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281
Ana Krulece588e312018-09-18 12:32:24 -07001282 if (!mPrimaryHWVsyncEnabled) {
1283 mPrimaryDispSync->beginResync();
1284 mEventControlThread->setVsyncEnabled(true);
1285 mPrimaryHWVsyncEnabled = true;
1286 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 }
1288}
1289
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 Mutex::Autolock _l(mHWVsyncLock);
1292 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001294 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 mPrimaryHWVsyncEnabled = false;
1296 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (makeUnavailable) {
1298 mHWVsyncAvailable = false;
1299 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300}
1301
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302void SurfaceFlinger::resyncWithRateLimit() {
1303 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001304
1305 // No explicit locking is needed here since EventThread holds a lock while calling this method
1306 static nsecs_t sLastResyncAttempted = 0;
1307 const nsecs_t now = systemTime();
1308 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001310 }
Dan Stoza57164302017-05-08 14:03:54 -07001311 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312}
1313
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001314void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1315 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001316 ATRACE_NAME("SF onVsync");
1317
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 return;
1322 }
1323
Dominik Laskowski075d3172018-05-24 15:50:06 -07001324 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001325 return;
1326 }
1327
Dominik Laskowski075d3172018-05-24 15:50:06 -07001328 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001329 // For now, we don't do anything with external display vsyncs.
1330 return;
1331 }
1332
Ana Krulece588e312018-09-18 12:32:24 -07001333 if (mUseScheduler) {
1334 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001336 bool needsHwVsync = false;
1337 { // Scope for the lock
1338 Mutex::Autolock _l(mHWVsyncLock);
1339 if (mPrimaryHWVsyncEnabled) {
1340 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1341 }
1342 }
1343
1344 if (needsHwVsync) {
1345 enableHardwareVsync();
1346 } else {
1347 disableHardwareVsync(false);
1348 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001349 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001350}
1351
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001353 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1354 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001355}
1356
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001357void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001358 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001360 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 // Ignore events that do not have the right sequenceId.
1363 if (sequenceId != getBE().mComposerSequenceId) {
1364 return;
1365 }
1366
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Only lock if we're not on the main thread. This function is normally
1368 // called on a hwbinder thread, but for the primary display it's called on
1369 // the main thread with the state lock already held, so don't attempt to
1370 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001372
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001374
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001375 if (std::this_thread::get_id() == mMainThreadId) {
1376 // Process all pending hot plug events immediately if we are on the main thread.
1377 processDisplayHotplugEventsLocked();
1378 }
1379
Lloyd Piqueba04e622017-12-14 17:11:26 -08001380 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001384 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001388 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001389}
1390
Dominik Laskowski075d3172018-05-24 15:50:06 -07001391void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001394 if (const auto displayId = getInternalDisplayId()) {
1395 getHwComposer().setVsyncEnabled(*displayId,
1396 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1397 }
Mathias Agopian86303202012-07-24 22:46:10 -07001398}
1399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001401void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001402 if (mUseScheduler) {
1403 mScheduler->disableHardwareVsync(true);
1404 } else {
1405 disableHardwareVsync(true);
1406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 // Clear the drawing state so that the logic inside of
1408 // handleTransactionLocked will fire. It will determine the delta between
1409 // mCurrentState and mDrawingState and re-apply all changes when we make the
1410 // transition.
1411 mDrawingState.displays.clear();
Alec Mouri8d4f90a2018-11-14 22:33:24 +00001412 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413 mDisplays.clear();
1414}
1415
Steven Thomas050b2c82017-03-06 11:45:16 -08001416void SurfaceFlinger::updateVrFlinger() {
1417 if (!mVrFlinger)
1418 return;
1419 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001421 return;
1422 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
David Sodman105b7dc2017-11-04 20:28:14 -07001424 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 ALOGE("Vr flinger is only supported for remote hardware composer"
1426 " service connections. Ignoring request to transition to vr"
1427 " flinger.");
1428 mVrFlingerRequestsDisplay = false;
1429 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001430 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomas0123ac62018-07-12 11:32:34 -07001434 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001435 LOG_ALWAYS_FATAL_IF(!display);
1436 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001437 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1438 // called below. Clear the reference now so we don't accidentally use it
1439 // later.
1440 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001447 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001448 getBE().mHwc = getFactory().createHWComposer(
1449 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001450 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451
David Sodman105b7dc2017-11-04 20:28:14 -07001452 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1453 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001454
1455 if (vrFlingerRequestsDisplay) {
1456 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
1459 mVisibleRegionsDirty = true;
1460 invalidateHwcGeometry();
1461
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001463 display = getDefaultDisplayDeviceLocked();
1464 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001465 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001468 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 const nsecs_t period = activeConfig->getVsyncPeriod();
1470 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001471
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001472 // The present fences returned from vr_hwc are not an accurate
1473 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001474 if (mUseScheduler) {
1475 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1476 } else {
1477 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1478 !hasSyncFramework);
1479 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001480
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 // Use phase of 0 since phase is not known.
1482 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001483 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1484 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001485
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001486 resyncToHardwareVsync(false);
1487
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001488 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001489 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001490}
1491
Mathias Agopian4fec8732012-06-29 14:12:52 -07001492void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001493 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001494 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001496 bool frameMissed = !mHadClientComposition &&
1497 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001498 (mPreviousPresentFence->getSignalTime() ==
1499 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001500 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001501 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001502 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001503 mTimeStats.incrementMissedFrames();
1504 if (mPropagateBackpressure) {
1505 signalLayerUpdate();
1506 break;
1507 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001508 }
Dan Stoza50182882016-07-08 12:02:20 -07001509
Steven Thomas050b2c82017-03-06 11:45:16 -08001510 // Now that we're going to make it to the handleMessageTransaction()
1511 // call below it's safe to call updateVrFlinger(), which will
1512 // potentially trigger a display handoff.
1513 updateVrFlinger();
1514
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 bool refreshNeeded = handleMessageTransaction();
1516 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001517 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001518 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001519 // Signal a refresh if a transaction modified the window state,
1520 // a new buffer was latched, or if HWC has requested a full
1521 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522 signalRefresh();
1523 }
1524 break;
1525 }
1526 case MessageQueue::REFRESH: {
1527 handleMessageRefresh();
1528 break;
1529 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001530 }
1531}
1532
Dan Stoza6b9454d2014-11-07 16:00:59 -08001533bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001534 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001536 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001537 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001538 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001539 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001540}
1541
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001544
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001545 mRefreshPending = false;
1546
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001547 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001548 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001549 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001550 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001551 for (const auto& [token, display] : mDisplays) {
1552 beginFrame(display);
1553 prepareFrame(display);
1554 doDebugFlashRegions(display, repaintEverything);
1555 doComposition(display, repaintEverything);
1556 }
1557
Adrian Roos1e1a1282017-11-01 19:05:31 +01001558 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001559 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001560
1561 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001562 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001563
Dan Stozabfbffeb2016-07-21 14:49:33 -07001564 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001565 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001566 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001567 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001568 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001569
Alec Mouri86770e52018-09-24 22:40:58 +00001570 // Setup RenderEngine sync fences if native sync is supported.
1571 if (getBE().mRenderEngine->useNativeFenceSync()) {
1572 if (mHadClientComposition) {
1573 base::unique_fd flushFence(getRenderEngine().flush());
1574 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1575 getBE().flushFence = new Fence(std::move(flushFence));
1576 } else {
1577 // Cleanup for hygiene.
1578 getBE().flushFence = Fence::NO_FENCE;
1579 }
1580 }
1581
Jorim Jaggi90535212018-05-23 23:44:06 +02001582 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001583
David Sodman7e4ae112018-02-09 15:02:28 -08001584 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001585 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001586 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001587 compositionInfo.hwc.hwcLayer = nullptr;
1588 }
David Sodmanba340492018-08-05 21:51:33 -07001589 }
David Sodman7e4ae112018-02-09 15:02:28 -08001590
1591 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001593
David Sodmanfa9b2af2017-12-24 13:28:59 -08001594
1595bool SurfaceFlinger::handleMessageInvalidate() {
1596 ATRACE_CALL();
1597 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001598}
1599
David Sodman79bba0e2018-08-05 18:07:49 -07001600void SurfaceFlinger::calculateWorkingSet() {
1601 ATRACE_CALL();
1602 ALOGV(__FUNCTION__);
1603
David Sodman79bba0e2018-08-05 18:07:49 -07001604 // build the h/w work list
1605 if (CC_UNLIKELY(mGeometryInvalid)) {
1606 mGeometryInvalid = false;
1607 for (const auto& [token, display] : mDisplays) {
1608 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001609 if (!displayId) {
1610 continue;
1611 }
David Sodman79bba0e2018-08-05 18:07:49 -07001612
Dominik Laskowski075d3172018-05-24 15:50:06 -07001613 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1614 for (size_t i = 0; i < currentLayers.size(); i++) {
1615 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001616
Dominik Laskowski075d3172018-05-24 15:50:06 -07001617 if (!layer->hasHwcLayer(*displayId)) {
1618 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1619 layer->forceClientComposition(*displayId);
1620 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001621 }
1622 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001623
1624 layer->setGeometry(display, i);
1625 if (mDebugDisableHWC || mDebugRegion) {
1626 layer->forceClientComposition(*displayId);
1627 }
David Sodman79bba0e2018-08-05 18:07:49 -07001628 }
1629 }
1630 }
1631
1632 // Set the per-frame data
1633 for (const auto& [token, display] : mDisplays) {
1634 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001635 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001636 continue;
1637 }
1638
1639 if (mDrawingState.colorMatrixChanged) {
1640 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001641 status_t result =
1642 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001643 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1644 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001645 }
1646 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1647 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001648 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001649 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1650 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1651 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001652 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001653 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1654 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1655 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001656 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001657 }
1658
Peiyong Lind3788632018-09-18 16:01:31 -07001659 // TODO(b/111562338) remove when composer 2.3 is shipped.
1660 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001661 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001662 }
1663
Dominik Laskowski075d3172018-05-24 15:50:06 -07001664 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001665 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001666 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001667 continue;
1668 }
1669
Dominik Laskowski075d3172018-05-24 15:50:06 -07001670 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1671 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001672 }
1673
Peiyong Lin13effd12018-07-24 17:01:47 -07001674 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001675 ColorMode colorMode;
1676 Dataspace dataSpace;
1677 RenderIntent renderIntent;
1678 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1679 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1680 }
1681 }
1682
1683 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001684
1685 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001686 getBE().mCompositionInfo[token].clear();
1687
David Sodmanba340492018-08-05 21:51:33 -07001688 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001689 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001690 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001691
1692 if (displayId) {
1693 if (!layer->setHwcLayer(*displayId)) {
1694 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1695 }
1696 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001697 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001698
Dominik Laskowski05275f12018-11-01 15:03:24 -07001699 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001700 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1701 }
1702 }
David Sodman79bba0e2018-08-05 18:07:49 -07001703}
1704
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001706{
1707 // is debugging enabled
1708 if (CC_LIKELY(!mDebugRegion))
1709 return;
1710
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711 if (display->isPoweredOn()) {
1712 // transform the dirty region into this screen's coordinate space
1713 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1714 if (!dirtyRegion.isEmpty()) {
1715 // redraw the whole screen
1716 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717
David Sodmanfa9b2af2017-12-24 13:28:59 -08001718 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001719 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001720 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001721
Alec Mouri8d4f90a2018-11-14 22:33:24 +00001722 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001723 }
1724 }
1725
David Sodmanfa9b2af2017-12-24 13:28:59 -08001726 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727
1728 if (mDebugRegion > 1) {
1729 usleep(mDebugRegion * 1000);
1730 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001731
Dominik Laskowski05275f12018-11-01 15:03:24 -07001732 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001733}
1734
Adrian Roos1e1a1282017-11-01 19:05:31 +01001735void SurfaceFlinger::doTracing(const char* where) {
1736 ATRACE_CALL();
1737 ATRACE_NAME(where);
1738 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001739 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001740 }
1741}
1742
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001743void SurfaceFlinger::logLayerStats() {
1744 ATRACE_CALL();
1745 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001746 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001747 if (display->isPrimary()) {
1748 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001749 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001750 }
1751 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001752
1753 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001754 }
1755}
1756
David Sodman2b406362017-12-15 13:33:47 -08001757void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 ATRACE_CALL();
1760 ALOGV("preComposition");
1761
David Sodman2b406362017-12-15 13:33:47 -08001762 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1763
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001765 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001766 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767 needExtraInvalidate = true;
1768 }
Robert Carr2047fae2016-11-28 14:09:09 -08001769 });
1770
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771 if (needExtraInvalidate) {
1772 signalLayerUpdate();
1773 }
1774}
1775
Ana Krulece588e312018-09-18 12:32:24 -07001776void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1777 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001778 // Update queue of past composite+present times and determine the
1779 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001780 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001782 while (!getBE().mCompositePresentTimes.empty()) {
1783 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784 // Cached values should have been updated before calling this method,
1785 // which helps avoid duplicate syscalls.
1786 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1787 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1788 break;
1789 }
1790 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001791 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 }
1793
1794 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001795 while (getBE().mCompositePresentTimes.size() > 16) {
1796 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 }
1798
Ana Krulece588e312018-09-18 12:32:24 -07001799 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001800}
1801
Ana Krulece588e312018-09-18 12:32:24 -07001802void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1803 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001804 // Integer division and modulo round toward 0 not -inf, so we need to
1805 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001806 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1807 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1808 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809
Brian Andersond0010582017-03-07 13:20:31 -08001810 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1811 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001812 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001813 }
1814
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815 // Snap the latency to a value that removes scheduling jitter from the
1816 // composition and present times, which often have >1ms of jitter.
1817 // Reducing jitter is important if an app attempts to extrapolate
1818 // something (such as user input) to an accurate diasplay time.
1819 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1820 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001821 nsecs_t bias = stats.vsyncPeriod / 2;
1822 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1823 nsecs_t snappedCompositeToPresentLatency =
1824 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825
David Sodman99974d22017-11-28 12:04:33 -08001826 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001827 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1828 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001829 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830}
1831
David Sodman2b406362017-12-15 13:33:47 -08001832void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 ATRACE_CALL();
1835 ALOGV("postComposition");
1836
Brian Anderson3546a3f2016-07-14 11:51:14 -07001837 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001838 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001839 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001840 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001841 }
1842
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001843 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001844 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001845
David Sodman73beded2017-11-15 11:56:06 -08001846 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001847 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001848 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001849 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001850 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001851 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001852 } else {
1853 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1854 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001855
David Sodman73beded2017-11-15 11:56:06 -08001856 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001857 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001858 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001859 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001860 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001861
Ana Krulece588e312018-09-18 12:32:24 -07001862 DisplayStatInfo stats;
1863 if (mUseScheduler) {
1864 mScheduler->getDisplayStatInfo(&stats);
1865 } else {
1866 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1867 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1868 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001869
David Sodman2b406362017-12-15 13:33:47 -08001870 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871 // when we started doing work for this frame, but that should be okay
1872 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001873 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001874 CompositorTiming compositorTiming;
1875 {
David Sodman99974d22017-11-28 12:04:33 -08001876 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1877 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001878 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001879
Robert Carr2047fae2016-11-28 14:09:09 -08001880 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001881 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1882 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001883 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001884 recordBufferingStats(layer->getName().string(),
1885 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001886 }
Robert Carr2047fae2016-11-28 14:09:09 -08001887 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001888
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001889 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001890 if (mUseScheduler) {
1891 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001892 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001893 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1894 enableHardwareVsync();
1895 } else {
1896 disableHardwareVsync(false);
1897 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001898 }
1899 }
1900
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001901 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001902 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001903 if (mUseScheduler) {
1904 mScheduler->enableHardwareVsync();
1905 } else {
1906 enableHardwareVsync();
1907 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001908 }
1909 }
1910
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001911 if (mAnimCompositionPending) {
1912 mAnimCompositionPending = false;
1913
Brian Anderson4e606e32017-03-16 15:34:57 -07001914 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001915 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001916 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001917 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001918 // The HWC doesn't support present fences, so use the refresh
1919 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001920 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001921 mAnimFrameTracker.setActualPresentTime(presentTime);
1922 }
1923 mAnimFrameTracker.advanceFrame();
1924 }
Dan Stozab90cf072015-03-05 11:05:59 -08001925
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001926 mTimeStats.incrementTotalFrames();
1927 if (mHadClientComposition) {
1928 mTimeStats.incrementClientCompositionFrames();
1929 }
1930
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001931 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1932
Dominik Laskowski075d3172018-05-24 15:50:06 -07001933 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001934 return;
1935 }
1936
1937 nsecs_t currentTime = systemTime();
1938 if (mHasPoweredOff) {
1939 mHasPoweredOff = false;
1940 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001941 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001942 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001943 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1944 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001945 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001946 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001947 }
David Sodman4a36e932017-11-07 14:29:47 -08001948 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001949 }
David Sodman4a36e932017-11-07 14:29:47 -08001950 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001951
1952 {
1953 std::lock_guard lock(mTexturePoolMutex);
1954 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1955 if (refillCount > 0) {
1956 const size_t offset = mTexturePool.size();
1957 mTexturePool.resize(mTexturePoolSize);
1958 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1959 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1960 }
1961 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001962
Marissa Wallfda30bb2018-10-12 11:34:28 -07001963 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07001964 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965}
1966
1967void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 ATRACE_CALL();
1969 ALOGV("rebuildLayerStacks");
1970
Mathias Agopiancd60f992012-08-16 16:28:27 -07001971 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001972 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001973 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001974 mVisibleRegionsDirty = false;
1975 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001976
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001977 for (const auto& pair : mDisplays) {
1978 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001979 Region opaqueRegion;
1980 Region dirtyRegion;
1981 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001982 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001983 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001984 const Rect bounds = display->getBounds();
1985 if (display->isPoweredOn()) {
1986 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001987
Jeff Sharkey76488112017-02-27 14:15:18 -07001988 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001989 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07001990 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001991 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001992 Region drawRegion(tr.transform(
1993 layer->visibleNonTransparentRegion));
1994 drawRegion.andSelf(bounds);
1995 if (!drawRegion.isEmpty()) {
1996 layersSortedByZ.add(layer);
1997 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001998 // Clear out the HWC layer if this layer was
1999 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002000 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002001 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002002 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002003 // WM changes display->layerStack upon sleep/awake.
2004 // Here we make sure we delete the HWC layers even if
2005 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002006 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002007 }
2008
2009 // If a layer is not going to get a release fence because
2010 // it is invisible, but it is also going to release its
2011 // old buffer, add it to the list of layers needing
2012 // fences.
2013 if (hwcLayerDestroyed) {
2014 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2015 mLayersWithQueuedFrames.cend(), layer);
2016 if (found != mLayersWithQueuedFrames.cend()) {
2017 layersNeedingFences.add(layer);
2018 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002019 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002020 });
2021 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 display->setVisibleLayersSortedByZ(layersSortedByZ);
2023 display->setLayersNeedingFences(layersNeedingFences);
2024 display->undefinedRegion.set(bounds);
2025 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2026 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002027 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002028 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002030
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002033// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002034// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002035// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002036// The returned HDR data space is one of
2037// - Dataspace::UNKNOWN
2038// - Dataspace::BT2020_HLG
2039// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002040Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2041 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002042 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002043 *outHdrDataSpace = Dataspace::UNKNOWN;
2044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002045 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002046 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047 case Dataspace::V0_SCRGB:
2048 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002049 case Dataspace::BT2020:
2050 case Dataspace::BT2020_ITU:
2051 case Dataspace::BT2020_LINEAR:
2052 case Dataspace::DISPLAY_BT2020:
2053 bestDataSpace = Dataspace::DISPLAY_BT2020;
2054 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002055 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002056 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002057 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 case Dataspace::BT2020_PQ:
2059 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002060 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002061 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002062 case Dataspace::BT2020_HLG:
2063 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002064 // When there's mixed PQ content and HLG content, we set the HDR
2065 // data space to be BT2020_PQ and convert HLG to PQ.
2066 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2067 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002068 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002069 break;
2070 default:
2071 break;
2072 }
Romain Guy54f154a2017-10-24 21:40:32 +01002073 }
2074
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002075 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002076}
2077
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002078// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002079void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2080 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002081 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2082 *outMode = ColorMode::NATIVE;
2083 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002084 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002085 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002086 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002087
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002088 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002089 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002090
Peiyong Lindfde5112018-06-05 10:58:41 -07002091 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002092 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002093 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002094 if (isHdr) {
2095 bestDataSpace = hdrDataSpace;
2096 }
2097
Chia-I Wu0d711262018-05-21 15:19:35 -07002098 RenderIntent intent;
2099 switch (mDisplayColorSetting) {
2100 case DisplayColorSetting::MANAGED:
2101 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002102 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002103 break;
2104 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002105 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002106 break;
2107 default: // vendor display color setting
2108 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2109 break;
2110 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002112 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002113}
2114
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002116{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117 bool dirty = !display->getDirtyRegion(false).isEmpty();
2118 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2119 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002120
David Sodmanfa9b2af2017-12-24 13:28:59 -08002121 // If nothing has changed (!dirty), don't recompose.
2122 // If something changed, but we don't currently have any visible layers,
2123 // and didn't when we last did a composition, then skip it this time.
2124 // The second rule does two things:
2125 // - When all layers are removed from a display, we'll emit one black
2126 // frame, then nothing more until we get new layers.
2127 // - When a display is created with a private layer stack, we won't
2128 // emit any black frames until a layer is added to the layer stack.
2129 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002130
Dominik Laskowski075d3172018-05-24 15:50:06 -07002131 const char flagPrefix[] = {'-', '+'};
2132 static_cast<void>(flagPrefix);
2133 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2134 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2135 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002136
David Sodmanfa9b2af2017-12-24 13:28:59 -08002137 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 if (mustRecompose) {
2140 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002141 }
2142}
2143
David Sodmanfa9b2af2017-12-24 13:28:59 -08002144void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002145{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002146 if (!display->isPoweredOn()) {
2147 return;
David Sodman2b406362017-12-15 13:33:47 -08002148 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149
Dominik Laskowski05275f12018-11-01 15:03:24 -07002150 status_t result = display->prepareFrame(getHwComposer(),
2151 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002152 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2153 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002154}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002155
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002157 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002158 ALOGV("doComposition");
2159
David Sodmanfa9b2af2017-12-24 13:28:59 -08002160 if (display->isPoweredOn()) {
2161 // transform the dirty region into this screen's coordinate space
2162 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002163
David Sodmanfa9b2af2017-12-24 13:28:59 -08002164 // repaint the framebuffer (if needed)
2165 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002166
David Sodmanfa9b2af2017-12-24 13:28:59 -08002167 display->dirtyRegion.clear();
2168 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002169 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002171}
2172
David Sodmanfa9b2af2017-12-24 13:28:59 -08002173void SurfaceFlinger::postFrame()
2174{
2175 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002176 const auto display = getDefaultDisplayDeviceLocked();
2177 if (display && getHwComposer().isConnected(*display->getId())) {
2178 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002179 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2180 logFrameStats();
2181 }
2182 }
2183}
2184
2185void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186{
Mathias Agopian841cde52012-03-01 15:44:37 -08002187 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002188 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002189
David Sodmanfa9b2af2017-12-24 13:28:59 -08002190 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002191
David Sodmanfa9b2af2017-12-24 13:28:59 -08002192 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002193 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002194 if (displayId) {
2195 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002196 }
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002197 display->onSwapBuffersCompleted();
2198 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002199 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002200 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002201
Chia-I Wu7b549592017-11-15 09:14:57 -08002202 // The layer buffer from the previous frame (if any) is released
2203 // by HWC only when the release fence from this frame (if any) is
2204 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002205 if (displayId && layer->hasHwcLayer(*displayId)) {
2206 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2207 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002208 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002209
2210 // If the layer was client composited in the previous frame, we
2211 // need to merge with the previous client target acquire fence.
2212 // Since we do not track that, always merge with the current
2213 // client target acquire fence when it is available, even though
2214 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002215 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002216 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002218 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002219
David Sodman15094112018-10-11 09:39:37 -07002220 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002221 }
Chia-I Wu83806892017-11-16 10:50:20 -08002222
2223 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002224 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002225 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 sp<Fence> presentFence =
2228 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002230 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002231 }
2232 }
2233
Dominik Laskowski075d3172018-05-24 15:50:06 -07002234 if (displayId) {
2235 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002236 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002237 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238}
2239
Mathias Agopian87baae12012-07-31 12:38:26 -07002240void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241{
Mathias Agopian841cde52012-03-01 15:44:37 -08002242 ATRACE_CALL();
2243
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002244 // here we keep a copy of the drawing state (that is the state that's
2245 // going to be overwritten by handleTransactionLocked()) outside of
2246 // mStateLock so that the side-effects of the State assignment
2247 // don't happen with mStateLock held (which can cause deadlocks).
2248 State drawingState(mDrawingState);
2249
Mathias Agopianca4d3602011-05-19 15:38:14 -07002250 Mutex::Autolock _l(mStateLock);
2251 const nsecs_t now = systemTime();
2252 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253
Mathias Agopianca4d3602011-05-19 15:38:14 -07002254 // Here we're guaranteed that some transaction flags are set
2255 // so we can call handleTransactionLocked() unconditionally.
2256 // We call getTransactionFlags(), which will also clear the flags,
2257 // with mStateLock held to guarantee that mCurrentState won't change
2258 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002259
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002260 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002261 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002262 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002263
Mathias Agopianca4d3602011-05-19 15:38:14 -07002264 mLastTransactionTime = systemTime() - now;
2265 mDebugInTransaction = 0;
2266 invalidateHwcGeometry();
2267 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002268}
2269
Lloyd Piqueba04e622017-12-14 17:11:26 -08002270void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2271 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002272 const std::optional<DisplayIdentificationInfo> info =
2273 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002274
Dominik Laskowski075d3172018-05-24 15:50:06 -07002275 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002276 continue;
2277 }
2278
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002281 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002282 mPhysicalDisplayTokens[info->id] = new BBinder();
2283 DisplayDeviceState state;
2284 state.displayId = info->id;
2285 state.isSecure = true; // All physical displays are currently considered secure.
2286 state.displayName = info->name;
2287 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2288 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002289 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002290 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002291 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002292
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2294 if (index >= 0) {
2295 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2296 mInterceptor->saveDisplayDeletion(state.sequenceId);
2297 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002298 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002299 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002300 }
2301
2302 processDisplayChangesLocked();
2303 }
2304
2305 mPendingHotplugEvents.clear();
2306}
2307
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002309 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2310 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2311 const sp<IGraphicBufferProducer>& producer) {
2312 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2313 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002314 creationArgs.isSecure = state.isSecure;
2315 creationArgs.displaySurface = dispSurface;
2316 creationArgs.hasWideColorGamut = false;
2317 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318
Dominik Laskowski075d3172018-05-24 15:50:06 -07002319 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2320 creationArgs.isPrimary = isInternalDisplay;
2321
2322 if (useColorManagement && displayId) {
2323 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002325 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002326 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328
Dominik Laskowski7e045462018-05-30 13:02:02 -07002329 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002331 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332 }
tangrobin6753a022018-08-10 10:58:54 +08002333 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 if (displayId) {
2336 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002337 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002339 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340
Lloyd Pique90c115d2018-09-18 21:39:42 -07002341 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002343 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344
Alec Mouri05874642018-11-14 22:34:02 +00002345 /*
2346 * Create our display's surface
2347 */
2348 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
2349 renderSurface->setCritical(isInternalDisplay);
2350 renderSurface->setAsync(state.isVirtual());
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002351 renderSurface->setNativeWindow(nativeWindow.get());
Alec Mouri05874642018-11-14 22:34:02 +00002352 creationArgs.renderSurface = std::move(renderSurface);
2353
Lloyd Pique99d3da52018-01-22 17:48:03 -08002354 // Make sure that composition can never be stalled by a virtual display
2355 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002356 // in two places:
2357 // * Here, in case the display is composed entirely by HWC.
2358 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2359 // window's swap interval in eglMakeCurrent, so they'll override the
2360 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002361 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2363 }
2364
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 creationArgs.displayInstallOrientation =
2366 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002367
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370
Lloyd Pique90c115d2018-09-18 21:39:42 -07002371 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372
2373 if (maxFrameBufferAcquiredBuffers >= 3) {
2374 nativeWindowSurface->preallocateBuffers();
2375 }
2376
2377 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002381 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 if (!state.isVirtual()) {
2386 LOG_ALWAYS_FATAL_IF(!displayId);
2387 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002388 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002390 display->setLayerStack(state.layerStack);
2391 display->setProjection(state.orientation, state.viewport, state.frame);
2392 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002394 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002395}
2396
Lloyd Pique347200f2017-12-14 17:00:15 -08002397void SurfaceFlinger::processDisplayChangesLocked() {
2398 // here we take advantage of Vector's copy-on-write semantics to
2399 // improve performance by skipping the transaction entirely when
2400 // know that the lists are identical
2401 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2402 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2403 if (!curr.isIdenticalTo(draw)) {
2404 mVisibleRegionsDirty = true;
2405 const size_t cc = curr.size();
2406 size_t dc = draw.size();
2407
2408 // find the displays that were removed
2409 // (ie: in drawing state but not in current state)
2410 // also handle displays that changed
2411 // (ie: displays that are in both lists)
2412 for (size_t i = 0; i < dc;) {
2413 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2414 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 // Save display IDs before disconnecting.
2416 const auto internalDisplayId = getInternalDisplayId();
2417 const auto externalDisplayId = getExternalDisplayId();
2418
Lloyd Pique347200f2017-12-14 17:00:15 -08002419 // in drawing state but not in current state
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002420 // Call makeCurrent() on the primary display so we can
2421 // be sure that nothing associated with this display
2422 // is current.
2423 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2424 defaultDisplay->makeCurrent();
2425 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002426 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2427 display->disconnect(getHwComposer());
2428 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002430 if (mUseScheduler) {
2431 mScheduler->hotplugReceived(mAppConnectionHandle,
2432 EventThread::DisplayType::Primary, false);
2433 } else {
2434 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2435 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002437 if (mUseScheduler) {
2438 mScheduler->hotplugReceived(mAppConnectionHandle,
2439 EventThread::DisplayType::External, false);
2440 } else {
2441 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2442 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002443 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002444 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 } else {
2446 // this display is in both lists. see if something changed.
2447 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2450 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2451 if (state_binder != draw_binder) {
2452 // changing the surface is like destroying and
2453 // recreating the DisplayDevice, so we just remove it
2454 // from the drawing state, so that it get re-added
2455 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002456 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2457 display->disconnect(getHwComposer());
2458 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002459 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002460 mDrawingState.displays.removeItemsAt(i);
2461 dc--;
2462 // at this point we must loop to the next item
2463 continue;
2464 }
2465
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002469 }
2470 if ((state.orientation != draw[i].orientation) ||
2471 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002472 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002473 }
2474 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002476 }
2477 }
2478 }
2479 ++i;
2480 }
2481
2482 // find displays that were added
2483 // (ie: in current state but not in drawing state)
2484 for (size_t i = 0; i < cc; i++) {
2485 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2486 const DisplayDeviceState& state(curr[i]);
2487
2488 sp<DisplaySurface> dispSurface;
2489 sp<IGraphicBufferProducer> producer;
2490 sp<IGraphicBufferProducer> bqProducer;
2491 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002492 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002495 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 // Virtual displays without a surface are dormant:
2497 // they have external state (layer stack, projection,
2498 // etc.) but no internal state (i.e. a DisplayDevice).
2499 if (state.surface != nullptr) {
2500 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 int width = 0;
2503 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2504 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2505 int height = 0;
2506 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2507 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2508 int intFormat = 0;
2509 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2510 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002511 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002512
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 displayId =
2514 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 }
2516
2517 // TODO: Plumb requested format back up to consumer
2518
2519 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 bqProducer, bqConsumer,
2522 state.displayName);
2523
2524 dispSurface = vds;
2525 producer = vds;
2526 }
2527 } else {
2528 ALOGE_IF(state.surface != nullptr,
2529 "adding a supported display, but rendering "
2530 "surface is provided (%p), ignoring it",
2531 state.surface.get());
2532
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 displayId = state.displayId;
2534 LOG_ALWAYS_FATAL_IF(!displayId);
2535 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002536 producer = bqProducer;
2537 }
2538
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002542 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002543 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002544 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 LOG_ALWAYS_FATAL_IF(!displayId);
2546
2547 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002548 if (mUseScheduler) {
2549 mScheduler->hotplugReceived(mAppConnectionHandle,
2550 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002551 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002552 } else {
2553 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2554 true);
2555 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002557 if (mUseScheduler) {
2558 mScheduler->hotplugReceived(mAppConnectionHandle,
2559 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002560 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002561 } else {
2562 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2563 true);
2564 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002565 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002566 }
2567 }
2568 }
2569 }
2570 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002571
2572 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002573}
2574
Mathias Agopian87baae12012-07-31 12:38:26 -07002575void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002576{
Dan Stoza7dde5992015-05-22 09:51:44 -07002577 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002578 mCurrentState.traverseInZOrder([](Layer* layer) {
2579 layer->notifyAvailableFrames();
2580 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002581
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 /*
2583 * Traversal of the children
2584 * (perform the transaction for each of them if needed)
2585 */
2586
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002588 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002590 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591
2592 const uint32_t flags = layer->doTransaction(0);
2593 if (flags & Layer::eVisibleRegion)
2594 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002595 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 }
2597
2598 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002599 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 */
2601
Mathias Agopiane57f2922012-08-09 16:29:12 -07002602 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002603 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002604 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002605 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002607 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002608 // The transform hint might have changed for some layers
2609 // (either because a display has changed, or because a layer
2610 // as changed).
2611 //
2612 // Walk through all the layers in currentLayers,
2613 // and update their transform hint.
2614 //
2615 // If a layer is visible only on a single display, then that
2616 // display is used to calculate the hint, otherwise we use the
2617 // default display.
2618 //
2619 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2620 // the hint is set before we acquire a buffer from the surface texture.
2621 //
2622 // NOTE: layer transactions have taken place already, so we use their
2623 // drawing state. However, SurfaceFlinger's own transaction has not
2624 // happened yet, so we must use the current state layer list
2625 // (soon to become the drawing state list).
2626 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002627 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002628 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002629 bool first = true;
2630 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002631 // NOTE: we rely on the fact that layers are sorted by
2632 // layerStack first (so we don't have to traverse the list
2633 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002635 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002636 currentlayerStack = layerStack;
2637 // figure out if this layerstack is mirrored
2638 // (more than one display) if so, pick the default display,
2639 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002640 hintDisplay = nullptr;
2641 for (const auto& [token, display] : mDisplays) {
2642 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2643 if (hintDisplay) {
2644 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002645 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002646 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002647 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002648 }
2649 }
2650 }
2651 }
Chet Haase91d25932013-04-11 15:24:55 -07002652
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002653 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002654 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2655 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002656
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002657 // could be null when this layer is using a layerStack
2658 // that is not visible on any display. Also can occur at
2659 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002660 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002661 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002662
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002663 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002664 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 if (hintDisplay) {
2666 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002667 }
Robert Carr2047fae2016-11-28 14:09:09 -08002668
2669 first = false;
2670 });
Mathias Agopian84300952012-11-21 16:02:13 -08002671 }
2672
2673
Mathias Agopian3559b072012-08-15 13:46:03 -07002674 /*
2675 * Perform our own transaction if needed
2676 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677
2678 if (mLayersAdded) {
2679 mLayersAdded = false;
2680 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002681 mVisibleRegionsDirty = true;
2682 }
2683
2684 // some layers might have been removed, so
2685 // we need to update the regions they're exposing.
2686 if (mLayersRemoved) {
2687 mLayersRemoved = false;
2688 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002689 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002691 // this layer is not visible anymore
2692 // TODO: we could traverse the tree from front to back and
2693 // compute the actual visible region
2694 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 Region visibleReg;
2696 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002697 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002698 }
Robert Carr2047fae2016-11-28 14:09:09 -08002699 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 }
2701
2702 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002703
2704 updateCursorAsync();
2705}
2706
2707void SurfaceFlinger::updateCursorAsync()
2708{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002710 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002711 continue;
2712 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2715 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002716 }
2717 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718}
2719
2720void SurfaceFlinger::commitTransaction()
2721{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002722 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002723 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724 for (const auto& l : mLayersPendingRemoval) {
2725 recordBufferingStats(l->getName().string(),
2726 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002727
2728 // We need to release the HWC layers when the Layer is removed
2729 // from the current state otherwise the HWC layer just continues
2730 // showing at its last configured state until we eventually
2731 // abandon the buffer queue.
2732 if (l->isRemovedFromCurrentState()) {
2733 l->destroyAllHwcLayers();
Robert Carr3aee9892018-11-07 12:53:41 -08002734 // destroyAllHwcLayers traverses to children, but releasePendingBuffer
2735 // doesn't in other scenarios. So we have to traverse explicitly here.
2736 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
2737 child->releasePendingBuffer(systemTime());
2738 });
Robert Carr2e102c92018-10-23 12:11:15 -07002739 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002740 }
2741 mLayersPendingRemoval.clear();
2742 }
2743
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002744 // If this transaction is part of a window animation then the next frame
2745 // we composite should be considered an animation as well.
2746 mAnimCompositionPending = mAnimTransactionPending;
2747
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002749 // clear the "changed" flags in current state
2750 mCurrentState.colorMatrixChanged = false;
2751
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 mDrawingState.traverseInZOrder([](Layer* layer) {
2753 layer->commitChildList();
2754 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002755 mTransactionPending = false;
2756 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002757 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758}
2759
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2761 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002762 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002764
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 Region aboveOpaqueLayers;
2766 Region aboveCoveredLayers;
2767 Region dirty;
2768
Mathias Agopian87baae12012-07-31 12:38:26 -07002769 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770
Robert Carr2047fae2016-11-28 14:09:09 -08002771 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002773 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774
Jesse Hall01e29052013-02-19 16:13:35 -08002775 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002776 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002777 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002778 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002779
Mathias Agopianab028732010-03-16 16:41:46 -07002780 /*
2781 * opaqueRegion: area of a surface that is fully opaque.
2782 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002784
2785 /*
2786 * visibleRegion: area of a surface that is visible on screen
2787 * and not fully transparent. This is essentially the layer's
2788 * footprint minus the opaque regions above it.
2789 * Areas covered by a translucent surface are considered visible.
2790 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002792
2793 /*
2794 * coveredRegion: area of a surface that is covered by all
2795 * visible regions above it (which includes the translucent areas).
2796 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002798
Jesse Halla8026d22012-09-25 13:25:04 -07002799 /*
2800 * transparentRegion: area of a surface that is hinted to be completely
2801 * transparent. This is only used to tell when the layer has no visible
2802 * non-transparent regions and can be removed from the layer list. It
2803 * does not affect the visibleRegion of this layer or any layers
2804 * beneath it. The hint may not be correct if apps don't respect the
2805 * SurfaceView restrictions (which, sadly, some don't).
2806 */
2807 Region transparentRegion;
2808
Mathias Agopianab028732010-03-16 16:41:46 -07002809
2810 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002811 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002812 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002813 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002815 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002816 if (!visibleRegion.isEmpty()) {
2817 // Remove the transparent area from the visible region
2818 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002819 if (tr.preserveRects()) {
2820 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002821 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002822 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002823 // transformation too complex, can't do the
2824 // transparent region optimization.
2825 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826 }
Mathias Agopianab028732010-03-16 16:41:46 -07002827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
Mathias Agopianab028732010-03-16 16:41:46 -07002829 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002830 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002831 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002832 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002833 // the opaque region is the layer's footprint
2834 opaqueRegion = visibleRegion;
2835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 }
2837 }
2838
Robert Carre5f4f692018-01-12 13:12:28 -08002839 if (visibleRegion.isEmpty()) {
2840 layer->clearVisibilityRegions();
2841 return;
2842 }
2843
Mathias Agopianab028732010-03-16 16:41:46 -07002844 // Clip the covered region to the visible region
2845 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2846
2847 // Update aboveCoveredLayers for next (lower) layer
2848 aboveCoveredLayers.orSelf(visibleRegion);
2849
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 // subtract the opaque region covered by the layers above us
2851 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852
2853 // compute this layer's dirty region
2854 if (layer->contentDirty) {
2855 // we need to invalidate the whole region
2856 dirty = visibleRegion;
2857 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 layer->contentDirty = false;
2860 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002861 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002862 * the exposed region consists of two components:
2863 * 1) what's VISIBLE now and was COVERED before
2864 * 2) what's EXPOSED now less what was EXPOSED before
2865 *
2866 * note that (1) is conservative, we start with the whole
2867 * visible region but only keep what used to be covered by
2868 * something -- which mean it may have been exposed.
2869 *
2870 * (2) handles areas that were not covered by anything but got
2871 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002872 */
Mathias Agopianab028732010-03-16 16:41:46 -07002873 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002874 const Region oldVisibleRegion = layer->visibleRegion;
2875 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002876 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2877 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 }
2879 dirty.subtractSelf(aboveOpaqueLayers);
2880
2881 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002882 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883
Mathias Agopianab028732010-03-16 16:41:46 -07002884 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002886
Jesse Halla8026d22012-09-25 13:25:04 -07002887 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 layer->setVisibleRegion(visibleRegion);
2889 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002890 layer->setVisibleNonTransparentRegion(
2891 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002892 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Mathias Agopian87baae12012-07-31 12:38:26 -07002894 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895}
2896
Chia-I Wuab0c3192017-08-01 11:29:00 -07002897void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002898 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2900 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002901 }
2902 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002903}
2904
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 ALOGV("handlePageFlip");
2908
Brian Andersond6927fb2016-07-23 23:37:30 -07002909 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910
Mathias Agopian4fec8732012-06-29 14:12:52 -07002911 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002912 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002913 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002914
2915 // Store the set of layers that need updates. This set must not change as
2916 // buffers are being latched, as this could result in a deadlock.
2917 // Example: Two producers share the same command stream and:
2918 // 1.) Layer 0 is latched
2919 // 2.) Layer 0 gets a new frame
2920 // 2.) Layer 1 gets a new frame
2921 // 3.) Layer 1 is latched.
2922 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2923 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002924 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002925 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002926 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002927 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2928 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002929 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002930 } else {
2931 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002933 } else {
2934 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 }
Robert Carr2047fae2016-11-28 14:09:09 -08002936 });
2937
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002939 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002940 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002941 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002942 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002943 newDataLatched = true;
2944 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002945 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002946
Alec Mouri86770e52018-09-24 22:40:58 +00002947 // Clear the renderengine fence here...
2948 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2949 // clear instead of sp::clear.
2950 getBE().flushFence = Fence::NO_FENCE;
2951
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002952 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002953
2954 // If we will need to wake up at some time in the future to deal with a
2955 // queued frame that shouldn't be displayed during this vsync period, wake
2956 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002957 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002958 signalLayerUpdate();
2959 }
2960
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002961 // enter boot animation on first buffer latch
2962 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2963 ALOGI("Enter boot animation");
2964 mBootStage = BootStage::BOOTANIMATION;
2965 }
2966
Dan Stoza6b9454d2014-11-07 16:00:59 -08002967 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002968 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969}
2970
Mathias Agopianad456f92011-01-13 17:53:01 -08002971void SurfaceFlinger::invalidateHwcGeometry()
2972{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002974}
2975
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002976void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002978 // We only need to actually compose the display if:
2979 // 1) It is being handled by hardware composer, which may need this to
2980 // keep its virtual display state machine in sync, or
2981 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07002982 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002984 return;
2985 }
2986
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002988 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002989
2990 // swap buffers (presentation)
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002991 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992}
2993
Alec Mouri8d4f90a2018-11-14 22:33:24 +00002994bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002996
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002997 const Region bounds(display->bounds());
2998 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002999 const auto displayId = display->getId();
3000 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003001 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003002
Peiyong Lind3788632018-09-18 16:01:31 -07003003 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003004 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003005 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003006
Dan Stoza9e56aa02015-11-02 13:00:03 -08003007 if (hasClientComposition) {
3008 ALOGV("hasClientComposition");
3009
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003010 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003011 if (display->hasWideColorGamut()) {
3012 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003013 }
3014 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003015 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003016 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003017
Dominik Laskowski7e045462018-05-30 13:02:02 -07003018 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003019 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3020 HWC2::Capability::SkipClientColorTransform);
3021
Peiyong Lind3788632018-09-18 16:01:31 -07003022 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003023 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3024 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003025 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003026 }
3027
Chia-I Wud49d6692018-06-27 07:17:41 +08003028 // The current enhanced saturation matrix is designed to enhance Display P3,
3029 // thus we only apply this matrix when the render intent is not colorimetric
3030 // and the output color space is Display P3.
3031 needsEnhancedColorMatrix =
3032 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3033 outputDataspace == Dataspace::DISPLAY_P3);
3034 if (needsEnhancedColorMatrix) {
3035 colorMatrix *= mEnhancedSaturationMatrix;
3036 }
3037
Alec Mouri8d4f90a2018-11-14 22:33:24 +00003038 if (!display->makeCurrent()) {
3039 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
3040 display->getDisplayName().c_str());
3041 getRenderEngine().resetCurrentSurface();
3042
3043 // |mStateLock| not needed as we are on the main thread
3044 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3045 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3046 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3047 }
3048 return false;
3049 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003050
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003051 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003053 // when using overlays, we assume a fully transparent framebuffer
3054 // NOTE: we could reduce how much we need to clear, for instance
3055 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003056 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003057 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003058 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003059 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003060 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003061 // we're left with the letterbox region
3062 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003063 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003064
3065 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003066 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003067
Mathias Agopianb9494d52012-04-18 02:28:45 -07003068 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003069 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003070 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003071 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003072 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003073 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003075 const Rect& bounds = display->getBounds();
3076 const Rect& scissor = display->getScissor();
3077 if (scissor != bounds) {
3078 // scissor doesn't match the screen's dimensions, so we
3079 // need to clear everything outside of it and enable
3080 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003081
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003082 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003083 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003084 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003085 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003086
Mathias Agopian85d751c2012-08-29 16:59:24 -07003087 /*
3088 * and then, render the layers targeted at the framebuffer
3089 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003090
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003092 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003094 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003095 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003096 displayTransform.transform(layer->visibleRegion)));
3097 ALOGV("Layer: %s", layer->getName().string());
3098 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003100 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 case HWC2::Composition::Cursor:
3102 case HWC2::Composition::Device:
3103 case HWC2::Composition::Sideband:
3104 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003105 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003106 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003107 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003108 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3109 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003110 // never clear the very first layer since we're
3111 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003112 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003113 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003114 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003115 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003116 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003117 if (layer->hasColorTransform()) {
3118 mat4 tmpMatrix;
3119 if (applyColorMatrix) {
3120 tmpMatrix = mDrawingState.colorMatrix;
3121 }
3122 tmpMatrix *= layer->getColorTransform();
3123 if (needsEnhancedColorMatrix) {
3124 tmpMatrix *= mEnhancedSaturationMatrix;
3125 }
3126 getRenderEngine().setColorTransform(tmpMatrix);
3127 } else {
3128 getRenderEngine().setColorTransform(colorMatrix);
3129 }
David Sodmanc1498e62018-09-12 14:36:26 -07003130 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003131 break;
3132 }
3133 default:
3134 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003135 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003136 } else {
3137 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003138 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003139 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003140 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003141
Alec Mouri8d4f90a2018-11-14 22:33:24 +00003142 // Clear color transform matrix at the end of the frame.
3143 getRenderEngine().setColorTransform(mat4());
3144
3145 // disable scissor at the end of the frame
3146 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003147 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148}
3149
Chia-I Wu28e3a252018-09-07 12:05:02 -07003150void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003151 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003152 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153}
3154
Dan Stoza7d89d062015-04-30 13:29:25 -07003155status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003156 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003157 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 const sp<Layer>& lbc,
3159 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003160{
Dan Stoza7d89d062015-04-30 13:29:25 -07003161 // add this layer to the current state list
3162 {
3163 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003164 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003165 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3166 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003167 return NO_MEMORY;
3168 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003169 if (parent == nullptr) {
3170 mCurrentState.layersSortedByZ.add(lbc);
3171 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003172 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003173 ALOGE("addClientLayer called with a removed parent");
3174 return NAME_NOT_FOUND;
3175 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 parent->addChild(lbc);
3177 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003178
Yiwei Zhang243b3782018-05-15 17:40:04 -07003179 if (gbc != nullptr) {
3180 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3181 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3182 mMaxGraphicBufferProducerListSize,
3183 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3184 mGraphicBufferProducerList.size(),
3185 mMaxGraphicBufferProducerListSize, mNumLayers);
3186 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003188 }
3189
Mathias Agopian96f08192010-06-02 23:28:45 -07003190 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003191 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003192
Dan Stoza7d89d062015-04-30 13:29:25 -07003193 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003194}
3195
Robert Carr8d2711b2018-11-14 16:36:18 -08003196status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003197 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003198 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003199}
Robert Carr7f9b8992017-03-10 11:08:39 -08003200
Robert Carr8d2711b2018-11-14 16:36:18 -08003201status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003203 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003204 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003205 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003206 } else {
3207 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003208 }
3209
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003210 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003211
3212 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003213 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214}
3215
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003216uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003217 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003218}
3219
Mathias Agopian3f844832013-08-07 21:24:32 -07003220uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003221 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222}
3223
Mathias Agopian3f844832013-08-07 21:24:32 -07003224uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003225 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003226}
3227
3228uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003229 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003230 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003231 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003233 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 }
3235 return old;
3236}
3237
chaviwca27f252018-02-06 16:46:39 -08003238bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3239 for (const ComposerState& state : states) {
3240 // Here we need to check that the interface we're given is indeed
3241 // one of our own. A malicious client could give us a nullptr
3242 // IInterface, or one of its own or even one of our own but a
3243 // different type. All these situations would cause us to crash.
3244 if (state.client == nullptr) {
3245 return true;
3246 }
3247
3248 sp<IBinder> binder = IInterface::asBinder(state.client);
3249 if (binder == nullptr) {
3250 return true;
3251 }
3252
3253 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3254 return true;
3255 }
3256 }
3257 return false;
3258}
3259
Mathias Agopian8b33f032012-07-24 20:43:54 -07003260void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003261 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003262 const Vector<DisplayState>& displays,
3263 uint32_t flags)
3264{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003265 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003266 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003267 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268
chaviwca27f252018-02-06 16:46:39 -08003269 if (containsAnyInvalidClientState(states)) {
3270 return;
3271 }
3272
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003273 if (flags & eAnimation) {
3274 // For window updates that are part of an animation we must wait for
3275 // previous animation "frames" to be handled.
3276 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003277 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003278 if (CC_UNLIKELY(err != NO_ERROR)) {
3279 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003280 // caller after a few seconds.
3281 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3282 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003283 mAnimTransactionPending = false;
3284 break;
3285 }
3286 }
3287 }
3288
chaviwca27f252018-02-06 16:46:39 -08003289 for (const DisplayState& display : displays) {
3290 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003291 }
3292
Marissa Walle2ffb422018-10-12 11:33:52 -07003293 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003294 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003295 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003296 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003297 // If the state doesn't require a traversal and there are callbacks, send them now
3298 if (!(clientStateFlags & eTraversalNeeded)) {
3299 mTransactionCompletedThread.sendCallbacks();
3300 }
3301 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003302
3303 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3304 // as destroyed should only occur after setting all other states. This is to allow for a
3305 // child re-parent to happen before marking its original parent as destroyed (which would
3306 // then mark the child as destroyed).
3307 for (const ComposerState& state : states) {
3308 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003309 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003310
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003311 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3312 // anyway. This can be used as a flush mechanism for previous async transactions.
3313 // Empty animation transaction can be used to simulate back-pressure, so also force a
3314 // transaction for empty animation transactions.
3315 if (transactionFlags == 0 &&
3316 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003317 transactionFlags = eTransactionNeeded;
3318 }
3319
Mathias Agopian386aa982011-11-07 21:58:03 -08003320 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003321 if (mInterceptor->isEnabled()) {
3322 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003323 }
Irvel468051e2016-06-13 16:44:44 -07003324
Mathias Agopian386aa982011-11-07 21:58:03 -08003325 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003326 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3327 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003328 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003329
3330 // if this is a synchronous transaction, wait for it to take effect
3331 // before returning.
3332 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003333 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003334 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003335 if (flags & eAnimation) {
3336 mAnimTransactionPending = true;
3337 }
3338 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003339 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3340 if (CC_UNLIKELY(err != NO_ERROR)) {
3341 // just in case something goes wrong in SF, return to the
3342 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3344 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003345 break;
3346 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348 }
3349}
3350
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003351uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3352 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3353 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003354
Mathias Agopiane57f2922012-08-09 16:29:12 -07003355 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003356 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3357
3358 const uint32_t what = s.what;
3359 if (what & DisplayState::eSurfaceChanged) {
3360 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3361 state.surface = s.surface;
3362 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003363 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003364 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003365 if (what & DisplayState::eLayerStackChanged) {
3366 if (state.layerStack != s.layerStack) {
3367 state.layerStack = s.layerStack;
3368 flags |= eDisplayTransactionNeeded;
3369 }
3370 }
3371 if (what & DisplayState::eDisplayProjectionChanged) {
3372 if (state.orientation != s.orientation) {
3373 state.orientation = s.orientation;
3374 flags |= eDisplayTransactionNeeded;
3375 }
3376 if (state.frame != s.frame) {
3377 state.frame = s.frame;
3378 flags |= eDisplayTransactionNeeded;
3379 }
3380 if (state.viewport != s.viewport) {
3381 state.viewport = s.viewport;
3382 flags |= eDisplayTransactionNeeded;
3383 }
3384 }
3385 if (what & DisplayState::eDisplaySizeChanged) {
3386 if (state.width != s.width) {
3387 state.width = s.width;
3388 flags |= eDisplayTransactionNeeded;
3389 }
3390 if (state.height != s.height) {
3391 state.height = s.height;
3392 flags |= eDisplayTransactionNeeded;
3393 }
3394 }
3395
Mathias Agopiane57f2922012-08-09 16:29:12 -07003396 return flags;
3397}
3398
Robert Carrd4ae7f32018-06-07 16:10:57 -07003399bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3400 IPCThreadState* ipc = IPCThreadState::self();
3401 const int pid = ipc->getCallingPid();
3402 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003403 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003404 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003405 return false;
3406 }
3407 return true;
3408}
3409
chaviwca27f252018-02-06 16:46:39 -08003410uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3411 const layer_state_t& s = composerState.state;
3412 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3413
Mathias Agopian13127d82013-03-05 17:47:11 -08003414 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003415 if (layer == nullptr) {
3416 return 0;
3417 }
3418
chaviw8b3871a2017-11-01 17:41:01 -07003419 uint32_t flags = 0;
3420
3421 const uint32_t what = s.what;
3422 bool geometryAppliesWithResize =
3423 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003424
3425 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3426 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003427 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003428 layer->pushPendingState();
3429 }
3430
chaviw8b3871a2017-11-01 17:41:01 -07003431 if (what & layer_state_t::ePositionChanged) {
3432 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3433 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 }
3436 if (what & layer_state_t::eLayerChanged) {
3437 // NOTE: index needs to be calculated before we update the state
3438 const auto& p = layer->getParent();
3439 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003440 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003441 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003442 mCurrentState.layersSortedByZ.removeAt(idx);
3443 mCurrentState.layersSortedByZ.add(layer);
3444 // we need traversal (state changed)
3445 // AND transaction (list changed)
3446 flags |= eTransactionNeeded|eTraversalNeeded;
3447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 } else {
3449 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003450 flags |= eTransactionNeeded|eTraversalNeeded;
3451 }
3452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 }
3454 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003455 // NOTE: index needs to be calculated before we update the state
3456 const auto& p = layer->getParent();
3457 if (p == nullptr) {
3458 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3459 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3460 mCurrentState.layersSortedByZ.removeAt(idx);
3461 mCurrentState.layersSortedByZ.add(layer);
3462 // we need traversal (state changed)
3463 // AND transaction (list changed)
3464 flags |= eTransactionNeeded|eTraversalNeeded;
3465 }
3466 } else {
3467 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3468 flags |= eTransactionNeeded|eTraversalNeeded;
3469 }
chaviw8b3871a2017-11-01 17:41:01 -07003470 }
3471 }
3472 if (what & layer_state_t::eSizeChanged) {
3473 if (layer->setSize(s.w, s.h)) {
3474 flags |= eTraversalNeeded;
3475 }
3476 }
3477 if (what & layer_state_t::eAlphaChanged) {
3478 if (layer->setAlpha(s.alpha))
3479 flags |= eTraversalNeeded;
3480 }
3481 if (what & layer_state_t::eColorChanged) {
3482 if (layer->setColor(s.color))
3483 flags |= eTraversalNeeded;
3484 }
Peiyong Lind3788632018-09-18 16:01:31 -07003485 if (what & layer_state_t::eColorTransformChanged) {
3486 if (layer->setColorTransform(s.colorTransform)) {
3487 flags |= eTraversalNeeded;
3488 }
3489 }
chaviw8b3871a2017-11-01 17:41:01 -07003490 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003491 // TODO: b/109894387
3492 //
3493 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3494 // rotation. To see the problem observe that if we have a square parent, and a child
3495 // of the same size, then we rotate the child 45 degrees around it's center, the child
3496 // must now be cropped to a non rectangular 8 sided region.
3497 //
3498 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3499 // private API, and the WindowManager only uses rotation in one case, which is on a top
3500 // level layer in which cropping is not an issue.
3501 //
3502 // However given that abuse of rotation matrices could lead to surfaces extending outside
3503 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3504 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3505 // transformations.
3506 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003507 flags |= eTraversalNeeded;
3508 }
3509 if (what & layer_state_t::eTransparentRegionChanged) {
3510 if (layer->setTransparentRegionHint(s.transparentRegion))
3511 flags |= eTraversalNeeded;
3512 }
3513 if (what & layer_state_t::eFlagsChanged) {
3514 if (layer->setFlags(s.flags, s.mask))
3515 flags |= eTraversalNeeded;
3516 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003517 if (what & layer_state_t::eCropChanged_legacy) {
3518 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003519 flags |= eTraversalNeeded;
3520 }
chaviw8b3871a2017-11-01 17:41:01 -07003521 if (what & layer_state_t::eLayerStackChanged) {
3522 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3523 // We only allow setting layer stacks for top level layers,
3524 // everything else inherits layer stack from its parent.
3525 if (layer->hasParent()) {
3526 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3527 layer->getName().string());
3528 } else if (idx < 0) {
3529 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3530 "that also does not appear in the top level layer list. Something"
3531 " has gone wrong.", layer->getName().string());
3532 } else if (layer->setLayerStack(s.layerStack)) {
3533 mCurrentState.layersSortedByZ.removeAt(idx);
3534 mCurrentState.layersSortedByZ.add(layer);
3535 // we need traversal (state changed)
3536 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003537 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003538 }
3539 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003540 if (what & layer_state_t::eDeferTransaction_legacy) {
3541 if (s.barrierHandle_legacy != nullptr) {
3542 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3543 } else if (s.barrierGbp_legacy != nullptr) {
3544 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (authenticateSurfaceTextureLocked(gbp)) {
3546 const auto& otherLayer =
3547 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003548 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003549 } else {
3550 ALOGE("Attempt to defer transaction to to an"
3551 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003552 }
3553 }
chaviw8b3871a2017-11-01 17:41:01 -07003554 // We don't trigger a traversal here because if no other state is
3555 // changed, we don't want this to cause any more work
3556 }
3557 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003558 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003560 if (!hadParent) {
3561 mCurrentState.layersSortedByZ.remove(layer);
3562 }
chaviw8b3871a2017-11-01 17:41:01 -07003563 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003564 }
chaviw8b3871a2017-11-01 17:41:01 -07003565 }
3566 if (what & layer_state_t::eReparentChildren) {
3567 if (layer->reparentChildren(s.reparentHandle)) {
3568 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003569 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 if (what & layer_state_t::eDetachChildren) {
3572 layer->detachChildren();
3573 }
3574 if (what & layer_state_t::eOverrideScalingModeChanged) {
3575 layer->setOverrideScalingMode(s.overrideScalingMode);
3576 // We don't trigger a traversal here because if no other state is
3577 // changed, we don't want this to cause any more work
3578 }
Marissa Wall61c58622018-07-18 10:12:20 -07003579 if (what & layer_state_t::eTransformChanged) {
3580 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3581 }
3582 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3583 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3584 flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eCropChanged) {
3587 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eBufferChanged) {
3590 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3591 }
3592 if (what & layer_state_t::eAcquireFenceChanged) {
3593 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eDataspaceChanged) {
3596 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3597 }
3598 if (what & layer_state_t::eHdrMetadataChanged) {
3599 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3600 }
3601 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3602 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3603 }
3604 if (what & layer_state_t::eApiChanged) {
3605 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3606 }
3607 if (what & layer_state_t::eSidebandStreamChanged) {
3608 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3609 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003610
3611 std::vector<sp<CallbackHandle>> callbackHandles;
3612 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3613 mTransactionCompletedThread.run();
3614 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3615 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3616 }
3617 }
3618 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3619 // Do not put anything that updates layer state or modifies flags after
3620 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003621 return flags;
3622}
3623
chaviwca27f252018-02-06 16:46:39 -08003624void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3625 const layer_state_t& state = composerState.state;
3626 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3627
3628 sp<Layer> layer(client->getLayerUser(state.surface));
3629 if (layer == nullptr) {
3630 return;
3631 }
3632
chaviwca27f252018-02-06 16:46:39 -08003633 if (state.what & layer_state_t::eDestroySurface) {
3634 removeLayerLocked(mStateLock, layer);
3635 }
3636}
3637
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003639 const String8& name,
3640 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003642 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003643 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003645 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003646 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003647 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003648 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003649 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003650
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003651 status_t result = NO_ERROR;
3652
3653 sp<Layer> layer;
3654
Cody Northropbc755282017-03-31 12:00:08 -06003655 String8 uniqueName = getUniqueLayerName(name);
3656
Mathias Agopian3165cc22012-08-08 19:42:09 -07003657 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003658 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003659 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3660 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003661
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003663 case ISurfaceComposerClient::eFXSurfaceBufferState:
3664 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3665 break;
chaviw13fdc492017-06-27 12:40:18 -07003666 case ISurfaceComposerClient::eFXSurfaceColor:
3667 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003668 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003669 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003671 case ISurfaceComposerClient::eFXSurfaceContainer:
3672 result = createContainerLayer(client,
3673 uniqueName, w, h, flags,
3674 handle, &layer);
3675 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003676 default:
3677 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678 break;
3679 }
3680
Dan Stoza7d89d062015-04-30 13:29:25 -07003681 if (result != NO_ERROR) {
3682 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003684
Chia-I Wuab0c3192017-08-01 11:29:00 -07003685 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3686 // TODO b/64227542
3687 if (windowType == 441731) {
3688 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3689 layer->setPrimaryDisplayOnly();
3690 }
3691
Albert Chaulk479c60c2017-01-27 14:21:34 -05003692 layer->setInfo(windowType, ownerUid);
3693
Robert Carr1f0a16a2016-10-24 16:27:39 -07003694 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003695 if (result != NO_ERROR) {
3696 return result;
3697 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003698 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003699
3700 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003702}
3703
Cody Northropbc755282017-03-31 12:00:08 -06003704String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3705{
3706 bool matchFound = true;
3707 uint32_t dupeCounter = 0;
3708
3709 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3710 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3711
Dan Stoza436ccf32018-06-21 12:10:12 -07003712 // Grab the state lock since we're accessing mCurrentState
3713 Mutex::Autolock lock(mStateLock);
3714
Cody Northropbc755282017-03-31 12:00:08 -06003715 // Loop over layers until we're sure there is no matching name
3716 while (matchFound) {
3717 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003718 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003719 if (layer->getName() == uniqueName) {
3720 matchFound = true;
3721 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3722 }
3723 });
3724 }
3725
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003726 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3727 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003728
3729 return uniqueName;
3730}
3731
Marissa Wallfd668622018-05-10 10:21:13 -07003732status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3733 uint32_t w, uint32_t h, uint32_t flags,
3734 PixelFormat& format, sp<IBinder>* handle,
3735 sp<IGraphicBufferProducer>* gbp,
3736 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003737 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003738 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 case PIXEL_FORMAT_TRANSPARENT:
3740 case PIXEL_FORMAT_TRANSLUCENT:
3741 format = PIXEL_FORMAT_RGBA_8888;
3742 break;
3743 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003744 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745 break;
3746 }
3747
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003748 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003749 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003750 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003752 *handle = layer->getHandle();
3753 *gbp = layer->getProducer();
3754 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003756
Marissa Wallfd668622018-05-10 10:21:13 -07003757 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759}
3760
Marissa Wall61c58622018-07-18 10:12:20 -07003761status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3762 uint32_t w, uint32_t h, uint32_t flags,
3763 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003764 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003765 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003766 *handle = layer->getHandle();
3767 *outLayer = layer;
3768
3769 return NO_ERROR;
3770}
3771
chaviw13fdc492017-06-27 12:40:18 -07003772status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003773 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003774 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003775{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003776 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003777 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003778 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003779}
3780
Robert Carr6b3f6c52018-08-13 13:05:17 -07003781status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3782 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3783 sp<IBinder>* handle, sp<Layer>* outLayer)
3784{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003785 *outLayer =
3786 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003787 *handle = (*outLayer)->getHandle();
3788 return NO_ERROR;
3789}
3790
3791
Mathias Agopianac9fa422013-02-11 16:40:36 -08003792status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793{
Robert Carr9524cb32017-02-13 11:32:32 -08003794 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003795 status_t err = NO_ERROR;
3796 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003797 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003798 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003799 err = removeLayer(l);
3800 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3801 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003802 }
3803 return err;
3804}
3805
Robert Carr2e102c92018-10-23 12:11:15 -07003806void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3807 mLayersPendingRemoval.add(layer);
3808 mLayersRemoved = true;
3809 setTransactionFlags(eTransactionNeeded);
3810}
3811
3812void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003813{
Robert Carr2e102c92018-10-23 12:11:15 -07003814 Mutex::Autolock lock(mStateLock);
3815 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003816}
3817
Mathias Agopianb60314a2012-04-10 22:09:54 -07003818// ---------------------------------------------------------------------------
3819
Andy McFadden13a082e2012-08-24 10:16:42 -07003820void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003821 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003822 if (!displayToken) return;
3823
Jesse Hall01e29052013-02-19 16:13:35 -08003824 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003825 Vector<ComposerState> state;
3826 Vector<DisplayState> displays;
3827 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003828 d.what = DisplayState::eDisplayProjectionChanged |
3829 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003830 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003831 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003832 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003833 d.frame.makeInvalid();
3834 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003835 d.width = 0;
3836 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003837 displays.add(d);
3838 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003839
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003840 const auto display = getDisplayDevice(displayToken);
3841 if (!display) return;
3842
3843 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3844
Dominik Laskowski075d3172018-05-24 15:50:06 -07003845 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003846 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003847 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003848
Brian Andersond0010582017-03-07 13:20:31 -08003849 // Use phase of 0 since phase is not known.
3850 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003851 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3852 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003853}
3854
3855void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003856 // Async since we may be called from the main thread.
3857 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003858}
3859
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003860void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3861 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003862 if (display->isVirtual()) {
3863 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003864 return;
3865 }
3866
Dominik Laskowski075d3172018-05-24 15:50:06 -07003867 const auto displayId = display->getId();
3868 LOG_ALWAYS_FATAL_IF(!displayId);
3869
Dominik Laskowski34157762018-10-31 13:07:19 -07003870 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003871
3872 int currentMode = display->getPowerMode();
3873 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003874 return;
3875 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003876
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003877 display->setPowerMode(mode);
3878
Lloyd Pique4dccc412018-01-22 17:21:36 -08003879 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003880 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003881 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003882 if (idx < 0) {
3883 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3884 return;
3885 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003886 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003887 }
3888
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003889 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003890 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003891 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003892 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003893 if (mUseScheduler) {
3894 mScheduler->onScreenAcquired(mAppConnectionHandle);
3895 } else {
3896 mEventThread->onScreenAcquired();
3897 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003898 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003902 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003903 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003904
3905 struct sched_param param = {0};
3906 param.sched_priority = 1;
3907 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3908 ALOGW("Couldn't set SCHED_FIFO on display on");
3909 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003910 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003911 // Turn off the display
3912 struct sched_param param = {0};
3913 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3914 ALOGW("Couldn't set SCHED_OTHER on display off");
3915 }
3916
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003917 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003918 if (mUseScheduler) {
3919 mScheduler->disableHardwareVsync(true);
3920 } else {
3921 disableHardwareVsync(true); // also cancels any in-progress resync
3922 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003923 if (mUseScheduler) {
3924 mScheduler->onScreenReleased(mAppConnectionHandle);
3925 } else {
3926 mEventThread->onScreenReleased();
3927 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003928 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003929
Dominik Laskowski075d3172018-05-24 15:50:06 -07003930 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003931 mVisibleRegionsDirty = true;
3932 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003933 } else if (mode == HWC_POWER_MODE_DOZE ||
3934 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003935 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003936 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003937 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003938 if (mUseScheduler) {
3939 mScheduler->onScreenAcquired(mAppConnectionHandle);
3940 } else {
3941 mEventThread->onScreenAcquired();
3942 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003943 resyncToHardwareVsync(true);
3944 }
3945 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3946 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003947 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003948 if (mUseScheduler) {
3949 mScheduler->disableHardwareVsync(true);
3950 } else {
3951 disableHardwareVsync(true); // also cancels any in-progress resync
3952 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003953 if (mUseScheduler) {
3954 mScheduler->onScreenReleased(mAppConnectionHandle);
3955 } else {
3956 mEventThread->onScreenReleased();
3957 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003958 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003959 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003960 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003961 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003962 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003963 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003964
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003965 if (display->isPrimary()) {
3966 mTimeStats.setPowerMode(mode);
3967 }
3968
Dominik Laskowski34157762018-10-31 13:07:19 -07003969 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003970}
3971
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003972void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003973 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003974 const auto display = getDisplayDevice(displayToken);
3975 if (!display) {
3976 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3977 displayToken.get());
3978 } else if (display->isVirtual()) {
3979 ALOGW("Attempt to set power mode %d for virtual display", mode);
3980 } else {
3981 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003982 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003983 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003984}
3985
3986// ---------------------------------------------------------------------------
3987
Lloyd Pique755e3192018-01-31 16:46:15 -08003988status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3989 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003991
Mathias Agopianbd115332013-04-18 16:41:04 -07003992 IPCThreadState* ipc = IPCThreadState::self();
3993 const int pid = ipc->getCallingPid();
3994 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003995
Mathias Agopianbd115332013-04-18 16:41:04 -07003996 if ((uid != AID_SHELL) &&
3997 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003998 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003999 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004001 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004002 // (this would indicate SF is stuck, but we want to be able to
4003 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004004 status_t err = mStateLock.timedLock(s2ns(1));
4005 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004006 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004007 result.appendFormat(
4008 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4009 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004010 }
4011
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004012 bool dumpAll = true;
4013 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004014 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004015
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004016 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017 if ((index < numArgs) &&
4018 (args[index] == String16("--list"))) {
4019 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004020 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004021 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022 }
4023
4024 if ((index < numArgs) &&
4025 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004026 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004027 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004028 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004029 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004030
4031 if ((index < numArgs) &&
4032 (args[index] == String16("--latency-clear"))) {
4033 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004034 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004035 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004036 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004037
4038 if ((index < numArgs) &&
4039 (args[index] == String16("--dispsync"))) {
4040 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004041 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004042 dumpAll = false;
4043 }
Dan Stozab90cf072015-03-05 11:05:59 -08004044
4045 if ((index < numArgs) &&
4046 (args[index] == String16("--static-screen"))) {
4047 index++;
4048 dumpStaticScreenStats(result);
4049 dumpAll = false;
4050 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004051
4052 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004053 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004054 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004055 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004056 dumpAll = false;
4057 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004058
4059 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4060 index++;
4061 dumpWideColorInfo(result);
4062 dumpAll = false;
4063 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004064
4065 if ((index < numArgs) &&
4066 (args[index] == String16("--enable-layer-stats"))) {
4067 index++;
4068 mLayerStats.enable();
4069 dumpAll = false;
4070 }
4071
4072 if ((index < numArgs) &&
4073 (args[index] == String16("--disable-layer-stats"))) {
4074 index++;
4075 mLayerStats.disable();
4076 dumpAll = false;
4077 }
4078
4079 if ((index < numArgs) &&
4080 (args[index] == String16("--clear-layer-stats"))) {
4081 index++;
4082 mLayerStats.clear();
4083 dumpAll = false;
4084 }
4085
4086 if ((index < numArgs) &&
4087 (args[index] == String16("--dump-layer-stats"))) {
4088 index++;
4089 mLayerStats.dump(result);
4090 dumpAll = false;
4091 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004092
4093 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004094 (args[index] == String16("--frame-composition"))) {
4095 index++;
4096 dumpFrameCompositionInfo(result);
4097 dumpAll = false;
4098 }
4099
4100 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004101 (args[index] == String16("--display-identification"))) {
4102 index++;
4103 dumpDisplayIdentificationData(result);
4104 dumpAll = false;
4105 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004106
4107 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4108 index++;
4109 mTimeStats.parseArgs(asProto, args, index, result);
4110 dumpAll = false;
4111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004113
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004114 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004115 if (asProto) {
4116 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4117 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4118 } else {
4119 dumpAllLocked(args, index, result);
4120 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004121 }
4122
Mathias Agopian9795c422009-08-26 16:36:26 -07004123 if (locked) {
4124 mStateLock.unlock();
4125 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 }
4127 write(fd, result.string(), result.size());
4128 return NO_ERROR;
4129}
4130
Dan Stozac7014012014-02-14 15:03:43 -08004131void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4132 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004133{
Robert Carr2047fae2016-11-28 14:09:09 -08004134 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004135 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004136 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004137}
4138
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004139void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004140 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141{
4142 String8 name;
4143 if (index < args.size()) {
4144 name = String8(args[index]);
4145 index++;
4146 }
4147
Dominik Laskowski075d3172018-05-24 15:50:06 -07004148 if (const auto displayId = getInternalDisplayId();
4149 displayId && getHwComposer().isConnected(*displayId)) {
4150 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004151 const nsecs_t period = activeConfig->getVsyncPeriod();
4152 result.appendFormat("%" PRId64 "\n", period);
4153 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004154
4155 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004156 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004157 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004158 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004159 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004160 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004161 }
Robert Carr2047fae2016-11-28 14:09:09 -08004162 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163 }
4164}
4165
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004166void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004167 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004168{
4169 String8 name;
4170 if (index < args.size()) {
4171 name = String8(args[index]);
4172 index++;
4173 }
4174
Robert Carr2047fae2016-11-28 14:09:09 -08004175 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004176 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004177 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004178 }
Robert Carr2047fae2016-11-28 14:09:09 -08004179 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004180
Svetoslavd85084b2014-03-20 10:28:31 -07004181 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004182}
4183
Jamie Gennis6547ff42013-07-16 20:12:42 -07004184// This should only be called from the main thread. Otherwise it would need
4185// the lock and should use mCurrentState rather than mDrawingState.
4186void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004187 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004188 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004189 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004190
4191 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4192}
4193
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004194void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004195{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004196 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004197
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004198 if (isLayerTripleBufferingDisabled())
4199 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004200
4201 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004202 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004203 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004204 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004205 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4206 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004207 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004208}
4209
Dan Stozab90cf072015-03-05 11:05:59 -08004210void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4211{
4212 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004213 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4214 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004215 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004216 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004217 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4218 b + 1, bucketTimeSec, percent);
4219 }
David Sodman4a36e932017-11-07 14:29:47 -08004220 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004221 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004222 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004223 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004224 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004225}
4226
Dan Stozae77c7662016-05-13 11:37:28 -07004227void SurfaceFlinger::recordBufferingStats(const char* layerName,
4228 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004229 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4230 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004231 for (const auto& segment : history) {
4232 if (!segment.usedThirdBuffer) {
4233 stats.twoBufferTime += segment.totalTime;
4234 }
4235 if (segment.occupancyAverage < 1.0f) {
4236 stats.doubleBufferedTime += segment.totalTime;
4237 } else if (segment.occupancyAverage < 2.0f) {
4238 stats.tripleBufferedTime += segment.totalTime;
4239 }
4240 ++stats.numSegments;
4241 stats.totalTime += segment.totalTime;
4242 }
4243}
4244
Brian Andersond6927fb2016-07-23 23:37:30 -07004245void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4246 result.appendFormat("Layer frame timestamps:\n");
4247
4248 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4249 const size_t count = currentLayers.size();
4250 for (size_t i=0 ; i<count ; i++) {
4251 currentLayers[i]->dumpFrameEvents(result);
4252 }
4253}
4254
Dan Stozae77c7662016-05-13 11:37:28 -07004255void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4256 result.append("Buffering stats:\n");
4257 result.append(" [Layer name] <Active time> <Two buffer> "
4258 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004259 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004260 typedef std::tuple<std::string, float, float, float> BufferTuple;
4261 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004262 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004263 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004264 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004265 if (stats.numSegments == 0) {
4266 continue;
4267 }
4268 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4269 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4270 stats.totalTime;
4271 float doubleBufferRatio = static_cast<float>(
4272 stats.doubleBufferedTime) / stats.totalTime;
4273 float tripleBufferRatio = static_cast<float>(
4274 stats.tripleBufferedTime) / stats.totalTime;
4275 sorted.insert({activeTime, {name, twoBufferRatio,
4276 doubleBufferRatio, tripleBufferRatio}});
4277 }
4278 for (const auto& sortedPair : sorted) {
4279 float activeTime = sortedPair.first;
4280 const BufferTuple& values = sortedPair.second;
4281 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4282 std::get<0>(values).c_str(), activeTime,
4283 std::get<1>(values), std::get<2>(values),
4284 std::get<3>(values));
4285 }
4286 result.append("\n");
4287}
4288
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004289void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004290 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004291 const auto displayId = display->getId();
4292 if (!displayId) {
4293 continue;
4294 }
4295 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004296 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004297 continue;
4298 }
4299
Dominik Laskowski34157762018-10-31 13:07:19 -07004300 result.appendFormat("Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
Dominik Laskowski075d3172018-05-24 15:50:06 -07004301 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004302 uint8_t port;
4303 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004304 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004305 result.append("no identification data\n");
4306 continue;
4307 }
4308
4309 if (!isEdid(data)) {
4310 result.append("unknown identification data: ");
4311 for (uint8_t byte : data) {
4312 result.appendFormat("%x ", byte);
4313 }
4314 result.append("\n");
4315 continue;
4316 }
4317
4318 const auto edid = parseEdid(data);
4319 if (!edid) {
4320 result.append("invalid EDID: ");
4321 for (uint8_t byte : data) {
4322 result.appendFormat("%x ", byte);
4323 }
4324 result.append("\n");
4325 continue;
4326 }
4327
4328 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4329 result.append(edid->displayName.data(), edid->displayName.length());
4330 result.append("\"\n");
4331 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004332}
4333
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004334void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004335 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4336 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004337 result.appendFormat("DisplayColorSetting: %s\n",
4338 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004339
4340 // TODO: print out if wide-color mode is active or not
4341
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004342 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004343 const auto displayId = display->getId();
4344 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004345 continue;
4346 }
4347
Dominik Laskowski34157762018-10-31 13:07:19 -07004348 result.appendFormat("Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004349 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004350 for (auto&& mode : modes) {
4351 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4352 }
4353
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004354 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004355 result.appendFormat(" Current color mode: %s (%d)\n",
4356 decodeColorMode(currentMode).c_str(), currentMode);
4357 }
4358 result.append("\n");
4359}
4360
David Sodman7e4ae112018-02-09 15:02:28 -08004361void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4362 std::string stringResult;
4363
4364 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004365 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4366 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004367 continue;
4368 }
4369
Dominik Laskowski05275f12018-11-01 15:03:24 -07004370 const auto& compositionInfoList = it->second;
4371 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004372 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4373 for (const auto& compositionInfo : compositionInfoList) {
4374 compositionInfo.dump(stringResult, nullptr);
4375 stringResult += base::StringPrintf("\n");
4376 }
4377 }
4378
4379 result.append(stringResult.c_str());
4380}
4381
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004382LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004383 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004384 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4385 const State& state = useDrawing ? mDrawingState : mCurrentState;
4386 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004387 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004388 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004389 });
4390
4391 return layersProto;
4392}
4393
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004394LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004395 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004396
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004397 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004398 resolution->set_w(display.getWidth());
4399 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004401 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4402 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4403 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004404
Dominik Laskowski075d3172018-05-24 15:50:06 -07004405 const auto displayId = display.getId();
4406 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004407 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004408 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004410 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004411 }
4412 });
4413
4414 return layersProto;
4415}
4416
Mathias Agopian74d211a2013-04-22 16:55:35 +02004417void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4418 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004420 bool colorize = false;
4421 if (index < args.size()
4422 && (args[index] == String16("--color"))) {
4423 colorize = true;
4424 index++;
4425 }
4426
4427 Colorizer colorizer(colorize);
4428
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004429 // figure out if we're stuck somewhere
4430 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004431 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004432 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4433
4434 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004435 * Dump library configuration.
4436 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004437
4438 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004439 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004440 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004441 appendSfConfigString(result);
4442 appendUiConfigString(result);
4443 appendGuiConfigString(result);
4444 result.append("\n");
4445
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004446 result.append("\nDisplay identification data:\n");
4447 dumpDisplayIdentificationData(result);
4448
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004449 result.append("\nWide-Color information:\n");
4450 dumpWideColorInfo(result);
4451
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004452 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004453 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004454 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004455 result.append(SyncFeatures::getInstance().toString());
4456 result.append("\n");
4457
Andy McFadden41d67d72014-04-25 16:58:34 -07004458 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004459 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004460 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004461
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004462 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4463 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004464 if (const auto displayId = getInternalDisplayId();
4465 displayId && getHwComposer().isConnected(*displayId)) {
4466 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski34157762018-10-31 13:07:19 -07004467 result.appendFormat("Display %s: app phase %" PRId64 " ns, "
Dominik Laskowski075d3172018-05-24 15:50:06 -07004468 "sf phase %" PRId64 " ns, "
4469 "early app phase %" PRId64 " ns, "
4470 "early sf phase %" PRId64 " ns, "
4471 "early app gl phase %" PRId64 " ns, "
4472 "early sf gl phase %" PRId64 " ns, "
4473 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dominik Laskowski34157762018-10-31 13:07:19 -07004474 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4475 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
Dominik Laskowski075d3172018-05-24 15:50:06 -07004476 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004477 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004478 result.append("\n");
4479
Dan Stozab90cf072015-03-05 11:05:59 -08004480 // Dump static screen stats
4481 result.append("\n");
4482 dumpStaticScreenStats(result);
4483 result.append("\n");
4484
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004485 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4486
Dan Stozae77c7662016-05-13 11:37:28 -07004487 dumpBufferingStats(result);
4488
Andy McFadden4803b742012-09-24 19:07:20 -07004489 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004490 * Dump the visible layer list
4491 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004492 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004493 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004494 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4495 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004496 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004497
Chia-I Wu2f884132018-09-13 15:17:58 -07004498 {
4499 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4500 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4501 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4502 result.append("\n");
4503 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504
David Sodman7e4ae112018-02-09 15:02:28 -08004505 result.append("\nFrame-Composition information:\n");
4506 dumpFrameCompositionInfo(result);
4507 result.append("\n");
4508
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004510 * Dump Display state
4511 */
4512
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004513 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004514 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004515 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004516 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004517 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004518 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004519 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004520
4521 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004522 * Dump SurfaceFlinger global state
4523 */
4524
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004526 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004528
David Sodmanbc815282017-11-05 18:57:52 -08004529 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004530
Dominik Laskowski075d3172018-05-24 15:50:06 -07004531 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004532 display->undefinedRegion.dump(result, "undefinedRegion");
4533 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4534 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004535 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004536 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004537 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004538 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004539
Dominik Laskowski075d3172018-05-24 15:50:06 -07004540 if (const auto displayId = getInternalDisplayId();
4541 displayId && getHwComposer().isConnected(*displayId)) {
4542 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004543 result.appendFormat(" refresh-rate : %f fps\n"
4544 " x-dpi : %f\n"
4545 " y-dpi : %f\n",
4546 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4547 activeConfig->getDpiY());
4548 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549
Mathias Agopian74d211a2013-04-22 16:55:35 +02004550 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004551 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004552
Ana Krulec98b5b242018-08-10 15:03:23 -07004553 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004554 /*
4555 * VSYNC state
4556 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004557 if (mUseScheduler) {
4558 mScheduler->dump(mAppConnectionHandle, result);
4559 } else {
4560 mEventThread->dump(result);
4561 }
Dan Stozae22aec72016-08-01 13:20:59 -07004562 result.append("\n");
4563
4564 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004565 * Tracing state
4566 */
4567 mTracing.dump(result);
4568 result.append("\n");
4569
4570 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004571 * HWC layer minidump
4572 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004573 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004574 const auto displayId = display->getId();
4575 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004576 continue;
4577 }
4578
Dominik Laskowski34157762018-10-31 13:07:19 -07004579 result.appendFormat("Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004580 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004581 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004582 result.append("\n");
4583 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004584
4585 /*
4586 * Dump HWComposer state
4587 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004588 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004589 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004590 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004591 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004592 result.appendFormat(" h/w composer %s\n",
4593 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004594 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004595
4596 /*
4597 * Dump gralloc state
4598 */
4599 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4600 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004601
4602 /*
4603 * Dump VrFlinger state if in use.
4604 */
4605 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4606 result.append("VrFlinger state:\n");
4607 result.append(mVrFlinger->Dump().c_str());
4608 result.append("\n");
4609 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610}
4611
Dominik Laskowski075d3172018-05-24 15:50:06 -07004612const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004613 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004615 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004616 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004617 }
4618 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004619
Dominik Laskowski34157762018-10-31 13:07:19 -07004620 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004621 static const Vector<sp<Layer>> empty;
4622 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004623}
4624
Keun young Park63f165f2012-08-31 10:53:36 -07004625bool SurfaceFlinger::startDdmConnection()
4626{
4627 void* libddmconnection_dso =
4628 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4629 if (!libddmconnection_dso) {
4630 return false;
4631 }
4632 void (*DdmConnection_start)(const char* name);
4633 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004634 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004635 if (!DdmConnection_start) {
4636 dlclose(libddmconnection_dso);
4637 return false;
4638 }
4639 (*DdmConnection_start)(getServiceName());
4640 return true;
4641}
4642
Chia-I Wu28f320b2018-05-03 11:02:56 -07004643void SurfaceFlinger::updateColorMatrixLocked() {
4644 mat4 colorMatrix;
4645 if (mGlobalSaturationFactor != 1.0f) {
4646 // Rec.709 luma coefficients
4647 float3 luminance{0.213f, 0.715f, 0.072f};
4648 luminance *= 1.0f - mGlobalSaturationFactor;
4649 mat4 saturationMatrix = mat4(
4650 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4651 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4652 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4653 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4654 );
4655 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4656 } else {
4657 colorMatrix = mClientColorMatrix * mDaltonizer();
4658 }
4659
4660 if (mCurrentState.colorMatrix != colorMatrix) {
4661 mCurrentState.colorMatrix = colorMatrix;
4662 mCurrentState.colorMatrixChanged = true;
4663 setTransactionFlags(eTransactionNeeded);
4664 }
4665}
4666
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004667status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004668#pragma clang diagnostic push
4669#pragma clang diagnostic error "-Wswitch-enum"
4670 switch (static_cast<ISurfaceComposerTag>(code)) {
4671 // These methods should at minimum make sure that the client requested
4672 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004673 case BOOT_FINISHED:
4674 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004675 case CREATE_CONNECTION:
4676 case CREATE_DISPLAY:
4677 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004678 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004679 case GET_ACTIVE_COLOR_MODE:
4680 case GET_ANIMATION_FRAME_STATS:
4681 case GET_HDR_CAPABILITIES:
4682 case SET_ACTIVE_CONFIG:
4683 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004684 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004686 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4687 IPCThreadState* ipc = IPCThreadState::self();
4688 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4689 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004690 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691 }
Robert Carr1db73f62016-12-21 12:58:51 -08004692 return OK;
4693 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004695 IPCThreadState* ipc = IPCThreadState::self();
4696 const int pid = ipc->getCallingPid();
4697 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004698 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4699 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004700 return PERMISSION_DENIED;
4701 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004702 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004703 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704 // Used by apps to hook Choreographer to SurfaceFlinger.
4705 case CREATE_DISPLAY_EVENT_CONNECTION:
4706 // The following calls are currently used by clients that do not
4707 // request necessary permissions. However, they do not expose any secret
4708 // information, so it is OK to pass them.
4709 case AUTHENTICATE_SURFACE:
4710 case GET_ACTIVE_CONFIG:
4711 case GET_BUILT_IN_DISPLAY:
4712 case GET_DISPLAY_COLOR_MODES:
4713 case GET_DISPLAY_CONFIGS:
4714 case GET_DISPLAY_STATS:
4715 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4716 // Calling setTransactionState is safe, because you need to have been
4717 // granted a reference to Client* and Handle* to do anything with it.
4718 case SET_TRANSACTION_STATE:
4719 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004720 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004721 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004722 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004723 return OK;
4724 }
4725 case CAPTURE_LAYERS:
4726 case CAPTURE_SCREEN: {
4727 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004728 IPCThreadState* ipc = IPCThreadState::self();
4729 const int pid = ipc->getCallingPid();
4730 const int uid = ipc->getCallingUid();
4731 if ((uid != AID_GRAPHICS) &&
4732 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4733 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4734 return PERMISSION_DENIED;
4735 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004736 return OK;
4737 }
4738 // The following codes are deprecated and should never be allowed to access SF.
4739 case CONNECT_DISPLAY_UNUSED:
4740 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4741 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4742 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004744 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745
4746 // These codes are used for the IBinder protocol to either interrogate the recipient
4747 // side of the transaction for its canonical interface descriptor or to dump its state.
4748 // We let them pass by default.
4749 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4750 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4751 code == IBinder::SYSPROPS_TRANSACTION) {
4752 return OK;
4753 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004754 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004756 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004757 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4758 return OK;
4759 }
4760 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4761 return PERMISSION_DENIED;
4762#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004763}
4764
Ana Krulec13be8ad2018-08-21 02:43:56 +00004765status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4766 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004767 status_t credentialCheck = CheckTransactCodeCredentials(code);
4768 if (credentialCheck != OK) {
4769 return credentialCheck;
4770 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004772 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4773 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004774 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004775 IPCThreadState* ipc = IPCThreadState::self();
4776 const int uid = ipc->getCallingUid();
4777 if (CC_UNLIKELY(uid != AID_SYSTEM
4778 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004779 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004780 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004781 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004782 return PERMISSION_DENIED;
4783 }
4784 int n;
4785 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004786 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004787 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004788 return NO_ERROR;
4789 case 1002: // SHOW_UPDATES
4790 n = data.readInt32();
4791 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004792 invalidateHwcGeometry();
4793 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004794 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004796 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004797 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004798 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004799 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004800 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004801 setTransactionFlags(
4802 eTransactionNeeded|
4803 eDisplayTransactionNeeded|
4804 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004805 return NO_ERROR;
4806 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004807 case 1006:{ // send empty update
4808 signalRefresh();
4809 return NO_ERROR;
4810 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004811 case 1008: // toggle use of hw composer
4812 n = data.readInt32();
4813 mDebugDisableHWC = n ? 1 : 0;
4814 invalidateHwcGeometry();
4815 repaintEverything();
4816 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004817 case 1009: // toggle use of transform hint
4818 n = data.readInt32();
4819 mDebugDisableTransformHint = n ? 1 : 0;
4820 invalidateHwcGeometry();
4821 repaintEverything();
4822 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004823 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004824 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 reply->writeInt32(0);
4826 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004827 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004828 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004829 return NO_ERROR;
4830 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004831 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004832 if (!display) {
4833 return NAME_NOT_FOUND;
4834 }
4835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004836 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004837 return NO_ERROR;
4838 }
4839 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004840 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004841 // daltonize
4842 n = data.readInt32();
4843 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004844 case 1:
4845 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4846 break;
4847 case 2:
4848 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4849 break;
4850 case 3:
4851 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4852 break;
4853 default:
4854 mDaltonizer.setType(ColorBlindnessType::None);
4855 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004856 }
4857 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004858 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004859 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004860 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004861 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004862
4863 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004864 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004865 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004866 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004867 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004868 // apply a color matrix
4869 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004870 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004871 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004872 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004873 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004874 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004875 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004876 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004878 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004879 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004880
4881 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4882 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004883 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004884 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4885 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4886 }
4887
Chia-I Wu28f320b2018-05-03 11:02:56 -07004888 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004889 return NO_ERROR;
4890 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004891 // This is an experimental interface
4892 // Needs to be shifted to proper binder interface when we productize
4893 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004894 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004895 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004896 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004897 return NO_ERROR;
4898 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004899 case 1017: {
4900 n = data.readInt32();
4901 mForceFullDamage = static_cast<bool>(n);
4902 return NO_ERROR;
4903 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004904 case 1018: { // Modify Choreographer's phase offset
4905 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004906 if (mUseScheduler) {
4907 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4908 } else {
4909 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4910 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004911 return NO_ERROR;
4912 }
4913 case 1019: { // Modify SurfaceFlinger's phase offset
4914 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004915 if (mUseScheduler) {
4916 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4917 } else {
4918 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4919 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004920 return NO_ERROR;
4921 }
Irvel468051e2016-06-13 16:44:44 -07004922 case 1020: { // Layer updates interceptor
4923 n = data.readInt32();
4924 if (n) {
4925 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004926 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004927 }
4928 else{
4929 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004930 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004931 }
4932 return NO_ERROR;
4933 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004934 case 1021: { // Disable HWC virtual displays
4935 n = data.readInt32();
4936 mUseHwcVirtualDisplays = !n;
4937 return NO_ERROR;
4938 }
Romain Guy0147a172017-06-01 13:53:56 -07004939 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004940 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004941 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004942
Chia-I Wu28f320b2018-05-03 11:02:56 -07004943 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004944 return NO_ERROR;
4945 }
Romain Guy54f154a2017-10-24 21:40:32 +01004946 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004947 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004948 invalidateHwcGeometry();
4949 repaintEverything();
4950 return NO_ERROR;
4951 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004952 // Deprecate, use 1030 to check whether the device is color managed.
4953 case 1024: {
4954 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004955 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004956 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004957 n = data.readInt32();
4958 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004959 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004960 mTracing.enable();
4961 doTracing("tracing.enable");
4962 reply->writeInt32(NO_ERROR);
4963 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004964 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004965 status_t err = mTracing.disable();
4966 reply->writeInt32(err);
4967 }
4968 return NO_ERROR;
4969 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004970 case 1026: { // Get layer tracing status
4971 reply->writeBool(mTracing.isEnabled());
4972 return NO_ERROR;
4973 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004974 // Is a DisplayColorSetting supported?
4975 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004976 const auto display = getDefaultDisplayDevice();
4977 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004978 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004979 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004980
4981 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4982 switch (setting) {
4983 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004984 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004985 break;
4986 case DisplayColorSetting::UNMANAGED:
4987 reply->writeBool(true);
4988 break;
4989 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004991 break;
4992 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004993 reply->writeBool(
4994 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004995 break;
4996 }
4997 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004998 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004999 // Is VrFlinger active?
5000 case 1028: {
5001 Mutex::Autolock _l(mStateLock);
5002 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5003 return NO_ERROR;
5004 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005005 // Is device color managed?
5006 case 1030: {
5007 reply->writeBool(useColorManagement);
5008 return NO_ERROR;
5009 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005010 // Override default composition data space
5011 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5012 // && adb shell stop zygote && adb shell start zygote
5013 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5014 // adb shell stop zygote && adb shell start zygote
5015 case 1031: {
5016 Mutex::Autolock _l(mStateLock);
5017 n = data.readInt32();
5018 if (n) {
5019 n = data.readInt32();
5020 if (n) {
5021 Dataspace dataspace = static_cast<Dataspace>(n);
5022 if (!validateCompositionDataspace(dataspace)) {
5023 return BAD_VALUE;
5024 }
5025 mDefaultCompositionDataspace = dataspace;
5026 }
5027 n = data.readInt32();
5028 if (n) {
5029 Dataspace dataspace = static_cast<Dataspace>(n);
5030 if (!validateCompositionDataspace(dataspace)) {
5031 return BAD_VALUE;
5032 }
5033 mWideColorGamutCompositionDataspace = dataspace;
5034 }
5035 } else {
5036 // restore composition data space.
5037 mDefaultCompositionDataspace = defaultCompositionDataspace;
5038 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5039 }
5040 return NO_ERROR;
5041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005042 }
5043 }
5044 return err;
5045}
5046
Steven Thomas6d8110b2017-08-31 18:24:21 -07005047void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005048 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005049 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005050}
5051
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005052// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5053class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005054public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005055 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5056 ~WindowDisconnector() {
5057 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005058 }
5059
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005060private:
5061 ANativeWindow* mWindow;
5062 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005063};
5064
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005065status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005066 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5067 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005068 uint32_t reqWidth, uint32_t reqHeight,
5069 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005070 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005071 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005073 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005074
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005075 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5076
Chia-I Wu20261cb2018-08-23 12:55:44 -07005077 sp<DisplayDevice> display;
5078 {
5079 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005080
Chia-I Wu20261cb2018-08-23 12:55:44 -07005081 display = getDisplayDeviceLocked(displayToken);
5082 if (!display) return BAD_VALUE;
5083
Chia-I Wucb023152018-08-28 12:57:23 -07005084 // set the requested width/height to the logical display viewport size
5085 // by default
5086 if (reqWidth == 0 || reqHeight == 0) {
5087 reqWidth = uint32_t(display->getViewport().width());
5088 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005089 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005090 }
5091
Peiyong Lin0e003c92018-09-17 11:09:51 -07005092 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5093 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005094
5095 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005096 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005097 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5098 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005099}
5100
5101status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005102 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5103 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005104 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005105 ATRACE_CALL();
5106
5107 class LayerRenderArea : public RenderArea {
5108 public:
Robert Carr578038f2018-03-09 12:25:24 -08005109 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005110 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5111 bool childrenOnly)
5112 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005113 mLayer(layer),
5114 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005115 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005116 mFlinger(flinger),
5117 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005118 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005119 Rect getBounds() const override {
5120 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005121 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005122 }
Marissa Wall61c58622018-07-18 10:12:20 -07005123 int getHeight() const override {
5124 return mLayer->getActiveHeight(mLayer->getDrawingState());
5125 }
5126 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005127 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005128 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005129 Rect getSourceCrop() const override {
5130 if (mCrop.isEmpty()) {
5131 return getBounds();
5132 } else {
5133 return mCrop;
5134 }
5135 }
Robert Carr578038f2018-03-09 12:25:24 -08005136 class ReparentForDrawing {
5137 public:
5138 const sp<Layer>& oldParent;
5139 const sp<Layer>& newParent;
5140
5141 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5142 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005143 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005144 }
Robert Carr15eae092018-03-23 13:43:53 -07005145 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005146 };
5147
5148 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005149 const Rect sourceCrop = getSourceCrop();
5150 // no need to check rotation because there is none
5151 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5152 sourceCrop.height() != getReqHeight();
5153
Robert Carr578038f2018-03-09 12:25:24 -08005154 if (!mChildrenOnly) {
5155 mTransform = mLayer->getTransform().inverse();
5156 drawLayers();
5157 } else {
5158 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005159 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005160 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5161 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005162
5163 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5164 drawLayers();
5165 }
5166 }
chaviwa76b2712017-09-20 12:02:26 -07005167
chaviwa76b2712017-09-20 12:02:26 -07005168 private:
chaviw7206d492017-11-10 16:16:12 -08005169 const sp<Layer> mLayer;
5170 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005171
5172 // In the "childrenOnly" case we reparent the children to a screenshot
5173 // layer which has no properties set and which does not draw.
5174 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005175 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005176 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005177
5178 SurfaceFlinger* mFlinger;
5179 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005180 };
5181
5182 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5183 auto parent = layerHandle->owner.promote();
5184
Robert Carr2e102c92018-10-23 12:11:15 -07005185 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005186 ALOGE("captureLayers called with a removed parent");
5187 return NAME_NOT_FOUND;
5188 }
5189
Robert Carr578038f2018-03-09 12:25:24 -08005190 const int uid = IPCThreadState::self()->getCallingUid();
5191 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5192 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5193 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5194 return PERMISSION_DENIED;
5195 }
5196
chaviw7206d492017-11-10 16:16:12 -08005197 Rect crop(sourceCrop);
5198 if (sourceCrop.width() <= 0) {
5199 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005200 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005201 }
5202
5203 if (sourceCrop.height() <= 0) {
5204 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005205 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005206 }
5207
5208 int32_t reqWidth = crop.width() * frameScale;
5209 int32_t reqHeight = crop.height() * frameScale;
5210
Chia-I Wu20261cb2018-08-23 12:55:44 -07005211 // really small crop or frameScale
5212 if (reqWidth <= 0) {
5213 reqWidth = 1;
5214 }
5215 if (reqHeight <= 0) {
5216 reqHeight = 1;
5217 }
5218
Peiyong Lin0e003c92018-09-17 11:09:51 -07005219 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005220
Robert Carr578038f2018-03-09 12:25:24 -08005221 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005222 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5223 if (!layer->isVisible()) {
5224 return;
Robert Carr578038f2018-03-09 12:25:24 -08005225 } else if (childrenOnly && layer == parent.get()) {
5226 return;
chaviwa76b2712017-09-20 12:02:26 -07005227 }
5228 visitor(layer);
5229 });
5230 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005231 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005232}
5233
5234status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5235 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005236 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005237 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005238 bool useIdentityTransform) {
5239 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005240
Peiyong Lin0e003c92018-09-17 11:09:51 -07005241 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005242 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5243 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005244 *outBuffer =
5245 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5246 static_cast<android_pixel_format>(reqPixelFormat), 1,
5247 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005248
5249 // This mutex protects syncFd and captureResult for communication of the return values from the
5250 // main thread back to this Binder thread
5251 std::mutex captureMutex;
5252 std::condition_variable captureCondition;
5253 std::unique_lock<std::mutex> captureLock(captureMutex);
5254 int syncFd = -1;
5255 std::optional<status_t> captureResult;
5256
Robert Carr03480e22018-01-04 16:02:06 -08005257 const int uid = IPCThreadState::self()->getCallingUid();
5258 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5259
Dominik Laskowski8c001672018-05-30 16:52:06 -07005260 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005261 // If there is a refresh pending, bug out early and tell the binder thread to try again
5262 // after the refresh.
5263 if (mRefreshPending) {
5264 ATRACE_NAME("Skipping screenshot for now");
5265 std::unique_lock<std::mutex> captureLock(captureMutex);
5266 captureResult = std::make_optional<status_t>(EAGAIN);
5267 captureCondition.notify_one();
5268 return;
5269 }
5270
5271 status_t result = NO_ERROR;
5272 int fd = -1;
5273 {
5274 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005275 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005276 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5277 useIdentityTransform, forSystem, &fd);
5278 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005279 }
5280
5281 {
5282 std::unique_lock<std::mutex> captureLock(captureMutex);
5283 syncFd = fd;
5284 captureResult = std::make_optional<status_t>(result);
5285 captureCondition.notify_one();
5286 }
5287 });
5288
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005289 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005290 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005291 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005292 while (*captureResult == EAGAIN) {
5293 captureResult.reset();
5294 result = postMessageAsync(message);
5295 if (result != NO_ERROR) {
5296 return result;
5297 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005298 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005299 }
5300 result = *captureResult;
5301 }
5302
5303 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005304 sync_wait(syncFd, -1);
5305 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005306 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005307
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005308 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005309}
5310
chaviwa76b2712017-09-20 12:02:26 -07005311void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005312 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005313 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005314 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005315
Lloyd Pique144e1162017-12-20 16:44:52 -08005316 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005317
chaviwa76b2712017-09-20 12:02:26 -07005318 const auto reqWidth = renderArea.getReqWidth();
5319 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005320 const auto sourceCrop = renderArea.getSourceCrop();
5321 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005322
Peiyong Lin0e003c92018-09-17 11:09:51 -07005323 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005324 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005325
Mathias Agopian180f10d2013-04-10 22:55:41 -07005326 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005327 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005328
5329 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005330 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005331 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005332
chaviw50da5042018-04-09 13:49:37 -07005333 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005334 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005335 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005336
chaviwa76b2712017-09-20 12:02:26 -07005337 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005338 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005339 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005340 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005341 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005342}
5343
chaviwa76b2712017-09-20 12:02:26 -07005344status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5345 TraverseLayersFunction traverseLayers,
5346 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005347 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005348 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005349 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005350 ATRACE_CALL();
5351
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005352 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005353
5354 traverseLayers([&](Layer* layer) {
5355 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5356 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005357
Robert Carr03480e22018-01-04 16:02:06 -08005358 // We allow the system server to take screenshots of secure layers for
5359 // use in situations like the Screen-rotation animation and place
5360 // the impetus on WindowManager to not persist them.
5361 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005362 ALOGW("FB is protected: PERMISSION_DENIED");
5363 return PERMISSION_DENIED;
5364 }
5365
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005366 // this binds the given EGLImage as a framebuffer for the
5367 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005368 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005369 if (bufferBond.getStatus() != NO_ERROR) {
5370 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005371 return INVALID_OPERATION;
5372 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005373
Dan Stozaabcda352017-06-01 14:37:39 -07005374 // this will in fact render into our dequeued buffer
5375 // via an FBO, which means we didn't have to create
5376 // an EGLSurface and therefore we're not
5377 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005378 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005379
Alec Mouri492bc572018-09-11 21:40:04 +00005380 base::unique_fd syncFd = getRenderEngine().flush();
5381 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005382 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005383 }
Alec Mouri492bc572018-09-11 21:40:04 +00005384 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005385
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005386 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005387}
5388
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005389// ---------------------------------------------------------------------------
5390
Dan Stoza412903f2017-04-27 13:42:17 -07005391void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5392 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005393}
5394
Dan Stoza412903f2017-04-27 13:42:17 -07005395void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5396 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005397}
5398
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005399void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005400 const LayerVector::Visitor& visitor) {
5401 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005402 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005403 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005404 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005405 continue;
5406 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005407 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005408 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005409 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005410 return;
5411 }
chaviwa76b2712017-09-20 12:02:26 -07005412 if (!layer->isVisible()) {
5413 return;
5414 }
5415 visitor(layer);
5416 });
5417 }
5418}
5419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005420}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005421
Lloyd Pique074e8122018-07-26 12:57:23 -07005422
Mathias Agopian3f844832013-08-07 21:24:32 -07005423#if defined(__gl_h_)
5424#error "don't include gl/gl.h in this file"
5425#endif
5426
5427#if defined(__gl2_h_)
5428#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005429#endif