blob: 26de7545df120aa14e2467e34f8678c8076035d9 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700128 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700144ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
145 switch (rotation) {
146 case ISurfaceComposer::eRotateNone:
147 return ui::Transform::ROT_0;
148 case ISurfaceComposer::eRotate90:
149 return ui::Transform::ROT_90;
150 case ISurfaceComposer::eRotate180:
151 return ui::Transform::ROT_180;
152 case ISurfaceComposer::eRotate270:
153 return ui::Transform::ROT_270;
154 }
155 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
156 return ui::Transform::ROT_0;
157}
158
Peiyong Linfca547f2018-07-09 13:03:33 -0700159#pragma clang diagnostic pop
160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161class ConditionalLock {
162public:
163 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
164 if (lock) {
165 mMutex.lock();
166 }
167 }
168 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
169private:
170 Mutex& mMutex;
171 bool mLocked;
172};
Peiyong Linfca547f2018-07-09 13:03:33 -0700173
Peiyong Lin9d846a52018-11-05 13:18:20 -0800174// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
175bool validateCompositionDataspace(Dataspace dataspace) {
176 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
177}
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179} // namespace anonymous
180
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181// ---------------------------------------------------------------------------
182
Mathias Agopian99b49842011-06-27 16:05:52 -0700183const String16 sHardwareTest("android.permission.HARDWARE_TEST");
184const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
185const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
186const String16 sDump("android.permission.DUMP");
187
188// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800189int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
190int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700191int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700192bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800193uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800194bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800195bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800196int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600197bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700198int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700199bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700200bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700201Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
202ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
203Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
204ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700205
Kalle Raitaa099a242017-01-11 11:17:29 -0800206std::string getHwcServiceName() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.hwc_service_name", value, "default");
209 ALOGI("Using HWComposer service: '%s'", value);
210 return std::string(value);
211}
212
213bool useTrebleTestingOverride() {
214 char value[PROPERTY_VALUE_MAX] = {};
215 property_get("debug.sf.treble_testing_override", value, "false");
216 ALOGI("Treble testing override: '%s'", value);
217 return std::string(value) == "true";
218}
219
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
221 switch(displayColorSetting) {
222 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Enhanced");
228 default:
229 return std::string("Unknown ") +
230 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800232}
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Pique90c115d2018-09-18 21:39:42 -0700243SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
244 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700246 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800253 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800254 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800255 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700257 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700258 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700259 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700260 mDebugInTransaction(0),
261 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700262 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700263 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700264 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800265 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800266 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700268 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700269 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800270
Lloyd Pique90c115d2018-09-18 21:39:42 -0700271SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
272 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
275 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
276 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
277
278 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
280
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800281 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700284 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
286
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700287 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
289
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800290 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
292
Steven Thomas050b2c82017-03-06 11:45:16 -0800293 // Vr flinger is only enabled on Daydream ready devices.
294 useVrFlinger = getBool< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::useVrFlinger>(false);
296
Fabien Sanglard1971b632017-03-10 14:50:03 -0800297 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
299
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600300 hasWideColorDisplay =
301 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700302 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700303 getBool<V1_2::ISurfaceFlingerConfigs,
304 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
305
306 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
307 if (surfaceFlingerConfigsServiceV1_2) {
308 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700309 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
310 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
311 defaultCompositionDataspace = tmpDefaultDataspace;
312 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
313 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
314 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
315 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700316 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800317 mDefaultCompositionDataspace = defaultCompositionDataspace;
318 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600319
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320 useContextPriority = getBool<ISurfaceFlingerConfigs,
321 &ISurfaceFlingerConfigs::useContextPriority>(true);
322
Iris Chang7501ed62018-04-30 14:45:42 +0800323 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700324 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
325 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation::ORIENTATION_0);
327
328 switch (primaryDisplayOrientation) {
329 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800343
Lloyd Pique90c115d2018-09-18 21:39:42 -0700344 mPrimaryDispSync =
345 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
346 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 // debugging stuff...
349 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopianb4b17302013-03-20 18:36:41 -0700351 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700352 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 property_get("debug.sf.showupdates", value, "0");
355 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700357 property_get("debug.sf.ddms", value, "0");
358 mDebugDDMS = atoi(value);
359 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700360 if (!startDdmConnection()) {
361 // start failed, and DDMS debugging not enabled
362 mDebugDDMS = 0;
363 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700365 ALOGI_IF(mDebugRegion, "showupdates enabled");
366 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700367
368 property_get("debug.sf.disable_backpressure", value, "0");
369 mPropagateBackpressure = !atoi(value);
370 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700371
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800372 property_get("debug.sf.enable_hwc_vds", value, "0");
373 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800374 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 property_get("ro.sf.disable_triple_buffer", value, "1");
377 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700379
Yiwei Zhang243b3782018-05-15 17:40:04 -0700380 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700381 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
382 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
383
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200384 property_get("debug.sf.early_phase_offset_ns", value, "-1");
385 const int earlySfOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
388 const int earlyGlSfOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
391 const int earlyAppOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
394 const int earlyGlAppOffsetNs = atoi(value);
395
Ana Krulec98b5b242018-08-10 15:03:23 -0700396 property_get("debug.sf.use_scheduler", value, "0");
397 mUseScheduler = atoi(value);
398
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200399 const VSyncModulator::Offsets earlyOffsets =
400 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
401 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
402 const VSyncModulator::Offsets earlyGlOffsets =
403 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
405 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
406 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700407
Romain Guy11d63f42017-07-20 12:47:14 -0700408 // We should be reading 'persist.sys.sf.color_saturation' here
409 // but since /data may be encrypted, we need to wait until after vold
410 // comes online to attempt to read the property. The property is
411 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800412
413 if (useTrebleTestingOverride()) {
414 // Without the override SurfaceFlinger cannot connect to HIDL
415 // services that are not listed in the manifests. Considered
416 // deriving the setting from the set service name, but it
417 // would be brittle if the name that's not 'default' is used
418 // for production purposes later on.
419 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423void SurfaceFlinger::onFirstRef()
424{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800425 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428SurfaceFlinger::~SurfaceFlinger()
429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Dan Stozac7014012014-02-14 15:03:43 -0800432void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433{
434 // the window manager died on us. prepare its eulogy.
435
Andy McFadden13a082e2012-08-24 10:16:42 -0700436 // restore initial conditions (default device unblank, etc)
437 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438
439 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441}
442
Robert Carr1db73f62016-12-21 12:58:51 -0800443static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700444 status_t err = client->initCheck();
445 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return nullptr;
449}
450
451sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
452 return initClient(new Client(this));
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
456 const sp<IGraphicBufferProducer>& gbp) {
457 if (authenticateSurfaceTexture(gbp) == false) {
458 return nullptr;
459 }
460 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
461 if (layer == nullptr) {
462 return nullptr;
463 }
464
465 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800466}
467
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700468sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
469 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470{
471 class DisplayToken : public BBinder {
472 sp<SurfaceFlinger> flinger;
473 virtual ~DisplayToken() {
474 // no more references, this display must be terminated
475 Mutex::Autolock _l(flinger->mStateLock);
476 flinger->mCurrentState.displays.removeItem(this);
477 flinger->setTransactionFlags(eDisplayTransactionNeeded);
478 }
479 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700480 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 : flinger(flinger) {
482 }
483 };
484
485 sp<BBinder> token = new DisplayToken(this);
486
487 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 // Display ID is assigned when virtual display is allocated by HWC.
489 DisplayDeviceState state;
490 state.isSecure = secure;
491 state.displayName = displayName;
492 mCurrentState.displays.add(token, state);
493 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494 return token;
495}
496
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 Mutex::Autolock _l(mStateLock);
499
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
501 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700502 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 return;
504 }
505
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
507 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700508 ALOGE("destroyDisplay called for non-virtual display");
509 return;
510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 mInterceptor->saveDisplayDeletion(state.sequenceId);
512 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700513 setTransactionFlags(eDisplayTransactionNeeded);
514}
515
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 std::optional<DisplayId> displayId;
518
519 if (id == HWC_DISPLAY_PRIMARY) {
520 displayId = getInternalDisplayId();
521 } else if (id == HWC_DISPLAY_EXTERNAL) {
522 displayId = getExternalDisplayId();
523 }
524
525 if (!displayId) {
526 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800527 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700528 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700529
530 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700531}
532
Ady Abraham37965d42018-11-01 13:43:32 -0700533status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
534 if (!outGetColorManagement) {
535 return BAD_VALUE;
536 }
537 *outGetColorManagement = useColorManagement;
538 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700539}
540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541void SurfaceFlinger::bootFinished()
542{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700543 if (mStartPropertySetThread->join() != NO_ERROR) {
544 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 const nsecs_t now = systemTime();
547 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000548 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
550 // wait patiently for the window manager death
551 const String16 name("window");
552 sp<IBinder> window(defaultServiceManager()->getService(name));
553 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700554 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 }
556
Steven Thomas050b2c82017-03-06 11:45:16 -0800557 if (mVrFlinger) {
558 mVrFlinger->OnBootFinished();
559 }
560
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700562 // formerly we would just kill the process, but we now ask it to exit so it
563 // can choose where to stop the animation.
564 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700565
566 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
567 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
568 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700569
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 postMessageAsync(new LambdaMessage([this] {
571 readPersistentProperties();
572 mBootStage = BootStage::FINISHED;
573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700598 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700599}
600
Wei Wangf9b05ee2017-07-19 20:59:39 -0700601// Do not call property_set on main thread which will be blocked by init
602// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700604 ALOGI( "SurfaceFlinger's main thread ready to run. "
605 "Initializing graphics H/W...");
606
Thierry Strudel2924d012017-08-14 15:19:37 -0700607 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700612 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 mScheduler = getFactory().createScheduler([this](bool enabled) {
614 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
615 });
616
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700618 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 [this] { resyncWithRateLimit(); },
620 impl::EventThread::InterceptVSyncsCallback());
621 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700622 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700623 [this] { resyncWithRateLimit(); },
624 [this](nsecs_t timestamp) {
625 mInterceptor->saveVSyncEvent(timestamp);
626 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800627
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700629 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
630 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 } else {
632 mEventThreadSource =
633 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
634 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
635 mEventThread =
636 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
637 [this] { resyncWithRateLimit(); },
638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 [this](nsecs_t timestamp) {
648 mInterceptor->saveVSyncEvent(timestamp);
649 },
650 "sfEventThread");
651 mEventQueue->setEventThread(mSFEventThread.get());
652 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
Steven Thomasb02664d2017-07-26 18:48:28 -0700655 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700656 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700657 renderEngineFeature |= (useColorManagement ?
658 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700659 renderEngineFeature |= (useContextPriority ?
660 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700661
662 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
663 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700664 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
665 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800666 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700670 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700671 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Lloyd Piquefcd86612017-12-14 17:15:36 -0800679 // make the default display GLContext current so that we can create textures
680 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800682
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 // This callback is called from the vr flinger dispatch thread. We
686 // need to call signalTransaction(), which requires holding
687 // mStateLock when we're not on the main thread. Acquiring
688 // mStateLock from the vr flinger dispatch thread might trigger a
689 // deadlock in surface flinger (see b/66916578), so post a message
690 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700692 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
693 mVrFlingerRequestsDisplay = requestDisplay;
694 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
698 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700699 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700700 .value_or(0),
701 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800702 if (!mVrFlinger) {
703 ALOGE("Failed to start vrflinger");
704 }
705 }
706
Lloyd Pique90c115d2018-09-18 21:39:42 -0700707 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700709
Mathias Agopian92a979a2012-08-02 18:32:23 -0700710 // initialize our drawing state
711 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700712
Andy McFadden13a082e2012-08-24 10:16:42 -0700713 // set initial conditions (e.g. unblank default device)
714 initializeDisplays();
715
David Sodmanbc815282017-11-05 18:57:52 -0800716 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700717
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700719
720 const bool presentFenceReliable =
721 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
722 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723
724 if (mStartPropertySetThread->Start() != NO_ERROR) {
725 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727
Chia-I Wud49d6692018-06-27 07:17:41 +0800728 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
729 // is used to saturate legacy sRGB content. However, to make sure the same color under
730 // Display P3 will be saturated to the same color, we intentionally break the API spec
731 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
732 // such saturation matrix on Display P3 is understood fully, the API should always return
733 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700734 mEnhancedSaturationMatrix =
735 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800736
737 // we will apply this on Display P3.
738 if (mEnhancedSaturationMatrix != mat4()) {
739 ColorSpace srgb(ColorSpace::sRGB());
740 ColorSpace displayP3(ColorSpace::DisplayP3());
741 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
742 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
743 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
744 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800745
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700747}
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 Mutex::Autolock _l(mStateLock);
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752 char value[PROPERTY_VALUE_MAX];
753
754 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700756 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800757 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100758
759 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700760 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700761}
762
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Start boot animation service by setting a property mailbox
765 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700768 if (mStartPropertySetThread->join() != NO_ERROR) {
769 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800770 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700771}
772
Mathias Agopian875d8e12013-06-07 15:35:48 -0700773size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800774 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700775}
776
Mathias Agopian875d8e12013-06-07 15:35:48 -0700777size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800778 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700779}
780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800781// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800782
Jamie Gennis582270d2011-08-17 18:19:00 -0700783bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800785 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800786 return authenticateSurfaceTextureLocked(bufferProducer);
787}
788
789bool SurfaceFlinger::authenticateSurfaceTextureLocked(
790 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800791 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800792 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800793}
794
Brian Anderson6b376712017-04-04 10:51:39 -0700795status_t SurfaceFlinger::getSupportedFrameTimestamps(
796 std::vector<FrameEvent>* outSupported) const {
797 *outSupported = {
798 FrameEvent::REQUESTED_PRESENT,
799 FrameEvent::ACQUIRE,
800 FrameEvent::LATCH,
801 FrameEvent::FIRST_REFRESH_START,
802 FrameEvent::LAST_REFRESH_START,
803 FrameEvent::GPU_COMPOSITION_DONE,
804 FrameEvent::DEQUEUE_READY,
805 FrameEvent::RELEASE,
806 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700807 ConditionalLock _l(mStateLock,
808 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700809 if (!getHwComposer().hasCapability(
810 HWC2::Capability::PresentFenceIsNotReliable)) {
811 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
812 }
813 return NO_ERROR;
814}
815
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700816status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
817 Vector<DisplayInfo>* configs) {
818 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 return BAD_VALUE;
820 }
821
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 const auto displayId = getPhysicalDisplayId(displayToken);
823 if (!displayId) {
824 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700825 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 // TODO: Not sure if display density should handled by SF any longer
828 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700831 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800832 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700833 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 }
835 return density;
836 }
837 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700840 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 return getDensityFromProperty("ro.sf.lcd_density"); }
842 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700848 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 DisplayInfo info = DisplayInfo();
850
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 float xdpi = hwConfig->getDpiX();
852 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700854 info.w = hwConfig->getWidth();
855 info.h = hwConfig->getHeight();
856 // Default display viewport to display width and height
857 info.viewportW = info.w;
858 info.viewportH = info.h;
859
Dominik Laskowski075d3172018-05-24 15:50:06 -0700860 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 // The density of the device is provided by a build property
862 float density = Density::getBuildDensity() / 160.0f;
863 if (density == 0) {
864 // the build doesn't provide a density -- this is wrong!
865 // use xdpi instead
866 ALOGE("ro.sf.lcd_density must be defined as a build property");
867 density = xdpi / 160.0f;
868 }
869 if (Density::getEmuDensity()) {
870 // if "qemu.sf.lcd_density" is specified, it overrides everything
871 xdpi = ydpi = density = Density::getEmuDensity();
872 density /= 160.0f;
873 }
874 info.density = density;
875
876 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877 const auto display = getDefaultDisplayDeviceLocked();
878 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700879
880 // This is for screenrecord
881 const Rect viewport = display->getViewport();
882 if (viewport.isValid()) {
883 info.viewportW = uint32_t(viewport.getWidth());
884 info.viewportH = uint32_t(viewport.getHeight());
885 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 } else {
887 // TODO: where should this value come from?
888 static const int TV_DENSITY = 213;
889 info.density = TV_DENSITY / 160.0f;
890 info.orientation = 0;
891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 info.xdpi = xdpi;
894 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900896 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897
Andy McFadden91b2ca82014-06-13 14:04:23 -0700898 // This is how far in advance a buffer must be queued for
899 // presentation at a given time. If you want a buffer to appear
900 // on the screen at time N, you must submit the buffer before
901 // (N - presentationDeadline).
902 //
903 // Normally it's one full refresh period (to give SF a chance to
904 // latch the buffer), but this can be reduced by configuring a
905 // DispSync offset. Any additional delays introduced by the hardware
906 // composer or panel must be accounted for here.
907 //
908 // We add an additional 1ms to allow for processing time and
909 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800911 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700912
913 // All non-virtual displays are currently considered secure.
914 info.secure = true;
915
Dominik Laskowski075d3172018-05-24 15:50:06 -0700916 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700917 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800918 std::swap(info.w, info.h);
919 }
920
Michael Wright28f24d02016-07-12 13:30:53 -0700921 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700922 }
923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 return NO_ERROR;
925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
928 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return BAD_VALUE;
930 }
931
Ana Krulece588e312018-09-18 12:32:24 -0700932 if (mUseScheduler) {
933 mScheduler->getDisplayStatInfo(stats);
934 } else {
935 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
936 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
937 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return NO_ERROR;
939}
940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
942 const auto display = getDisplayDevice(displayToken);
943 if (!display) {
944 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800945 return BAD_VALUE;
946 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700949}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700952 if (display->isVirtual()) {
953 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
954 return;
955 }
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 return;
960 }
961
Dominik Laskowski075d3172018-05-24 15:50:06 -0700962 const auto displayId = display->getId();
963 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700966 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967}
968
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700970 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 Vector<DisplayInfo> configs;
972 getDisplayConfigs(displayToken, &configs);
973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
975 configs.size());
976 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700977 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 const auto display = getDisplayDevice(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
981 displayToken.get());
982 } else if (display->isVirtual()) {
983 ALOGW("Attempt to set active config %d for virtual display", mode);
984 } else {
985 setActiveConfigInternal(display, mode);
986 }
987 }));
988
Mathias Agopian888c8222012-08-04 21:10:38 -0700989 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700990}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
993 Vector<ColorMode>* outColorModes) {
994 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700995 return BAD_VALUE;
996 }
997
Dominik Laskowski075d3172018-05-24 15:50:06 -0700998 const auto displayId = getPhysicalDisplayId(displayToken);
999 if (!displayId) {
1000 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001001 }
1002
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001004 {
1005 ConditionalLock _l(mStateLock,
1006 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001008 }
Michael Wright28f24d02016-07-12 13:30:53 -07001009 outColorModes->clear();
1010 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1011
1012 return NO_ERROR;
1013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1016 if (const auto display = getDisplayDevice(displayToken)) {
1017 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001018 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1023 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001024 if (display->isVirtual()) {
1025 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 ColorMode currentMode = display->getActiveColorMode();
1030 Dataspace currentDataSpace = display->getCompositionDataSpace();
1031 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001032
Peiyong Lin38e9a562018-04-10 16:24:20 -07001033 if (mode == currentMode && dataSpace == currentDataSpace &&
1034 renderIntent == currentRenderIntent) {
1035 return;
1036 }
1037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 display->setActiveColorMode(mode);
1039 display->setCompositionDataSpace(dataSpace);
1040 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001041
Dominik Laskowski075d3172018-05-24 15:50:06 -07001042 const auto displayId = display->getId();
1043 LOG_ALWAYS_FATAL_IF(!displayId);
1044 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1045
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();
Chia-I Wu7f402902017-11-09 12:51:10 -08001412 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
David Sodmanfa9b2af2017-12-24 13:28:59 -08001722 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 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962}
1963
1964void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 ATRACE_CALL();
1966 ALOGV("rebuildLayerStacks");
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001969 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001970 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001971 mVisibleRegionsDirty = false;
1972 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001973
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001974 for (const auto& pair : mDisplays) {
1975 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001976 Region opaqueRegion;
1977 Region dirtyRegion;
1978 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001979 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001980 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 const Rect bounds = display->getBounds();
1982 if (display->isPoweredOn()) {
1983 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001984
Jeff Sharkey76488112017-02-27 14:15:18 -07001985 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001986 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07001987 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001988 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001989 Region drawRegion(tr.transform(
1990 layer->visibleNonTransparentRegion));
1991 drawRegion.andSelf(bounds);
1992 if (!drawRegion.isEmpty()) {
1993 layersSortedByZ.add(layer);
1994 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001995 // Clear out the HWC layer if this layer was
1996 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07001997 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07001998 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001999 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002000 // WM changes display->layerStack upon sleep/awake.
2001 // Here we make sure we delete the HWC layers even if
2002 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002003 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002004 }
2005
2006 // If a layer is not going to get a release fence because
2007 // it is invisible, but it is also going to release its
2008 // old buffer, add it to the list of layers needing
2009 // fences.
2010 if (hwcLayerDestroyed) {
2011 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2012 mLayersWithQueuedFrames.cend(), layer);
2013 if (found != mLayersWithQueuedFrames.cend()) {
2014 layersNeedingFences.add(layer);
2015 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002016 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002017 });
2018 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 display->setVisibleLayersSortedByZ(layersSortedByZ);
2020 display->setLayersNeedingFences(layersNeedingFences);
2021 display->undefinedRegion.set(bounds);
2022 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2023 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002024 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002025 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002027
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002029// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002030// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002031// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002032// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002033// The returned HDR data space is one of
2034// - Dataspace::UNKNOWN
2035// - Dataspace::BT2020_HLG
2036// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002037Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2038 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002039 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002040 *outHdrDataSpace = Dataspace::UNKNOWN;
2041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002042 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002043 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002044 case Dataspace::V0_SCRGB:
2045 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002046 case Dataspace::BT2020:
2047 case Dataspace::BT2020_ITU:
2048 case Dataspace::BT2020_LINEAR:
2049 case Dataspace::DISPLAY_BT2020:
2050 bestDataSpace = Dataspace::DISPLAY_BT2020;
2051 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002052 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002053 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002054 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002055 case Dataspace::BT2020_PQ:
2056 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002057 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002059 case Dataspace::BT2020_HLG:
2060 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002061 // When there's mixed PQ content and HLG content, we set the HDR
2062 // data space to be BT2020_PQ and convert HLG to PQ.
2063 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2064 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002065 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002066 break;
2067 default:
2068 break;
2069 }
Romain Guy54f154a2017-10-24 21:40:32 +01002070 }
2071
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002072 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002073}
2074
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002075// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2077 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002078 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2079 *outMode = ColorMode::NATIVE;
2080 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002081 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002082 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002083 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002084
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002085 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002086 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002087
Peiyong Lindfde5112018-06-05 10:58:41 -07002088 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002089 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002090 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002091 if (isHdr) {
2092 bestDataSpace = hdrDataSpace;
2093 }
2094
Chia-I Wu0d711262018-05-21 15:19:35 -07002095 RenderIntent intent;
2096 switch (mDisplayColorSetting) {
2097 case DisplayColorSetting::MANAGED:
2098 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002099 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002100 break;
2101 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002102 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002103 break;
2104 default: // vendor display color setting
2105 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2106 break;
2107 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002109 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002110}
2111
David Sodmanfa9b2af2017-12-24 13:28:59 -08002112void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002113{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002114 bool dirty = !display->getDirtyRegion(false).isEmpty();
2115 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2116 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002117
David Sodmanfa9b2af2017-12-24 13:28:59 -08002118 // If nothing has changed (!dirty), don't recompose.
2119 // If something changed, but we don't currently have any visible layers,
2120 // and didn't when we last did a composition, then skip it this time.
2121 // The second rule does two things:
2122 // - When all layers are removed from a display, we'll emit one black
2123 // frame, then nothing more until we get new layers.
2124 // - When a display is created with a private layer stack, we won't
2125 // emit any black frames until a layer is added to the layer stack.
2126 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002127
Dominik Laskowski075d3172018-05-24 15:50:06 -07002128 const char flagPrefix[] = {'-', '+'};
2129 static_cast<void>(flagPrefix);
2130 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2131 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2132 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002133
David Sodmanfa9b2af2017-12-24 13:28:59 -08002134 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002135
David Sodmanfa9b2af2017-12-24 13:28:59 -08002136 if (mustRecompose) {
2137 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002138 }
2139}
2140
David Sodmanfa9b2af2017-12-24 13:28:59 -08002141void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002142{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002143 if (!display->isPoweredOn()) {
2144 return;
David Sodman2b406362017-12-15 13:33:47 -08002145 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002146
Dominik Laskowski05275f12018-11-01 15:03:24 -07002147 status_t result = display->prepareFrame(getHwComposer(),
2148 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002149 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2150 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002151}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002152
David Sodmanfa9b2af2017-12-24 13:28:59 -08002153void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002154 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 ALOGV("doComposition");
2156
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157 if (display->isPoweredOn()) {
2158 // transform the dirty region into this screen's coordinate space
2159 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002160
David Sodmanfa9b2af2017-12-24 13:28:59 -08002161 // repaint the framebuffer (if needed)
2162 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002163
David Sodmanfa9b2af2017-12-24 13:28:59 -08002164 display->dirtyRegion.clear();
2165 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002166 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002167 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002168}
2169
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170void SurfaceFlinger::postFrame()
2171{
2172 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002173 const auto display = getDefaultDisplayDeviceLocked();
2174 if (display && getHwComposer().isConnected(*display->getId())) {
2175 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002176 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2177 logFrameStats();
2178 }
2179 }
2180}
2181
2182void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183{
Mathias Agopian841cde52012-03-01 15:44:37 -08002184 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002186
David Sodmanfa9b2af2017-12-24 13:28:59 -08002187 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002188
David Sodmanfa9b2af2017-12-24 13:28:59 -08002189 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002190 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002191 if (displayId) {
2192 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002193 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002194 display->onSwapBuffersCompleted();
2195 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002196 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002197 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002198
Chia-I Wu7b549592017-11-15 09:14:57 -08002199 // The layer buffer from the previous frame (if any) is released
2200 // by HWC only when the release fence from this frame (if any) is
2201 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002202 if (displayId && layer->hasHwcLayer(*displayId)) {
2203 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2204 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002205 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002206
2207 // If the layer was client composited in the previous frame, we
2208 // need to merge with the previous client target acquire fence.
2209 // Since we do not track that, always merge with the current
2210 // client target acquire fence when it is available, even though
2211 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002212 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002213 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002214 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002215 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002216
David Sodman15094112018-10-11 09:39:37 -07002217 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002218 }
Chia-I Wu83806892017-11-16 10:50:20 -08002219
2220 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002221 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002222 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002223 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002224 sp<Fence> presentFence =
2225 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002227 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002228 }
2229 }
2230
Dominik Laskowski075d3172018-05-24 15:50:06 -07002231 if (displayId) {
2232 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002233 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002234 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235}
2236
Mathias Agopian87baae12012-07-31 12:38:26 -07002237void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238{
Mathias Agopian841cde52012-03-01 15:44:37 -08002239 ATRACE_CALL();
2240
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002241 // here we keep a copy of the drawing state (that is the state that's
2242 // going to be overwritten by handleTransactionLocked()) outside of
2243 // mStateLock so that the side-effects of the State assignment
2244 // don't happen with mStateLock held (which can cause deadlocks).
2245 State drawingState(mDrawingState);
2246
Mathias Agopianca4d3602011-05-19 15:38:14 -07002247 Mutex::Autolock _l(mStateLock);
2248 const nsecs_t now = systemTime();
2249 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250
Mathias Agopianca4d3602011-05-19 15:38:14 -07002251 // Here we're guaranteed that some transaction flags are set
2252 // so we can call handleTransactionLocked() unconditionally.
2253 // We call getTransactionFlags(), which will also clear the flags,
2254 // with mStateLock held to guarantee that mCurrentState won't change
2255 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002256
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002257 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002258 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002259 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002260
Mathias Agopianca4d3602011-05-19 15:38:14 -07002261 mLastTransactionTime = systemTime() - now;
2262 mDebugInTransaction = 0;
2263 invalidateHwcGeometry();
2264 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002265}
2266
Lloyd Piqueba04e622017-12-14 17:11:26 -08002267void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2268 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 const std::optional<DisplayIdentificationInfo> info =
2270 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002271
Dominik Laskowski075d3172018-05-24 15:50:06 -07002272 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002273 continue;
2274 }
2275
Lloyd Piqueba04e622017-12-14 17:11:26 -08002276 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002277 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002278 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 mPhysicalDisplayTokens[info->id] = new BBinder();
2280 DisplayDeviceState state;
2281 state.displayId = info->id;
2282 state.isSecure = true; // All physical displays are currently considered secure.
2283 state.displayName = info->name;
2284 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2285 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002286 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002287 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002288 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002289
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2291 if (index >= 0) {
2292 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2293 mInterceptor->saveDisplayDeletion(state.sequenceId);
2294 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002295 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002297 }
2298
2299 processDisplayChangesLocked();
2300 }
2301
2302 mPendingHotplugEvents.clear();
2303}
2304
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002306 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2307 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2308 const sp<IGraphicBufferProducer>& producer) {
2309 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2310 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002311 creationArgs.isSecure = state.isSecure;
2312 creationArgs.displaySurface = dispSurface;
2313 creationArgs.hasWideColorGamut = false;
2314 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315
Dominik Laskowski075d3172018-05-24 15:50:06 -07002316 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2317 creationArgs.isPrimary = isInternalDisplay;
2318
2319 if (useColorManagement && displayId) {
2320 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002322 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002323 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325
Dominik Laskowski7e045462018-05-30 13:02:02 -07002326 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002327 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002328 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329 }
tangrobin6753a022018-08-10 10:58:54 +08002330 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 if (displayId) {
2333 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002334 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002336 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337
Lloyd Pique90c115d2018-09-18 21:39:42 -07002338 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002340 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341
2342 /*
2343 * Create our display's surface
2344 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002345 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 renderSurface->setCritical(isInternalDisplay);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002347 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002349 creationArgs.displayWidth = renderSurface->getWidth();
2350 creationArgs.displayHeight = renderSurface->getHeight();
2351 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002352
2353 // Make sure that composition can never be stalled by a virtual display
2354 // consumer that isn't processing buffers fast enough. We have to do this
2355 // in two places:
2356 // * Here, in case the display is composed entirely by HWC.
2357 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2358 // window's swap interval in eglMakeCurrent, so they'll override the
2359 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002360 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2362 }
2363
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 creationArgs.displayInstallOrientation =
2365 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002366
Lloyd Pique99d3da52018-01-22 17:48:03 -08002367 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002368 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002369
Lloyd Pique90c115d2018-09-18 21:39:42 -07002370 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371
2372 if (maxFrameBufferAcquiredBuffers >= 3) {
2373 nativeWindowSurface->preallocateBuffers();
2374 }
2375
2376 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002377 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002378 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002380 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002383 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002384 if (!state.isVirtual()) {
2385 LOG_ALWAYS_FATAL_IF(!displayId);
2386 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002387 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002389 display->setLayerStack(state.layerStack);
2390 display->setProjection(state.orientation, state.viewport, state.frame);
2391 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394}
2395
Lloyd Pique347200f2017-12-14 17:00:15 -08002396void SurfaceFlinger::processDisplayChangesLocked() {
2397 // here we take advantage of Vector's copy-on-write semantics to
2398 // improve performance by skipping the transaction entirely when
2399 // know that the lists are identical
2400 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2401 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2402 if (!curr.isIdenticalTo(draw)) {
2403 mVisibleRegionsDirty = true;
2404 const size_t cc = curr.size();
2405 size_t dc = draw.size();
2406
2407 // find the displays that were removed
2408 // (ie: in drawing state but not in current state)
2409 // also handle displays that changed
2410 // (ie: displays that are in both lists)
2411 for (size_t i = 0; i < dc;) {
2412 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2413 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002414 // Save display IDs before disconnecting.
2415 const auto internalDisplayId = getInternalDisplayId();
2416 const auto externalDisplayId = getExternalDisplayId();
2417
Lloyd Pique347200f2017-12-14 17:00:15 -08002418 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002419 // Call makeCurrent() on the primary display so we can
2420 // be sure that nothing associated with this display
2421 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002422 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2423 defaultDisplay->makeCurrent();
2424 }
2425 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2426 display->disconnect(getHwComposer());
2427 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002429 if (mUseScheduler) {
2430 mScheduler->hotplugReceived(mAppConnectionHandle,
2431 EventThread::DisplayType::Primary, false);
2432 } else {
2433 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2434 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002436 if (mUseScheduler) {
2437 mScheduler->hotplugReceived(mAppConnectionHandle,
2438 EventThread::DisplayType::External, false);
2439 } else {
2440 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2441 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002442 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002443 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 } else {
2445 // this display is in both lists. see if something changed.
2446 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2449 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2450 if (state_binder != draw_binder) {
2451 // changing the surface is like destroying and
2452 // recreating the DisplayDevice, so we just remove it
2453 // from the drawing state, so that it get re-added
2454 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2456 display->disconnect(getHwComposer());
2457 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002458 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 mDrawingState.displays.removeItemsAt(i);
2460 dc--;
2461 // at this point we must loop to the next item
2462 continue;
2463 }
2464
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 }
2469 if ((state.orientation != draw[i].orientation) ||
2470 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002471 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 }
2473 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002475 }
2476 }
2477 }
2478 ++i;
2479 }
2480
2481 // find displays that were added
2482 // (ie: in current state but not in drawing state)
2483 for (size_t i = 0; i < cc; i++) {
2484 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2485 const DisplayDeviceState& state(curr[i]);
2486
2487 sp<DisplaySurface> dispSurface;
2488 sp<IGraphicBufferProducer> producer;
2489 sp<IGraphicBufferProducer> bqProducer;
2490 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002491 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002494 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 // Virtual displays without a surface are dormant:
2496 // they have external state (layer stack, projection,
2497 // etc.) but no internal state (i.e. a DisplayDevice).
2498 if (state.surface != nullptr) {
2499 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 int width = 0;
2502 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2503 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2504 int height = 0;
2505 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2506 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2507 int intFormat = 0;
2508 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2509 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002510 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511
Dominik Laskowski075d3172018-05-24 15:50:06 -07002512 displayId =
2513 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 }
2515
2516 // TODO: Plumb requested format back up to consumer
2517
2518 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 bqProducer, bqConsumer,
2521 state.displayName);
2522
2523 dispSurface = vds;
2524 producer = vds;
2525 }
2526 } else {
2527 ALOGE_IF(state.surface != nullptr,
2528 "adding a supported display, but rendering "
2529 "surface is provided (%p), ignoring it",
2530 state.surface.get());
2531
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 displayId = state.displayId;
2533 LOG_ALWAYS_FATAL_IF(!displayId);
2534 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002535 producer = bqProducer;
2536 }
2537
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002538 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002539 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002540 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002541 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002543 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 LOG_ALWAYS_FATAL_IF(!displayId);
2545
2546 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002547 if (mUseScheduler) {
2548 mScheduler->hotplugReceived(mAppConnectionHandle,
2549 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002550 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002551 } else {
2552 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2553 true);
2554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002556 if (mUseScheduler) {
2557 mScheduler->hotplugReceived(mAppConnectionHandle,
2558 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002559 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002560 } else {
2561 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2562 true);
2563 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002564 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 }
2566 }
2567 }
2568 }
2569 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002570
2571 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002572}
2573
Mathias Agopian87baae12012-07-31 12:38:26 -07002574void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002575{
Dan Stoza7dde5992015-05-22 09:51:44 -07002576 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002577 mCurrentState.traverseInZOrder([](Layer* layer) {
2578 layer->notifyAvailableFrames();
2579 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002580
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 /*
2582 * Traversal of the children
2583 * (perform the transaction for each of them if needed)
2584 */
2585
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002587 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002589 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590
2591 const uint32_t flags = layer->doTransaction(0);
2592 if (flags & Layer::eVisibleRegion)
2593 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002594 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 }
2596
2597 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002598 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 */
2600
Mathias Agopiane57f2922012-08-09 16:29:12 -07002601 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002602 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002603 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002604 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002606 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002607 // The transform hint might have changed for some layers
2608 // (either because a display has changed, or because a layer
2609 // as changed).
2610 //
2611 // Walk through all the layers in currentLayers,
2612 // and update their transform hint.
2613 //
2614 // If a layer is visible only on a single display, then that
2615 // display is used to calculate the hint, otherwise we use the
2616 // default display.
2617 //
2618 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2619 // the hint is set before we acquire a buffer from the surface texture.
2620 //
2621 // NOTE: layer transactions have taken place already, so we use their
2622 // drawing state. However, SurfaceFlinger's own transaction has not
2623 // happened yet, so we must use the current state layer list
2624 // (soon to become the drawing state list).
2625 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002626 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002627 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002628 bool first = true;
2629 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002630 // NOTE: we rely on the fact that layers are sorted by
2631 // layerStack first (so we don't have to traverse the list
2632 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002633 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002634 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002635 currentlayerStack = layerStack;
2636 // figure out if this layerstack is mirrored
2637 // (more than one display) if so, pick the default display,
2638 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002639 hintDisplay = nullptr;
2640 for (const auto& [token, display] : mDisplays) {
2641 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2642 if (hintDisplay) {
2643 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002644 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002646 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002647 }
2648 }
2649 }
2650 }
Chet Haase91d25932013-04-11 15:24:55 -07002651
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002652 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002653 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2654 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002655
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002656 // could be null when this layer is using a layerStack
2657 // that is not visible on any display. Also can occur at
2658 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002659 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002660 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002661
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002662 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002663 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 if (hintDisplay) {
2665 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002666 }
Robert Carr2047fae2016-11-28 14:09:09 -08002667
2668 first = false;
2669 });
Mathias Agopian84300952012-11-21 16:02:13 -08002670 }
2671
2672
Mathias Agopian3559b072012-08-15 13:46:03 -07002673 /*
2674 * Perform our own transaction if needed
2675 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002676
2677 if (mLayersAdded) {
2678 mLayersAdded = false;
2679 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002680 mVisibleRegionsDirty = true;
2681 }
2682
2683 // some layers might have been removed, so
2684 // we need to update the regions they're exposing.
2685 if (mLayersRemoved) {
2686 mLayersRemoved = false;
2687 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002688 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002690 // this layer is not visible anymore
2691 // TODO: we could traverse the tree from front to back and
2692 // compute the actual visible region
2693 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 Region visibleReg;
2695 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002696 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002697 }
Robert Carr2047fae2016-11-28 14:09:09 -08002698 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 }
2700
2701 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002702
2703 updateCursorAsync();
2704}
2705
2706void SurfaceFlinger::updateCursorAsync()
2707{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002708 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002710 continue;
2711 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2714 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002715 }
2716 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717}
2718
2719void SurfaceFlinger::commitTransaction()
2720{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002721 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002722 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 for (const auto& l : mLayersPendingRemoval) {
2724 recordBufferingStats(l->getName().string(),
2725 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002726
2727 // We need to release the HWC layers when the Layer is removed
2728 // from the current state otherwise the HWC layer just continues
2729 // showing at its last configured state until we eventually
2730 // abandon the buffer queue.
2731 if (l->isRemovedFromCurrentState()) {
2732 l->destroyAllHwcLayers();
Robert Carr3aee9892018-11-07 12:53:41 -08002733 // destroyAllHwcLayers traverses to children, but releasePendingBuffer
2734 // doesn't in other scenarios. So we have to traverse explicitly here.
2735 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
2736 child->releasePendingBuffer(systemTime());
2737 });
Robert Carr2e102c92018-10-23 12:11:15 -07002738 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 }
2740 mLayersPendingRemoval.clear();
2741 }
2742
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002743 // If this transaction is part of a window animation then the next frame
2744 // we composite should be considered an animation as well.
2745 mAnimCompositionPending = mAnimTransactionPending;
2746
Mathias Agopian4fec8732012-06-29 14:12:52 -07002747 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002748 // clear the "changed" flags in current state
2749 mCurrentState.colorMatrixChanged = false;
2750
Robert Carr1f0a16a2016-10-24 16:27:39 -07002751 mDrawingState.traverseInZOrder([](Layer* layer) {
2752 layer->commitChildList();
2753 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002754 mTransactionPending = false;
2755 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002756 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757}
2758
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2760 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002761 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002763
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 Region aboveOpaqueLayers;
2765 Region aboveCoveredLayers;
2766 Region dirty;
2767
Mathias Agopian87baae12012-07-31 12:38:26 -07002768 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769
Robert Carr2047fae2016-11-28 14:09:09 -08002770 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002772 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Jesse Hall01e29052013-02-19 16:13:35 -08002774 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002775 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002776 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002777 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002778
Mathias Agopianab028732010-03-16 16:41:46 -07002779 /*
2780 * opaqueRegion: area of a surface that is fully opaque.
2781 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002783
2784 /*
2785 * visibleRegion: area of a surface that is visible on screen
2786 * and not fully transparent. This is essentially the layer's
2787 * footprint minus the opaque regions above it.
2788 * Areas covered by a translucent surface are considered visible.
2789 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002791
2792 /*
2793 * coveredRegion: area of a surface that is covered by all
2794 * visible regions above it (which includes the translucent areas).
2795 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002797
Jesse Halla8026d22012-09-25 13:25:04 -07002798 /*
2799 * transparentRegion: area of a surface that is hinted to be completely
2800 * transparent. This is only used to tell when the layer has no visible
2801 * non-transparent regions and can be removed from the layer list. It
2802 * does not affect the visibleRegion of this layer or any layers
2803 * beneath it. The hint may not be correct if apps don't respect the
2804 * SurfaceView restrictions (which, sadly, some don't).
2805 */
2806 Region transparentRegion;
2807
Mathias Agopianab028732010-03-16 16:41:46 -07002808
2809 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002810 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002811 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002812 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002814 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002815 if (!visibleRegion.isEmpty()) {
2816 // Remove the transparent area from the visible region
2817 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002818 if (tr.preserveRects()) {
2819 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002820 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002821 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002822 // transformation too complex, can't do the
2823 // transparent region optimization.
2824 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 }
Mathias Agopianab028732010-03-16 16:41:46 -07002826 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827
Mathias Agopianab028732010-03-16 16:41:46 -07002828 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002829 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002830 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002831 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002832 // the opaque region is the layer's footprint
2833 opaqueRegion = visibleRegion;
2834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 }
2836 }
2837
Robert Carre5f4f692018-01-12 13:12:28 -08002838 if (visibleRegion.isEmpty()) {
2839 layer->clearVisibilityRegions();
2840 return;
2841 }
2842
Mathias Agopianab028732010-03-16 16:41:46 -07002843 // Clip the covered region to the visible region
2844 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2845
2846 // Update aboveCoveredLayers for next (lower) layer
2847 aboveCoveredLayers.orSelf(visibleRegion);
2848
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 // subtract the opaque region covered by the layers above us
2850 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851
2852 // compute this layer's dirty region
2853 if (layer->contentDirty) {
2854 // we need to invalidate the whole region
2855 dirty = visibleRegion;
2856 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002857 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 layer->contentDirty = false;
2859 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002860 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002861 * the exposed region consists of two components:
2862 * 1) what's VISIBLE now and was COVERED before
2863 * 2) what's EXPOSED now less what was EXPOSED before
2864 *
2865 * note that (1) is conservative, we start with the whole
2866 * visible region but only keep what used to be covered by
2867 * something -- which mean it may have been exposed.
2868 *
2869 * (2) handles areas that were not covered by anything but got
2870 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002871 */
Mathias Agopianab028732010-03-16 16:41:46 -07002872 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002873 const Region oldVisibleRegion = layer->visibleRegion;
2874 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002875 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2876 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 }
2878 dirty.subtractSelf(aboveOpaqueLayers);
2879
2880 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002881 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Mathias Agopianab028732010-03-16 16:41:46 -07002883 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002885
Jesse Halla8026d22012-09-25 13:25:04 -07002886 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 layer->setVisibleRegion(visibleRegion);
2888 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002889 layer->setVisibleNonTransparentRegion(
2890 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002891 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892
Mathias Agopian87baae12012-07-31 12:38:26 -07002893 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894}
2895
Chia-I Wuab0c3192017-08-01 11:29:00 -07002896void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002897 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002898 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2899 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002900 }
2901 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002902}
2903
Dan Stoza6b9454d2014-11-07 16:00:59 -08002904bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002906 ALOGV("handlePageFlip");
2907
Brian Andersond6927fb2016-07-23 23:37:30 -07002908 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002911 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002912 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002913
2914 // Store the set of layers that need updates. This set must not change as
2915 // buffers are being latched, as this could result in a deadlock.
2916 // Example: Two producers share the same command stream and:
2917 // 1.) Layer 0 is latched
2918 // 2.) Layer 0 gets a new frame
2919 // 2.) Layer 1 gets a new frame
2920 // 3.) Layer 1 is latched.
2921 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2922 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002923 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002924 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002925 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002926 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2927 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002928 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002929 } else {
2930 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002931 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002932 } else {
2933 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002934 }
Robert Carr2047fae2016-11-28 14:09:09 -08002935 });
2936
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002938 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002939 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002940 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002941 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002942 newDataLatched = true;
2943 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002944 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002945
Alec Mouri86770e52018-09-24 22:40:58 +00002946 // Clear the renderengine fence here...
2947 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2948 // clear instead of sp::clear.
2949 getBE().flushFence = Fence::NO_FENCE;
2950
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002951 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002952
2953 // If we will need to wake up at some time in the future to deal with a
2954 // queued frame that shouldn't be displayed during this vsync period, wake
2955 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002956 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002957 signalLayerUpdate();
2958 }
2959
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002960 // enter boot animation on first buffer latch
2961 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2962 ALOGI("Enter boot animation");
2963 mBootStage = BootStage::BOOTANIMATION;
2964 }
2965
Dan Stoza6b9454d2014-11-07 16:00:59 -08002966 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002967 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968}
2969
Mathias Agopianad456f92011-01-13 17:53:01 -08002970void SurfaceFlinger::invalidateHwcGeometry()
2971{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002973}
2974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2976 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002977 // We only need to actually compose the display if:
2978 // 1) It is being handled by hardware composer, which may need this to
2979 // keep its virtual display state machine in sync, or
2980 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07002981 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002983 return;
2984 }
2985
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002987 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002988
2989 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991}
2992
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002993bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996 const Region bounds(display->bounds());
2997 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002998 const auto displayId = display->getId();
2999 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003000 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003001
Peiyong Lind3788632018-09-18 16:01:31 -07003002 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003004 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003005
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 if (hasClientComposition) {
3007 ALOGV("hasClientComposition");
3008
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003009 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003010 if (display->hasWideColorGamut()) {
3011 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003012 }
3013 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003014 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003016
Dominik Laskowski7e045462018-05-30 13:02:02 -07003017 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003018 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3019 HWC2::Capability::SkipClientColorTransform);
3020
Peiyong Lind3788632018-09-18 16:01:31 -07003021 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003022 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3023 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003024 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003025 }
3026
Chia-I Wud49d6692018-06-27 07:17:41 +08003027 // The current enhanced saturation matrix is designed to enhance Display P3,
3028 // thus we only apply this matrix when the render intent is not colorimetric
3029 // and the output color space is Display P3.
3030 needsEnhancedColorMatrix =
3031 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3032 outputDataspace == Dataspace::DISPLAY_P3);
3033 if (needsEnhancedColorMatrix) {
3034 colorMatrix *= mEnhancedSaturationMatrix;
3035 }
3036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003038 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003039 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003040 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003041
3042 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003043 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3044 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3045 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003046 }
3047 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003048 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003049
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003050 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003052 // when using overlays, we assume a fully transparent framebuffer
3053 // NOTE: we could reduce how much we need to clear, for instance
3054 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003055 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003056 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003057 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003058 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003059 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003060 // we're left with the letterbox region
3061 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003062 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003063
3064 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003065 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003066
Mathias Agopianb9494d52012-04-18 02:28:45 -07003067 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003068 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003069 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003070 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003071 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003072 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003073
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003074 const Rect& bounds = display->getBounds();
3075 const Rect& scissor = display->getScissor();
3076 if (scissor != bounds) {
3077 // scissor doesn't match the screen's dimensions, so we
3078 // need to clear everything outside of it and enable
3079 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003080
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003081 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003082 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003083 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003084 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003085
Mathias Agopian85d751c2012-08-29 16:59:24 -07003086 /*
3087 * and then, render the layers targeted at the framebuffer
3088 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003089
Dan Stoza9e56aa02015-11-02 13:00:03 -08003090 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003091 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003092 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003093 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003094 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003095 displayTransform.transform(layer->visibleRegion)));
3096 ALOGV("Layer: %s", layer->getName().string());
3097 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003098 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003099 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 case HWC2::Composition::Cursor:
3101 case HWC2::Composition::Device:
3102 case HWC2::Composition::Sideband:
3103 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003104 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003105 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003106 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003107 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3108 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003109 // never clear the very first layer since we're
3110 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003111 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003112 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003114 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003115 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003116 if (layer->hasColorTransform()) {
3117 mat4 tmpMatrix;
3118 if (applyColorMatrix) {
3119 tmpMatrix = mDrawingState.colorMatrix;
3120 }
3121 tmpMatrix *= layer->getColorTransform();
3122 if (needsEnhancedColorMatrix) {
3123 tmpMatrix *= mEnhancedSaturationMatrix;
3124 }
3125 getRenderEngine().setColorTransform(tmpMatrix);
3126 } else {
3127 getRenderEngine().setColorTransform(colorMatrix);
3128 }
David Sodmanc1498e62018-09-12 14:36:26 -07003129 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003130 break;
3131 }
3132 default:
3133 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003134 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003135 } else {
3136 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003137 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003138 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003139 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003140
Peiyong Lind3788632018-09-18 16:01:31 -07003141 // Clear color transform matrix at the end of the frame.
3142 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003143
Mathias Agopianf45c5102012-10-24 16:29:17 -07003144 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003145 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003146 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147}
3148
Chia-I Wu28e3a252018-09-07 12:05:02 -07003149void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003150 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003151 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152}
3153
Dan Stoza7d89d062015-04-30 13:29:25 -07003154status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003155 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003156 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003157 const sp<Layer>& lbc,
3158 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003159{
Dan Stoza7d89d062015-04-30 13:29:25 -07003160 // add this layer to the current state list
3161 {
3162 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003163 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003164 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3165 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003166 return NO_MEMORY;
3167 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 if (parent == nullptr) {
3169 mCurrentState.layersSortedByZ.add(lbc);
3170 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003171 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003172 ALOGE("addClientLayer called with a removed parent");
3173 return NAME_NOT_FOUND;
3174 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 parent->addChild(lbc);
3176 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003177
Yiwei Zhang243b3782018-05-15 17:40:04 -07003178 if (gbc != nullptr) {
3179 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3180 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3181 mMaxGraphicBufferProducerListSize,
3182 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3183 mGraphicBufferProducerList.size(),
3184 mMaxGraphicBufferProducerListSize, mNumLayers);
3185 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003186 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003187 }
3188
Mathias Agopian96f08192010-06-02 23:28:45 -07003189 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003190 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003191
Dan Stoza7d89d062015-04-30 13:29:25 -07003192 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003193}
3194
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003195status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003196 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003197 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3198}
Robert Carr7f9b8992017-03-10 11:08:39 -08003199
Robert Carr2e102c92018-10-23 12:11:15 -07003200status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003201 bool topLevelOnly) {
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 Wu515dc9c2017-06-15 12:53:59 -07003205 if (topLevelOnly) {
3206 return NO_ERROR;
3207 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003208 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003209 } else {
3210 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003211 }
3212
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003213 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003214
3215 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003216 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217}
3218
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003219uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003220 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003221}
3222
Mathias Agopian3f844832013-08-07 21:24:32 -07003223uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003224 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225}
3226
Mathias Agopian3f844832013-08-07 21:24:32 -07003227uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003228 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003229}
3230
3231uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003232 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003233 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003234 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003236 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 }
3238 return old;
3239}
3240
chaviwca27f252018-02-06 16:46:39 -08003241bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3242 for (const ComposerState& state : states) {
3243 // Here we need to check that the interface we're given is indeed
3244 // one of our own. A malicious client could give us a nullptr
3245 // IInterface, or one of its own or even one of our own but a
3246 // different type. All these situations would cause us to crash.
3247 if (state.client == nullptr) {
3248 return true;
3249 }
3250
3251 sp<IBinder> binder = IInterface::asBinder(state.client);
3252 if (binder == nullptr) {
3253 return true;
3254 }
3255
3256 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3257 return true;
3258 }
3259 }
3260 return false;
3261}
3262
Mathias Agopian8b33f032012-07-24 20:43:54 -07003263void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003264 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003265 const Vector<DisplayState>& displays,
3266 uint32_t flags)
3267{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003268 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003269 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003270 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003271
chaviwca27f252018-02-06 16:46:39 -08003272 if (containsAnyInvalidClientState(states)) {
3273 return;
3274 }
3275
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003276 if (flags & eAnimation) {
3277 // For window updates that are part of an animation we must wait for
3278 // previous animation "frames" to be handled.
3279 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003280 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003281 if (CC_UNLIKELY(err != NO_ERROR)) {
3282 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003283 // caller after a few seconds.
3284 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3285 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003286 mAnimTransactionPending = false;
3287 break;
3288 }
3289 }
3290 }
3291
chaviwca27f252018-02-06 16:46:39 -08003292 for (const DisplayState& display : displays) {
3293 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003294 }
3295
chaviwca27f252018-02-06 16:46:39 -08003296 for (const ComposerState& state : states) {
3297 transactionFlags |= setClientStateLocked(state);
3298 }
3299
3300 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3301 // as destroyed should only occur after setting all other states. This is to allow for a
3302 // child re-parent to happen before marking its original parent as destroyed (which would
3303 // then mark the child as destroyed).
3304 for (const ComposerState& state : states) {
3305 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003306 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003307
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003308 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3309 // anyway. This can be used as a flush mechanism for previous async transactions.
3310 // Empty animation transaction can be used to simulate back-pressure, so also force a
3311 // transaction for empty animation transactions.
3312 if (transactionFlags == 0 &&
3313 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003314 transactionFlags = eTransactionNeeded;
3315 }
3316
Mathias Agopian386aa982011-11-07 21:58:03 -08003317 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003318 if (mInterceptor->isEnabled()) {
3319 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003320 }
Irvel468051e2016-06-13 16:44:44 -07003321
Mathias Agopian386aa982011-11-07 21:58:03 -08003322 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003323 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3324 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003325 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003326
3327 // if this is a synchronous transaction, wait for it to take effect
3328 // before returning.
3329 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003330 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003331 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003332 if (flags & eAnimation) {
3333 mAnimTransactionPending = true;
3334 }
3335 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003336 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3337 if (CC_UNLIKELY(err != NO_ERROR)) {
3338 // just in case something goes wrong in SF, return to the
3339 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3341 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003342 break;
3343 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003344 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003345 }
3346}
3347
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003348uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3349 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3350 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003351
Mathias Agopiane57f2922012-08-09 16:29:12 -07003352 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003353 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3354
3355 const uint32_t what = s.what;
3356 if (what & DisplayState::eSurfaceChanged) {
3357 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3358 state.surface = s.surface;
3359 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003360 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003361 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003362 if (what & DisplayState::eLayerStackChanged) {
3363 if (state.layerStack != s.layerStack) {
3364 state.layerStack = s.layerStack;
3365 flags |= eDisplayTransactionNeeded;
3366 }
3367 }
3368 if (what & DisplayState::eDisplayProjectionChanged) {
3369 if (state.orientation != s.orientation) {
3370 state.orientation = s.orientation;
3371 flags |= eDisplayTransactionNeeded;
3372 }
3373 if (state.frame != s.frame) {
3374 state.frame = s.frame;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 if (state.viewport != s.viewport) {
3378 state.viewport = s.viewport;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 }
3382 if (what & DisplayState::eDisplaySizeChanged) {
3383 if (state.width != s.width) {
3384 state.width = s.width;
3385 flags |= eDisplayTransactionNeeded;
3386 }
3387 if (state.height != s.height) {
3388 state.height = s.height;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 }
3392
Mathias Agopiane57f2922012-08-09 16:29:12 -07003393 return flags;
3394}
3395
Robert Carrd4ae7f32018-06-07 16:10:57 -07003396bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3397 IPCThreadState* ipc = IPCThreadState::self();
3398 const int pid = ipc->getCallingPid();
3399 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003400 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003401 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003402 return false;
3403 }
3404 return true;
3405}
3406
chaviwca27f252018-02-06 16:46:39 -08003407uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3408 const layer_state_t& s = composerState.state;
3409 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3410
Mathias Agopian13127d82013-03-05 17:47:11 -08003411 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003412 if (layer == nullptr) {
3413 return 0;
3414 }
3415
chaviw8b3871a2017-11-01 17:41:01 -07003416 uint32_t flags = 0;
3417
3418 const uint32_t what = s.what;
3419 bool geometryAppliesWithResize =
3420 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003421
3422 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3423 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003424 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003425 layer->pushPendingState();
3426 }
3427
chaviw8b3871a2017-11-01 17:41:01 -07003428 if (what & layer_state_t::ePositionChanged) {
3429 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3430 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 }
3433 if (what & layer_state_t::eLayerChanged) {
3434 // NOTE: index needs to be calculated before we update the state
3435 const auto& p = layer->getParent();
3436 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003437 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003438 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003439 mCurrentState.layersSortedByZ.removeAt(idx);
3440 mCurrentState.layersSortedByZ.add(layer);
3441 // we need traversal (state changed)
3442 // AND transaction (list changed)
3443 flags |= eTransactionNeeded|eTraversalNeeded;
3444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 } else {
3446 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003447 flags |= eTransactionNeeded|eTraversalNeeded;
3448 }
3449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 }
3451 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003452 // NOTE: index needs to be calculated before we update the state
3453 const auto& p = layer->getParent();
3454 if (p == nullptr) {
3455 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3456 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3457 mCurrentState.layersSortedByZ.removeAt(idx);
3458 mCurrentState.layersSortedByZ.add(layer);
3459 // we need traversal (state changed)
3460 // AND transaction (list changed)
3461 flags |= eTransactionNeeded|eTraversalNeeded;
3462 }
3463 } else {
3464 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3465 flags |= eTransactionNeeded|eTraversalNeeded;
3466 }
chaviw8b3871a2017-11-01 17:41:01 -07003467 }
3468 }
3469 if (what & layer_state_t::eSizeChanged) {
3470 if (layer->setSize(s.w, s.h)) {
3471 flags |= eTraversalNeeded;
3472 }
3473 }
3474 if (what & layer_state_t::eAlphaChanged) {
3475 if (layer->setAlpha(s.alpha))
3476 flags |= eTraversalNeeded;
3477 }
3478 if (what & layer_state_t::eColorChanged) {
3479 if (layer->setColor(s.color))
3480 flags |= eTraversalNeeded;
3481 }
Peiyong Lind3788632018-09-18 16:01:31 -07003482 if (what & layer_state_t::eColorTransformChanged) {
3483 if (layer->setColorTransform(s.colorTransform)) {
3484 flags |= eTraversalNeeded;
3485 }
3486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003488 // TODO: b/109894387
3489 //
3490 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3491 // rotation. To see the problem observe that if we have a square parent, and a child
3492 // of the same size, then we rotate the child 45 degrees around it's center, the child
3493 // must now be cropped to a non rectangular 8 sided region.
3494 //
3495 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3496 // private API, and the WindowManager only uses rotation in one case, which is on a top
3497 // level layer in which cropping is not an issue.
3498 //
3499 // However given that abuse of rotation matrices could lead to surfaces extending outside
3500 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3501 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3502 // transformations.
3503 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003504 flags |= eTraversalNeeded;
3505 }
3506 if (what & layer_state_t::eTransparentRegionChanged) {
3507 if (layer->setTransparentRegionHint(s.transparentRegion))
3508 flags |= eTraversalNeeded;
3509 }
3510 if (what & layer_state_t::eFlagsChanged) {
3511 if (layer->setFlags(s.flags, s.mask))
3512 flags |= eTraversalNeeded;
3513 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003514 if (what & layer_state_t::eCropChanged_legacy) {
3515 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003516 flags |= eTraversalNeeded;
3517 }
chaviw8b3871a2017-11-01 17:41:01 -07003518 if (what & layer_state_t::eLayerStackChanged) {
3519 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3520 // We only allow setting layer stacks for top level layers,
3521 // everything else inherits layer stack from its parent.
3522 if (layer->hasParent()) {
3523 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3524 layer->getName().string());
3525 } else if (idx < 0) {
3526 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3527 "that also does not appear in the top level layer list. Something"
3528 " has gone wrong.", layer->getName().string());
3529 } else if (layer->setLayerStack(s.layerStack)) {
3530 mCurrentState.layersSortedByZ.removeAt(idx);
3531 mCurrentState.layersSortedByZ.add(layer);
3532 // we need traversal (state changed)
3533 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003534 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003535 }
3536 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003537 if (what & layer_state_t::eDeferTransaction_legacy) {
3538 if (s.barrierHandle_legacy != nullptr) {
3539 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3540 } else if (s.barrierGbp_legacy != nullptr) {
3541 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003542 if (authenticateSurfaceTextureLocked(gbp)) {
3543 const auto& otherLayer =
3544 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003545 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003546 } else {
3547 ALOGE("Attempt to defer transaction to to an"
3548 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003549 }
3550 }
chaviw8b3871a2017-11-01 17:41:01 -07003551 // We don't trigger a traversal here because if no other state is
3552 // changed, we don't want this to cause any more work
3553 }
3554 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003555 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003556 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003557 if (!hadParent) {
3558 mCurrentState.layersSortedByZ.remove(layer);
3559 }
chaviw8b3871a2017-11-01 17:41:01 -07003560 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003561 }
chaviw8b3871a2017-11-01 17:41:01 -07003562 }
3563 if (what & layer_state_t::eReparentChildren) {
3564 if (layer->reparentChildren(s.reparentHandle)) {
3565 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003566 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003567 }
chaviw8b3871a2017-11-01 17:41:01 -07003568 if (what & layer_state_t::eDetachChildren) {
3569 layer->detachChildren();
3570 }
3571 if (what & layer_state_t::eOverrideScalingModeChanged) {
3572 layer->setOverrideScalingMode(s.overrideScalingMode);
3573 // We don't trigger a traversal here because if no other state is
3574 // changed, we don't want this to cause any more work
3575 }
Marissa Wall61c58622018-07-18 10:12:20 -07003576 if (what & layer_state_t::eTransformChanged) {
3577 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3578 }
3579 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3580 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3581 flags |= eTraversalNeeded;
3582 }
3583 if (what & layer_state_t::eCropChanged) {
3584 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eBufferChanged) {
3587 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eAcquireFenceChanged) {
3590 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3591 }
3592 if (what & layer_state_t::eDataspaceChanged) {
3593 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eHdrMetadataChanged) {
3596 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3597 }
3598 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3599 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3600 }
3601 if (what & layer_state_t::eApiChanged) {
3602 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3603 }
3604 if (what & layer_state_t::eSidebandStreamChanged) {
3605 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3606 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003607 return flags;
3608}
3609
chaviwca27f252018-02-06 16:46:39 -08003610void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3611 const layer_state_t& state = composerState.state;
3612 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3613
3614 sp<Layer> layer(client->getLayerUser(state.surface));
3615 if (layer == nullptr) {
3616 return;
3617 }
3618
chaviwca27f252018-02-06 16:46:39 -08003619 if (state.what & layer_state_t::eDestroySurface) {
3620 removeLayerLocked(mStateLock, layer);
3621 }
3622}
3623
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003625 const String8& name,
3626 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003628 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003629 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003631 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003632 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003633 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003634 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003635 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003636
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003637 status_t result = NO_ERROR;
3638
3639 sp<Layer> layer;
3640
Cody Northropbc755282017-03-31 12:00:08 -06003641 String8 uniqueName = getUniqueLayerName(name);
3642
Mathias Agopian3165cc22012-08-08 19:42:09 -07003643 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003644 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003645 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3646 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003649 case ISurfaceComposerClient::eFXSurfaceBufferState:
3650 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3651 break;
chaviw13fdc492017-06-27 12:40:18 -07003652 case ISurfaceComposerClient::eFXSurfaceColor:
3653 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003654 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003655 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003656 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003657 case ISurfaceComposerClient::eFXSurfaceContainer:
3658 result = createContainerLayer(client,
3659 uniqueName, w, h, flags,
3660 handle, &layer);
3661 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003662 default:
3663 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003664 break;
3665 }
3666
Dan Stoza7d89d062015-04-30 13:29:25 -07003667 if (result != NO_ERROR) {
3668 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003670
Chia-I Wuab0c3192017-08-01 11:29:00 -07003671 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3672 // TODO b/64227542
3673 if (windowType == 441731) {
3674 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3675 layer->setPrimaryDisplayOnly();
3676 }
3677
Albert Chaulk479c60c2017-01-27 14:21:34 -05003678 layer->setInfo(windowType, ownerUid);
3679
Robert Carr1f0a16a2016-10-24 16:27:39 -07003680 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003681 if (result != NO_ERROR) {
3682 return result;
3683 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003684 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003685
3686 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688}
3689
Cody Northropbc755282017-03-31 12:00:08 -06003690String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3691{
3692 bool matchFound = true;
3693 uint32_t dupeCounter = 0;
3694
3695 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3696 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3697
Dan Stoza436ccf32018-06-21 12:10:12 -07003698 // Grab the state lock since we're accessing mCurrentState
3699 Mutex::Autolock lock(mStateLock);
3700
Cody Northropbc755282017-03-31 12:00:08 -06003701 // Loop over layers until we're sure there is no matching name
3702 while (matchFound) {
3703 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003704 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003705 if (layer->getName() == uniqueName) {
3706 matchFound = true;
3707 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3708 }
3709 });
3710 }
3711
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003712 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3713 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003714
3715 return uniqueName;
3716}
3717
Marissa Wallfd668622018-05-10 10:21:13 -07003718status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3719 uint32_t w, uint32_t h, uint32_t flags,
3720 PixelFormat& format, sp<IBinder>* handle,
3721 sp<IGraphicBufferProducer>* gbp,
3722 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003724 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725 case PIXEL_FORMAT_TRANSPARENT:
3726 case PIXEL_FORMAT_TRANSLUCENT:
3727 format = PIXEL_FORMAT_RGBA_8888;
3728 break;
3729 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003730 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 break;
3732 }
3733
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003734 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003735 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003736 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003737 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003738 *handle = layer->getHandle();
3739 *gbp = layer->getProducer();
3740 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003742
Marissa Wallfd668622018-05-10 10:21:13 -07003743 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745}
3746
Marissa Wall61c58622018-07-18 10:12:20 -07003747status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3748 uint32_t w, uint32_t h, uint32_t flags,
3749 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003750 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003751 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003752 *handle = layer->getHandle();
3753 *outLayer = layer;
3754
3755 return NO_ERROR;
3756}
3757
chaviw13fdc492017-06-27 12:40:18 -07003758status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003759 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003760 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003761{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003762 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003763 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003765}
3766
Robert Carr6b3f6c52018-08-13 13:05:17 -07003767status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3768 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3769 sp<IBinder>* handle, sp<Layer>* outLayer)
3770{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003771 *outLayer =
3772 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003773 *handle = (*outLayer)->getHandle();
3774 return NO_ERROR;
3775}
3776
3777
Mathias Agopianac9fa422013-02-11 16:40:36 -08003778status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003779{
Robert Carr9524cb32017-02-13 11:32:32 -08003780 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003781 status_t err = NO_ERROR;
3782 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003783 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003784 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003785 err = removeLayer(l);
3786 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3787 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003788 }
3789 return err;
3790}
3791
Robert Carr2e102c92018-10-23 12:11:15 -07003792void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3793 mLayersPendingRemoval.add(layer);
3794 mLayersRemoved = true;
3795 setTransactionFlags(eTransactionNeeded);
3796}
3797
3798void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003799{
Robert Carr2e102c92018-10-23 12:11:15 -07003800 Mutex::Autolock lock(mStateLock);
3801 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003802}
3803
Mathias Agopianb60314a2012-04-10 22:09:54 -07003804// ---------------------------------------------------------------------------
3805
Andy McFadden13a082e2012-08-24 10:16:42 -07003806void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003807 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003808 if (!displayToken) return;
3809
Jesse Hall01e29052013-02-19 16:13:35 -08003810 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003811 Vector<ComposerState> state;
3812 Vector<DisplayState> displays;
3813 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003814 d.what = DisplayState::eDisplayProjectionChanged |
3815 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003816 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003817 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003818 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003819 d.frame.makeInvalid();
3820 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003821 d.width = 0;
3822 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003823 displays.add(d);
3824 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003825
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003826 const auto display = getDisplayDevice(displayToken);
3827 if (!display) return;
3828
3829 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3830
Dominik Laskowski075d3172018-05-24 15:50:06 -07003831 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003832 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003833 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003834
Brian Andersond0010582017-03-07 13:20:31 -08003835 // Use phase of 0 since phase is not known.
3836 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003837 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3838 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003839}
3840
3841void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003842 // Async since we may be called from the main thread.
3843 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003844}
3845
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003846void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3847 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003848 if (display->isVirtual()) {
3849 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003850 return;
3851 }
3852
Dominik Laskowski075d3172018-05-24 15:50:06 -07003853 const auto displayId = display->getId();
3854 LOG_ALWAYS_FATAL_IF(!displayId);
3855
Dominik Laskowski34157762018-10-31 13:07:19 -07003856 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003857
3858 int currentMode = display->getPowerMode();
3859 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003860 return;
3861 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003862
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003863 display->setPowerMode(mode);
3864
Lloyd Pique4dccc412018-01-22 17:21:36 -08003865 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003866 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003867 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003868 if (idx < 0) {
3869 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3870 return;
3871 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003872 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003873 }
3874
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003875 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003876 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003877 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003878 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003879 if (mUseScheduler) {
3880 mScheduler->onScreenAcquired(mAppConnectionHandle);
3881 } else {
3882 mEventThread->onScreenAcquired();
3883 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003884 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003887 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003888 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003889 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003890
3891 struct sched_param param = {0};
3892 param.sched_priority = 1;
3893 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3894 ALOGW("Couldn't set SCHED_FIFO on display on");
3895 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003896 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003897 // Turn off the display
3898 struct sched_param param = {0};
3899 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3900 ALOGW("Couldn't set SCHED_OTHER on display off");
3901 }
3902
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003903 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003904 if (mUseScheduler) {
3905 mScheduler->disableHardwareVsync(true);
3906 } else {
3907 disableHardwareVsync(true); // also cancels any in-progress resync
3908 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003909 if (mUseScheduler) {
3910 mScheduler->onScreenReleased(mAppConnectionHandle);
3911 } else {
3912 mEventThread->onScreenReleased();
3913 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003914 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003915
Dominik Laskowski075d3172018-05-24 15:50:06 -07003916 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003917 mVisibleRegionsDirty = true;
3918 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003919 } else if (mode == HWC_POWER_MODE_DOZE ||
3920 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003921 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003922 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003923 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003924 if (mUseScheduler) {
3925 mScheduler->onScreenAcquired(mAppConnectionHandle);
3926 } else {
3927 mEventThread->onScreenAcquired();
3928 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003929 resyncToHardwareVsync(true);
3930 }
3931 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3932 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003933 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003934 if (mUseScheduler) {
3935 mScheduler->disableHardwareVsync(true);
3936 } else {
3937 disableHardwareVsync(true); // also cancels any in-progress resync
3938 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003939 if (mUseScheduler) {
3940 mScheduler->onScreenReleased(mAppConnectionHandle);
3941 } else {
3942 mEventThread->onScreenReleased();
3943 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003944 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003945 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003946 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003947 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003948 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003949 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003950
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003951 if (display->isPrimary()) {
3952 mTimeStats.setPowerMode(mode);
3953 }
3954
Dominik Laskowski34157762018-10-31 13:07:19 -07003955 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003956}
3957
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003958void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003959 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003960 const auto display = getDisplayDevice(displayToken);
3961 if (!display) {
3962 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3963 displayToken.get());
3964 } else if (display->isVirtual()) {
3965 ALOGW("Attempt to set power mode %d for virtual display", mode);
3966 } else {
3967 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003968 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003969 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003970}
3971
3972// ---------------------------------------------------------------------------
3973
Lloyd Pique755e3192018-01-31 16:46:15 -08003974status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3975 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003976 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003977
Mathias Agopianbd115332013-04-18 16:41:04 -07003978 IPCThreadState* ipc = IPCThreadState::self();
3979 const int pid = ipc->getCallingPid();
3980 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003981
Mathias Agopianbd115332013-04-18 16:41:04 -07003982 if ((uid != AID_SHELL) &&
3983 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003984 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003985 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003987 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003988 // (this would indicate SF is stuck, but we want to be able to
3989 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003990 status_t err = mStateLock.timedLock(s2ns(1));
3991 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003992 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003993 result.appendFormat(
3994 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3995 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003996 }
3997
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003998 bool dumpAll = true;
3999 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004000 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004001
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004002 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003 if ((index < numArgs) &&
4004 (args[index] == String16("--list"))) {
4005 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004006 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004007 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008 }
4009
4010 if ((index < numArgs) &&
4011 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004012 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004013 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004014 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004015 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004016
4017 if ((index < numArgs) &&
4018 (args[index] == String16("--latency-clear"))) {
4019 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004020 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004021 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004023
4024 if ((index < numArgs) &&
4025 (args[index] == String16("--dispsync"))) {
4026 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004027 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004028 dumpAll = false;
4029 }
Dan Stozab90cf072015-03-05 11:05:59 -08004030
4031 if ((index < numArgs) &&
4032 (args[index] == String16("--static-screen"))) {
4033 index++;
4034 dumpStaticScreenStats(result);
4035 dumpAll = false;
4036 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004037
4038 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004039 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004040 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004041 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004042 dumpAll = false;
4043 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004044
4045 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4046 index++;
4047 dumpWideColorInfo(result);
4048 dumpAll = false;
4049 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004050
4051 if ((index < numArgs) &&
4052 (args[index] == String16("--enable-layer-stats"))) {
4053 index++;
4054 mLayerStats.enable();
4055 dumpAll = false;
4056 }
4057
4058 if ((index < numArgs) &&
4059 (args[index] == String16("--disable-layer-stats"))) {
4060 index++;
4061 mLayerStats.disable();
4062 dumpAll = false;
4063 }
4064
4065 if ((index < numArgs) &&
4066 (args[index] == String16("--clear-layer-stats"))) {
4067 index++;
4068 mLayerStats.clear();
4069 dumpAll = false;
4070 }
4071
4072 if ((index < numArgs) &&
4073 (args[index] == String16("--dump-layer-stats"))) {
4074 index++;
4075 mLayerStats.dump(result);
4076 dumpAll = false;
4077 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004078
4079 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004080 (args[index] == String16("--frame-composition"))) {
4081 index++;
4082 dumpFrameCompositionInfo(result);
4083 dumpAll = false;
4084 }
4085
4086 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004087 (args[index] == String16("--display-identification"))) {
4088 index++;
4089 dumpDisplayIdentificationData(result);
4090 dumpAll = false;
4091 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004092
4093 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4094 index++;
4095 mTimeStats.parseArgs(asProto, args, index, result);
4096 dumpAll = false;
4097 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004098 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004099
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004100 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004101 if (asProto) {
4102 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4103 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4104 } else {
4105 dumpAllLocked(args, index, result);
4106 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004107 }
4108
Mathias Agopian9795c422009-08-26 16:36:26 -07004109 if (locked) {
4110 mStateLock.unlock();
4111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 }
4113 write(fd, result.string(), result.size());
4114 return NO_ERROR;
4115}
4116
Dan Stozac7014012014-02-14 15:03:43 -08004117void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4118 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004119{
Robert Carr2047fae2016-11-28 14:09:09 -08004120 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004121 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004122 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004123}
4124
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004125void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004126 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004127{
4128 String8 name;
4129 if (index < args.size()) {
4130 name = String8(args[index]);
4131 index++;
4132 }
4133
Dominik Laskowski075d3172018-05-24 15:50:06 -07004134 if (const auto displayId = getInternalDisplayId();
4135 displayId && getHwComposer().isConnected(*displayId)) {
4136 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004137 const nsecs_t period = activeConfig->getVsyncPeriod();
4138 result.appendFormat("%" PRId64 "\n", period);
4139 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004140
4141 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004142 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004143 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004144 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004145 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004146 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004147 }
Robert Carr2047fae2016-11-28 14:09:09 -08004148 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 }
4150}
4151
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004152void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004153 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004154{
4155 String8 name;
4156 if (index < args.size()) {
4157 name = String8(args[index]);
4158 index++;
4159 }
4160
Robert Carr2047fae2016-11-28 14:09:09 -08004161 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004162 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004163 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004164 }
Robert Carr2047fae2016-11-28 14:09:09 -08004165 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004166
Svetoslavd85084b2014-03-20 10:28:31 -07004167 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004168}
4169
Jamie Gennis6547ff42013-07-16 20:12:42 -07004170// This should only be called from the main thread. Otherwise it would need
4171// the lock and should use mCurrentState rather than mDrawingState.
4172void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004173 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004174 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004175 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004176
4177 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4178}
4179
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004180void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004181{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004182 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004183
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004184 if (isLayerTripleBufferingDisabled())
4185 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004186
4187 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004188 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004189 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004190 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004191 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4192 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004193 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004194}
4195
Dan Stozab90cf072015-03-05 11:05:59 -08004196void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4197{
4198 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004199 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4200 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004201 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004202 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004203 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4204 b + 1, bucketTimeSec, percent);
4205 }
David Sodman4a36e932017-11-07 14:29:47 -08004206 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004207 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004208 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004209 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004210 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004211}
4212
Dan Stozae77c7662016-05-13 11:37:28 -07004213void SurfaceFlinger::recordBufferingStats(const char* layerName,
4214 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004215 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4216 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004217 for (const auto& segment : history) {
4218 if (!segment.usedThirdBuffer) {
4219 stats.twoBufferTime += segment.totalTime;
4220 }
4221 if (segment.occupancyAverage < 1.0f) {
4222 stats.doubleBufferedTime += segment.totalTime;
4223 } else if (segment.occupancyAverage < 2.0f) {
4224 stats.tripleBufferedTime += segment.totalTime;
4225 }
4226 ++stats.numSegments;
4227 stats.totalTime += segment.totalTime;
4228 }
4229}
4230
Brian Andersond6927fb2016-07-23 23:37:30 -07004231void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4232 result.appendFormat("Layer frame timestamps:\n");
4233
4234 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4235 const size_t count = currentLayers.size();
4236 for (size_t i=0 ; i<count ; i++) {
4237 currentLayers[i]->dumpFrameEvents(result);
4238 }
4239}
4240
Dan Stozae77c7662016-05-13 11:37:28 -07004241void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4242 result.append("Buffering stats:\n");
4243 result.append(" [Layer name] <Active time> <Two buffer> "
4244 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004245 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004246 typedef std::tuple<std::string, float, float, float> BufferTuple;
4247 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004248 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004249 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004250 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004251 if (stats.numSegments == 0) {
4252 continue;
4253 }
4254 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4255 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4256 stats.totalTime;
4257 float doubleBufferRatio = static_cast<float>(
4258 stats.doubleBufferedTime) / stats.totalTime;
4259 float tripleBufferRatio = static_cast<float>(
4260 stats.tripleBufferedTime) / stats.totalTime;
4261 sorted.insert({activeTime, {name, twoBufferRatio,
4262 doubleBufferRatio, tripleBufferRatio}});
4263 }
4264 for (const auto& sortedPair : sorted) {
4265 float activeTime = sortedPair.first;
4266 const BufferTuple& values = sortedPair.second;
4267 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4268 std::get<0>(values).c_str(), activeTime,
4269 std::get<1>(values), std::get<2>(values),
4270 std::get<3>(values));
4271 }
4272 result.append("\n");
4273}
4274
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004275void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004276 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 const auto displayId = display->getId();
4278 if (!displayId) {
4279 continue;
4280 }
4281 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004282 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004283 continue;
4284 }
4285
Dominik Laskowski34157762018-10-31 13:07:19 -07004286 result.appendFormat("Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
Dominik Laskowski075d3172018-05-24 15:50:06 -07004287 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004288 uint8_t port;
4289 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004290 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004291 result.append("no identification data\n");
4292 continue;
4293 }
4294
4295 if (!isEdid(data)) {
4296 result.append("unknown identification data: ");
4297 for (uint8_t byte : data) {
4298 result.appendFormat("%x ", byte);
4299 }
4300 result.append("\n");
4301 continue;
4302 }
4303
4304 const auto edid = parseEdid(data);
4305 if (!edid) {
4306 result.append("invalid EDID: ");
4307 for (uint8_t byte : data) {
4308 result.appendFormat("%x ", byte);
4309 }
4310 result.append("\n");
4311 continue;
4312 }
4313
4314 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4315 result.append(edid->displayName.data(), edid->displayName.length());
4316 result.append("\"\n");
4317 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004318}
4319
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004320void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004321 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4322 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004323 result.appendFormat("DisplayColorSetting: %s\n",
4324 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004325
4326 // TODO: print out if wide-color mode is active or not
4327
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004328 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004329 const auto displayId = display->getId();
4330 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004331 continue;
4332 }
4333
Dominik Laskowski34157762018-10-31 13:07:19 -07004334 result.appendFormat("Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004335 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004336 for (auto&& mode : modes) {
4337 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4338 }
4339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004340 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004341 result.appendFormat(" Current color mode: %s (%d)\n",
4342 decodeColorMode(currentMode).c_str(), currentMode);
4343 }
4344 result.append("\n");
4345}
4346
David Sodman7e4ae112018-02-09 15:02:28 -08004347void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4348 std::string stringResult;
4349
4350 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004351 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4352 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004353 continue;
4354 }
4355
Dominik Laskowski05275f12018-11-01 15:03:24 -07004356 const auto& compositionInfoList = it->second;
4357 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004358 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4359 for (const auto& compositionInfo : compositionInfoList) {
4360 compositionInfo.dump(stringResult, nullptr);
4361 stringResult += base::StringPrintf("\n");
4362 }
4363 }
4364
4365 result.append(stringResult.c_str());
4366}
4367
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004368LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004369 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004370 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4371 const State& state = useDrawing ? mDrawingState : mCurrentState;
4372 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004373 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004374 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004375 });
4376
4377 return layersProto;
4378}
4379
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004380LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004381 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004382
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004383 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004384 resolution->set_w(display.getWidth());
4385 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004386
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004387 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4388 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4389 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004390
Dominik Laskowski075d3172018-05-24 15:50:06 -07004391 const auto displayId = display.getId();
4392 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004393 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004394 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004395 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004396 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004397 }
4398 });
4399
4400 return layersProto;
4401}
4402
Mathias Agopian74d211a2013-04-22 16:55:35 +02004403void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4404 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004406 bool colorize = false;
4407 if (index < args.size()
4408 && (args[index] == String16("--color"))) {
4409 colorize = true;
4410 index++;
4411 }
4412
4413 Colorizer colorizer(colorize);
4414
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415 // figure out if we're stuck somewhere
4416 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004417 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4419
4420 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004421 * Dump library configuration.
4422 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004423
4424 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004425 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004426 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004427 appendSfConfigString(result);
4428 appendUiConfigString(result);
4429 appendGuiConfigString(result);
4430 result.append("\n");
4431
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 result.append("\nDisplay identification data:\n");
4433 dumpDisplayIdentificationData(result);
4434
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004435 result.append("\nWide-Color information:\n");
4436 dumpWideColorInfo(result);
4437
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004438 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004439 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004440 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004441 result.append(SyncFeatures::getInstance().toString());
4442 result.append("\n");
4443
Andy McFadden41d67d72014-04-25 16:58:34 -07004444 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004445 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004446 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004447
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004448 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4449 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004450 if (const auto displayId = getInternalDisplayId();
4451 displayId && getHwComposer().isConnected(*displayId)) {
4452 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski34157762018-10-31 13:07:19 -07004453 result.appendFormat("Display %s: app phase %" PRId64 " ns, "
Dominik Laskowski075d3172018-05-24 15:50:06 -07004454 "sf phase %" PRId64 " ns, "
4455 "early app phase %" PRId64 " ns, "
4456 "early sf phase %" PRId64 " ns, "
4457 "early app gl phase %" PRId64 " ns, "
4458 "early sf gl phase %" PRId64 " ns, "
4459 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dominik Laskowski34157762018-10-31 13:07:19 -07004460 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4461 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
Dominik Laskowski075d3172018-05-24 15:50:06 -07004462 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004463 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004464 result.append("\n");
4465
Dan Stozab90cf072015-03-05 11:05:59 -08004466 // Dump static screen stats
4467 result.append("\n");
4468 dumpStaticScreenStats(result);
4469 result.append("\n");
4470
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004471 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4472
Dan Stozae77c7662016-05-13 11:37:28 -07004473 dumpBufferingStats(result);
4474
Andy McFadden4803b742012-09-24 19:07:20 -07004475 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004476 * Dump the visible layer list
4477 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004478 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004479 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004480 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4481 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004482 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004483
Chia-I Wu2f884132018-09-13 15:17:58 -07004484 {
4485 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4486 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4487 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4488 result.append("\n");
4489 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004490
David Sodman7e4ae112018-02-09 15:02:28 -08004491 result.append("\nFrame-Composition information:\n");
4492 dumpFrameCompositionInfo(result);
4493 result.append("\n");
4494
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004495 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004496 * Dump Display state
4497 */
4498
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004499 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004500 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004501 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004502 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004503 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004504 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004505 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004506
4507 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004508 * Dump SurfaceFlinger global state
4509 */
4510
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004511 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004512 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004513 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004514
David Sodmanbc815282017-11-05 18:57:52 -08004515 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004516
Dominik Laskowski075d3172018-05-24 15:50:06 -07004517 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004518 display->undefinedRegion.dump(result, "undefinedRegion");
4519 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4520 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004521 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004522 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004523 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004524 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004525
Dominik Laskowski075d3172018-05-24 15:50:06 -07004526 if (const auto displayId = getInternalDisplayId();
4527 displayId && getHwComposer().isConnected(*displayId)) {
4528 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004529 result.appendFormat(" refresh-rate : %f fps\n"
4530 " x-dpi : %f\n"
4531 " y-dpi : %f\n",
4532 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4533 activeConfig->getDpiY());
4534 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535
Mathias Agopian74d211a2013-04-22 16:55:35 +02004536 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004538
Ana Krulec98b5b242018-08-10 15:03:23 -07004539 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004540 /*
4541 * VSYNC state
4542 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004543 if (mUseScheduler) {
4544 mScheduler->dump(mAppConnectionHandle, result);
4545 } else {
4546 mEventThread->dump(result);
4547 }
Dan Stozae22aec72016-08-01 13:20:59 -07004548 result.append("\n");
4549
4550 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004551 * Tracing state
4552 */
4553 mTracing.dump(result);
4554 result.append("\n");
4555
4556 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004557 * HWC layer minidump
4558 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004559 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004560 const auto displayId = display->getId();
4561 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004562 continue;
4563 }
4564
Dominik Laskowski34157762018-10-31 13:07:19 -07004565 result.appendFormat("Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004566 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004567 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004568 result.append("\n");
4569 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004570
4571 /*
4572 * Dump HWComposer state
4573 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004574 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004575 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004576 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004577 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004578 result.appendFormat(" h/w composer %s\n",
4579 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004580 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004581
4582 /*
4583 * Dump gralloc state
4584 */
4585 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4586 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004587
4588 /*
4589 * Dump VrFlinger state if in use.
4590 */
4591 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4592 result.append("VrFlinger state:\n");
4593 result.append(mVrFlinger->Dump().c_str());
4594 result.append("\n");
4595 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004596}
4597
Dominik Laskowski075d3172018-05-24 15:50:06 -07004598const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004599 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004600 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004601 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004602 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004603 }
4604 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004605
Dominik Laskowski34157762018-10-31 13:07:19 -07004606 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004607 static const Vector<sp<Layer>> empty;
4608 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004609}
4610
Keun young Park63f165f2012-08-31 10:53:36 -07004611bool SurfaceFlinger::startDdmConnection()
4612{
4613 void* libddmconnection_dso =
4614 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4615 if (!libddmconnection_dso) {
4616 return false;
4617 }
4618 void (*DdmConnection_start)(const char* name);
4619 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004620 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004621 if (!DdmConnection_start) {
4622 dlclose(libddmconnection_dso);
4623 return false;
4624 }
4625 (*DdmConnection_start)(getServiceName());
4626 return true;
4627}
4628
Chia-I Wu28f320b2018-05-03 11:02:56 -07004629void SurfaceFlinger::updateColorMatrixLocked() {
4630 mat4 colorMatrix;
4631 if (mGlobalSaturationFactor != 1.0f) {
4632 // Rec.709 luma coefficients
4633 float3 luminance{0.213f, 0.715f, 0.072f};
4634 luminance *= 1.0f - mGlobalSaturationFactor;
4635 mat4 saturationMatrix = mat4(
4636 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4637 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4638 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4639 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4640 );
4641 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4642 } else {
4643 colorMatrix = mClientColorMatrix * mDaltonizer();
4644 }
4645
4646 if (mCurrentState.colorMatrix != colorMatrix) {
4647 mCurrentState.colorMatrix = colorMatrix;
4648 mCurrentState.colorMatrixChanged = true;
4649 setTransactionFlags(eTransactionNeeded);
4650 }
4651}
4652
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004653status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004654#pragma clang diagnostic push
4655#pragma clang diagnostic error "-Wswitch-enum"
4656 switch (static_cast<ISurfaceComposerTag>(code)) {
4657 // These methods should at minimum make sure that the client requested
4658 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004659 case BOOT_FINISHED:
4660 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004661 case CREATE_CONNECTION:
4662 case CREATE_DISPLAY:
4663 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004664 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004665 case GET_ACTIVE_COLOR_MODE:
4666 case GET_ANIMATION_FRAME_STATS:
4667 case GET_HDR_CAPABILITIES:
4668 case SET_ACTIVE_CONFIG:
4669 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004670 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004671 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004672 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4673 IPCThreadState* ipc = IPCThreadState::self();
4674 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4675 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004676 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004677 }
Robert Carr1db73f62016-12-21 12:58:51 -08004678 return OK;
4679 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004680 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004681 IPCThreadState* ipc = IPCThreadState::self();
4682 const int pid = ipc->getCallingPid();
4683 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004684 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4685 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004686 return PERMISSION_DENIED;
4687 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004688 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004689 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004690 // Used by apps to hook Choreographer to SurfaceFlinger.
4691 case CREATE_DISPLAY_EVENT_CONNECTION:
4692 // The following calls are currently used by clients that do not
4693 // request necessary permissions. However, they do not expose any secret
4694 // information, so it is OK to pass them.
4695 case AUTHENTICATE_SURFACE:
4696 case GET_ACTIVE_CONFIG:
4697 case GET_BUILT_IN_DISPLAY:
4698 case GET_DISPLAY_COLOR_MODES:
4699 case GET_DISPLAY_CONFIGS:
4700 case GET_DISPLAY_STATS:
4701 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4702 // Calling setTransactionState is safe, because you need to have been
4703 // granted a reference to Client* and Handle* to do anything with it.
4704 case SET_TRANSACTION_STATE:
4705 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004706 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004707 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004708 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004709 return OK;
4710 }
4711 case CAPTURE_LAYERS:
4712 case CAPTURE_SCREEN: {
4713 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004714 IPCThreadState* ipc = IPCThreadState::self();
4715 const int pid = ipc->getCallingPid();
4716 const int uid = ipc->getCallingUid();
4717 if ((uid != AID_GRAPHICS) &&
4718 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4719 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4720 return PERMISSION_DENIED;
4721 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722 return OK;
4723 }
4724 // The following codes are deprecated and should never be allowed to access SF.
4725 case CONNECT_DISPLAY_UNUSED:
4726 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4727 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4728 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004730 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731
4732 // These codes are used for the IBinder protocol to either interrogate the recipient
4733 // side of the transaction for its canonical interface descriptor or to dump its state.
4734 // We let them pass by default.
4735 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4736 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4737 code == IBinder::SYSPROPS_TRANSACTION) {
4738 return OK;
4739 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004740 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004741 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004742 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004743 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4744 return OK;
4745 }
4746 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4747 return PERMISSION_DENIED;
4748#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004749}
4750
Ana Krulec13be8ad2018-08-21 02:43:56 +00004751status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4752 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004753 status_t credentialCheck = CheckTransactCodeCredentials(code);
4754 if (credentialCheck != OK) {
4755 return credentialCheck;
4756 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4759 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004760 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004761 IPCThreadState* ipc = IPCThreadState::self();
4762 const int uid = ipc->getCallingUid();
4763 if (CC_UNLIKELY(uid != AID_SYSTEM
4764 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004765 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004766 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004767 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004768 return PERMISSION_DENIED;
4769 }
4770 int n;
4771 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004772 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004773 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 return NO_ERROR;
4775 case 1002: // SHOW_UPDATES
4776 n = data.readInt32();
4777 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004778 invalidateHwcGeometry();
4779 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004780 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004782 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004783 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004784 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004785 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004786 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004787 setTransactionFlags(
4788 eTransactionNeeded|
4789 eDisplayTransactionNeeded|
4790 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004791 return NO_ERROR;
4792 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004793 case 1006:{ // send empty update
4794 signalRefresh();
4795 return NO_ERROR;
4796 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004797 case 1008: // toggle use of hw composer
4798 n = data.readInt32();
4799 mDebugDisableHWC = n ? 1 : 0;
4800 invalidateHwcGeometry();
4801 repaintEverything();
4802 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004803 case 1009: // toggle use of transform hint
4804 n = data.readInt32();
4805 mDebugDisableTransformHint = n ? 1 : 0;
4806 invalidateHwcGeometry();
4807 repaintEverything();
4808 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004809 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004810 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004811 reply->writeInt32(0);
4812 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004813 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004814 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 return NO_ERROR;
4816 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004818 if (!display) {
4819 return NAME_NOT_FOUND;
4820 }
4821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004822 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004823 return NO_ERROR;
4824 }
4825 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004826 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004827 // daltonize
4828 n = data.readInt32();
4829 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004830 case 1:
4831 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4832 break;
4833 case 2:
4834 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4835 break;
4836 case 3:
4837 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4838 break;
4839 default:
4840 mDaltonizer.setType(ColorBlindnessType::None);
4841 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004842 }
4843 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004844 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004845 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004847 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004848
4849 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004850 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004851 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004852 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004854 // apply a color matrix
4855 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004856 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004857 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004858 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004859 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004860 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004861 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004862 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004863 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004864 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004866
4867 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4868 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004870 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4871 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4872 }
4873
Chia-I Wu28f320b2018-05-03 11:02:56 -07004874 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004875 return NO_ERROR;
4876 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004877 // This is an experimental interface
4878 // Needs to be shifted to proper binder interface when we productize
4879 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004880 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004881 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004882 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004883 return NO_ERROR;
4884 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004885 case 1017: {
4886 n = data.readInt32();
4887 mForceFullDamage = static_cast<bool>(n);
4888 return NO_ERROR;
4889 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004890 case 1018: { // Modify Choreographer's phase offset
4891 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004892 if (mUseScheduler) {
4893 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4894 } else {
4895 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4896 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004897 return NO_ERROR;
4898 }
4899 case 1019: { // Modify SurfaceFlinger's phase offset
4900 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004901 if (mUseScheduler) {
4902 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4903 } else {
4904 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4905 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004906 return NO_ERROR;
4907 }
Irvel468051e2016-06-13 16:44:44 -07004908 case 1020: { // Layer updates interceptor
4909 n = data.readInt32();
4910 if (n) {
4911 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004912 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004913 }
4914 else{
4915 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004916 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004917 }
4918 return NO_ERROR;
4919 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004920 case 1021: { // Disable HWC virtual displays
4921 n = data.readInt32();
4922 mUseHwcVirtualDisplays = !n;
4923 return NO_ERROR;
4924 }
Romain Guy0147a172017-06-01 13:53:56 -07004925 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004926 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004927 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004928
Chia-I Wu28f320b2018-05-03 11:02:56 -07004929 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004930 return NO_ERROR;
4931 }
Romain Guy54f154a2017-10-24 21:40:32 +01004932 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004933 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004934 invalidateHwcGeometry();
4935 repaintEverything();
4936 return NO_ERROR;
4937 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004938 // Deprecate, use 1030 to check whether the device is color managed.
4939 case 1024: {
4940 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004941 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004942 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004943 n = data.readInt32();
4944 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004945 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004946 mTracing.enable();
4947 doTracing("tracing.enable");
4948 reply->writeInt32(NO_ERROR);
4949 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004950 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004951 status_t err = mTracing.disable();
4952 reply->writeInt32(err);
4953 }
4954 return NO_ERROR;
4955 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004956 case 1026: { // Get layer tracing status
4957 reply->writeBool(mTracing.isEnabled());
4958 return NO_ERROR;
4959 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004960 // Is a DisplayColorSetting supported?
4961 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004962 const auto display = getDefaultDisplayDevice();
4963 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004964 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004965 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004966
4967 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4968 switch (setting) {
4969 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004970 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004971 break;
4972 case DisplayColorSetting::UNMANAGED:
4973 reply->writeBool(true);
4974 break;
4975 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004976 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004977 break;
4978 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004979 reply->writeBool(
4980 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004981 break;
4982 }
4983 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004984 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004985 // Is VrFlinger active?
4986 case 1028: {
4987 Mutex::Autolock _l(mStateLock);
4988 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4989 return NO_ERROR;
4990 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004991 // Is device color managed?
4992 case 1030: {
4993 reply->writeBool(useColorManagement);
4994 return NO_ERROR;
4995 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004996 // Override default composition data space
4997 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4998 // && adb shell stop zygote && adb shell start zygote
4999 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5000 // adb shell stop zygote && adb shell start zygote
5001 case 1031: {
5002 Mutex::Autolock _l(mStateLock);
5003 n = data.readInt32();
5004 if (n) {
5005 n = data.readInt32();
5006 if (n) {
5007 Dataspace dataspace = static_cast<Dataspace>(n);
5008 if (!validateCompositionDataspace(dataspace)) {
5009 return BAD_VALUE;
5010 }
5011 mDefaultCompositionDataspace = dataspace;
5012 }
5013 n = data.readInt32();
5014 if (n) {
5015 Dataspace dataspace = static_cast<Dataspace>(n);
5016 if (!validateCompositionDataspace(dataspace)) {
5017 return BAD_VALUE;
5018 }
5019 mWideColorGamutCompositionDataspace = dataspace;
5020 }
5021 } else {
5022 // restore composition data space.
5023 mDefaultCompositionDataspace = defaultCompositionDataspace;
5024 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5025 }
5026 return NO_ERROR;
5027 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005028 }
5029 }
5030 return err;
5031}
5032
Steven Thomas6d8110b2017-08-31 18:24:21 -07005033void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005034 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005035 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005036}
5037
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005038// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5039class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005040public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005041 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5042 ~WindowDisconnector() {
5043 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005044 }
5045
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005046private:
5047 ANativeWindow* mWindow;
5048 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005049};
5050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005051status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005052 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5053 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005054 uint32_t reqWidth, uint32_t reqHeight,
5055 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005056 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005057 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005059 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005060
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005061 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5062
Chia-I Wu20261cb2018-08-23 12:55:44 -07005063 sp<DisplayDevice> display;
5064 {
5065 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005066
Chia-I Wu20261cb2018-08-23 12:55:44 -07005067 display = getDisplayDeviceLocked(displayToken);
5068 if (!display) return BAD_VALUE;
5069
Chia-I Wucb023152018-08-28 12:57:23 -07005070 // set the requested width/height to the logical display viewport size
5071 // by default
5072 if (reqWidth == 0 || reqHeight == 0) {
5073 reqWidth = uint32_t(display->getViewport().width());
5074 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005075 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005076 }
5077
Peiyong Lin0e003c92018-09-17 11:09:51 -07005078 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5079 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005080
5081 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005082 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005083 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5084 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005085}
5086
5087status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005088 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5089 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005090 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005091 ATRACE_CALL();
5092
5093 class LayerRenderArea : public RenderArea {
5094 public:
Robert Carr578038f2018-03-09 12:25:24 -08005095 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005096 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5097 bool childrenOnly)
5098 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005099 mLayer(layer),
5100 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005101 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005102 mFlinger(flinger),
5103 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005104 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005105 Rect getBounds() const override {
5106 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005107 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005108 }
Marissa Wall61c58622018-07-18 10:12:20 -07005109 int getHeight() const override {
5110 return mLayer->getActiveHeight(mLayer->getDrawingState());
5111 }
5112 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005113 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005114 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005115 Rect getSourceCrop() const override {
5116 if (mCrop.isEmpty()) {
5117 return getBounds();
5118 } else {
5119 return mCrop;
5120 }
5121 }
Robert Carr578038f2018-03-09 12:25:24 -08005122 class ReparentForDrawing {
5123 public:
5124 const sp<Layer>& oldParent;
5125 const sp<Layer>& newParent;
5126
5127 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5128 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005129 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005130 }
Robert Carr15eae092018-03-23 13:43:53 -07005131 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005132 };
5133
5134 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005135 const Rect sourceCrop = getSourceCrop();
5136 // no need to check rotation because there is none
5137 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5138 sourceCrop.height() != getReqHeight();
5139
Robert Carr578038f2018-03-09 12:25:24 -08005140 if (!mChildrenOnly) {
5141 mTransform = mLayer->getTransform().inverse();
5142 drawLayers();
5143 } else {
5144 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005145 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005146 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5147 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005148
5149 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5150 drawLayers();
5151 }
5152 }
chaviwa76b2712017-09-20 12:02:26 -07005153
chaviwa76b2712017-09-20 12:02:26 -07005154 private:
chaviw7206d492017-11-10 16:16:12 -08005155 const sp<Layer> mLayer;
5156 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005157
5158 // In the "childrenOnly" case we reparent the children to a screenshot
5159 // layer which has no properties set and which does not draw.
5160 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005161 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005162 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005163
5164 SurfaceFlinger* mFlinger;
5165 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005166 };
5167
5168 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5169 auto parent = layerHandle->owner.promote();
5170
Robert Carr2e102c92018-10-23 12:11:15 -07005171 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005172 ALOGE("captureLayers called with a removed parent");
5173 return NAME_NOT_FOUND;
5174 }
5175
Robert Carr578038f2018-03-09 12:25:24 -08005176 const int uid = IPCThreadState::self()->getCallingUid();
5177 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5178 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5179 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5180 return PERMISSION_DENIED;
5181 }
5182
chaviw7206d492017-11-10 16:16:12 -08005183 Rect crop(sourceCrop);
5184 if (sourceCrop.width() <= 0) {
5185 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005186 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005187 }
5188
5189 if (sourceCrop.height() <= 0) {
5190 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005191 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005192 }
5193
5194 int32_t reqWidth = crop.width() * frameScale;
5195 int32_t reqHeight = crop.height() * frameScale;
5196
Chia-I Wu20261cb2018-08-23 12:55:44 -07005197 // really small crop or frameScale
5198 if (reqWidth <= 0) {
5199 reqWidth = 1;
5200 }
5201 if (reqHeight <= 0) {
5202 reqHeight = 1;
5203 }
5204
Peiyong Lin0e003c92018-09-17 11:09:51 -07005205 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005206
Robert Carr578038f2018-03-09 12:25:24 -08005207 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005208 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5209 if (!layer->isVisible()) {
5210 return;
Robert Carr578038f2018-03-09 12:25:24 -08005211 } else if (childrenOnly && layer == parent.get()) {
5212 return;
chaviwa76b2712017-09-20 12:02:26 -07005213 }
5214 visitor(layer);
5215 });
5216 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005217 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005218}
5219
5220status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5221 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005222 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005223 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005224 bool useIdentityTransform) {
5225 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005226
Peiyong Lin0e003c92018-09-17 11:09:51 -07005227 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005228 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5229 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005230 *outBuffer =
5231 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5232 static_cast<android_pixel_format>(reqPixelFormat), 1,
5233 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005234
5235 // This mutex protects syncFd and captureResult for communication of the return values from the
5236 // main thread back to this Binder thread
5237 std::mutex captureMutex;
5238 std::condition_variable captureCondition;
5239 std::unique_lock<std::mutex> captureLock(captureMutex);
5240 int syncFd = -1;
5241 std::optional<status_t> captureResult;
5242
Robert Carr03480e22018-01-04 16:02:06 -08005243 const int uid = IPCThreadState::self()->getCallingUid();
5244 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5245
Dominik Laskowski8c001672018-05-30 16:52:06 -07005246 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005247 // If there is a refresh pending, bug out early and tell the binder thread to try again
5248 // after the refresh.
5249 if (mRefreshPending) {
5250 ATRACE_NAME("Skipping screenshot for now");
5251 std::unique_lock<std::mutex> captureLock(captureMutex);
5252 captureResult = std::make_optional<status_t>(EAGAIN);
5253 captureCondition.notify_one();
5254 return;
5255 }
5256
5257 status_t result = NO_ERROR;
5258 int fd = -1;
5259 {
5260 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005261 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005262 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5263 useIdentityTransform, forSystem, &fd);
5264 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005265 }
5266
5267 {
5268 std::unique_lock<std::mutex> captureLock(captureMutex);
5269 syncFd = fd;
5270 captureResult = std::make_optional<status_t>(result);
5271 captureCondition.notify_one();
5272 }
5273 });
5274
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005275 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005276 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005277 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278 while (*captureResult == EAGAIN) {
5279 captureResult.reset();
5280 result = postMessageAsync(message);
5281 if (result != NO_ERROR) {
5282 return result;
5283 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005284 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005285 }
5286 result = *captureResult;
5287 }
5288
5289 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005290 sync_wait(syncFd, -1);
5291 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005292 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005293
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005294 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005295}
5296
chaviwa76b2712017-09-20 12:02:26 -07005297void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005298 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005299 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005300 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005301
Lloyd Pique144e1162017-12-20 16:44:52 -08005302 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005303
chaviwa76b2712017-09-20 12:02:26 -07005304 const auto reqWidth = renderArea.getReqWidth();
5305 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005306 const auto sourceCrop = renderArea.getSourceCrop();
5307 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005308
Peiyong Lin0e003c92018-09-17 11:09:51 -07005309 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005310 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005311
Mathias Agopian180f10d2013-04-10 22:55:41 -07005312 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005313 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005314
5315 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005316 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005317 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005318
chaviw50da5042018-04-09 13:49:37 -07005319 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005320 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005321 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005322
chaviwa76b2712017-09-20 12:02:26 -07005323 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005324 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005325 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005326 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005327 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005328}
5329
chaviwa76b2712017-09-20 12:02:26 -07005330status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5331 TraverseLayersFunction traverseLayers,
5332 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005333 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005334 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005335 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005336 ATRACE_CALL();
5337
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005338 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005339
5340 traverseLayers([&](Layer* layer) {
5341 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5342 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005343
Robert Carr03480e22018-01-04 16:02:06 -08005344 // We allow the system server to take screenshots of secure layers for
5345 // use in situations like the Screen-rotation animation and place
5346 // the impetus on WindowManager to not persist them.
5347 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005348 ALOGW("FB is protected: PERMISSION_DENIED");
5349 return PERMISSION_DENIED;
5350 }
5351
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005352 // this binds the given EGLImage as a framebuffer for the
5353 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005354 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005355 if (bufferBond.getStatus() != NO_ERROR) {
5356 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005357 return INVALID_OPERATION;
5358 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005359
Dan Stozaabcda352017-06-01 14:37:39 -07005360 // this will in fact render into our dequeued buffer
5361 // via an FBO, which means we didn't have to create
5362 // an EGLSurface and therefore we're not
5363 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005364 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005365
Alec Mouri492bc572018-09-11 21:40:04 +00005366 base::unique_fd syncFd = getRenderEngine().flush();
5367 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005368 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005369 }
Alec Mouri492bc572018-09-11 21:40:04 +00005370 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005371
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005373}
5374
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005375// ---------------------------------------------------------------------------
5376
Dan Stoza412903f2017-04-27 13:42:17 -07005377void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5378 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005379}
5380
Dan Stoza412903f2017-04-27 13:42:17 -07005381void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5382 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005383}
5384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005385void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005386 const LayerVector::Visitor& visitor) {
5387 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005388 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005389 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005390 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005391 continue;
5392 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005393 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005394 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005395 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005396 return;
5397 }
chaviwa76b2712017-09-20 12:02:26 -07005398 if (!layer->isVisible()) {
5399 return;
5400 }
5401 visitor(layer);
5402 });
5403 }
5404}
5405
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005406}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005407
Lloyd Pique074e8122018-07-26 12:57:23 -07005408
Mathias Agopian3f844832013-08-07 21:24:32 -07005409#if defined(__gl_h_)
5410#error "don't include gl/gl.h in this file"
5411#endif
5412
5413#if defined(__gl2_h_)
5414#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005415#endif