blob: 72ca3635aa1fdfb415e723c0fde69a412bee95dd [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
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070040#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070041#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080043#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080044#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070047#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070048#include <ui/ColorSpace.h>
49#include <ui/DebugUtils.h>
50#include <ui/DisplayInfo.h>
51#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070052#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080055#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070057#include <utils/String16.h>
58#include <utils/String8.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>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Robert Carr578038f2018-03-09 12:25:24 -080066#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070067#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070068#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020069#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080070#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020071#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080073#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070078#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070079#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070081#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070090#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091#include "Scheduler/EventControlThread.h"
92#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070093#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070095#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080096#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097
Mathias Agopianff2ed702013-09-01 21:36:12 -070098#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070099
David Sodman7e4ae112018-02-09 15:02:28 -0800100#include "android-base/stringprintf.h"
101
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700104#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800105#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900106#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107
chaviw1d044282017-09-27 12:19:28 -0700108#include <layerproto/LayerProtoParser.h>
109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800114using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700131 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700147ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
148 switch (rotation) {
149 case ISurfaceComposer::eRotateNone:
150 return ui::Transform::ROT_0;
151 case ISurfaceComposer::eRotate90:
152 return ui::Transform::ROT_90;
153 case ISurfaceComposer::eRotate180:
154 return ui::Transform::ROT_180;
155 case ISurfaceComposer::eRotate270:
156 return ui::Transform::ROT_270;
157 }
158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
159 return ui::Transform::ROT_0;
160}
161
Peiyong Linfca547f2018-07-09 13:03:33 -0700162#pragma clang diagnostic pop
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164class ConditionalLock {
165public:
166 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
167 if (lock) {
168 mMutex.lock();
169 }
170 }
171 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
172private:
173 Mutex& mMutex;
174 bool mLocked;
175};
Peiyong Linfca547f2018-07-09 13:03:33 -0700176
Peiyong Lin9d846a52018-11-05 13:18:20 -0800177// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
178bool validateCompositionDataspace(Dataspace dataspace) {
179 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
180}
181
Steven Thomasb02664d2017-07-26 18:48:28 -0700182} // namespace anonymous
183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184// ---------------------------------------------------------------------------
185
Mathias Agopian99b49842011-06-27 16:05:52 -0700186const String16 sHardwareTest("android.permission.HARDWARE_TEST");
187const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
188const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
189const String16 sDump("android.permission.DUMP");
190
191// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800192int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
193int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700194int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700195bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800196uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800197bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800198bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800199int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600200bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700201int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700202bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700203bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700204Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
205ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
206Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
207ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700208
Kalle Raitaa099a242017-01-11 11:17:29 -0800209std::string getHwcServiceName() {
210 char value[PROPERTY_VALUE_MAX] = {};
211 property_get("debug.sf.hwc_service_name", value, "default");
212 ALOGI("Using HWComposer service: '%s'", value);
213 return std::string(value);
214}
215
216bool useTrebleTestingOverride() {
217 char value[PROPERTY_VALUE_MAX] = {};
218 property_get("debug.sf.treble_testing_override", value, "false");
219 ALOGI("Treble testing override: '%s'", value);
220 return std::string(value) == "true";
221}
222
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
224 switch(displayColorSetting) {
225 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700226 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Enhanced");
231 default:
232 return std::string("Unknown ") +
233 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235}
236
David Sodmanbc815282017-11-05 18:57:52 -0800237SurfaceFlingerBE::SurfaceFlingerBE()
238 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800239 mFrameBuckets(),
240 mTotalTime(0),
241 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800242 mComposerSequenceId(0) {
243}
244
Lloyd Pique90c115d2018-09-18 21:39:42 -0700245SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
246 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800265 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800268 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700272 mMainThreadId(std::this_thread::get_id()),
273 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
276 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700306 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700307 getBool<V1_2::ISurfaceFlingerConfigs,
308 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
309
310 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
311 if (surfaceFlingerConfigsServiceV1_2) {
312 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700313 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
314 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
315 defaultCompositionDataspace = tmpDefaultDataspace;
316 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
317 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
318 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
319 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700320 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800321 mDefaultCompositionDataspace = defaultCompositionDataspace;
322 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600323
Peiyong Linb3839ad2018-09-05 15:37:19 -0700324 useContextPriority = getBool<ISurfaceFlingerConfigs,
325 &ISurfaceFlingerConfigs::useContextPriority>(true);
326
Iris Chang7501ed62018-04-30 14:45:42 +0800327 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700328 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
329 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800330 V1_1::DisplayOrientation::ORIENTATION_0);
331
332 switch (primaryDisplayOrientation) {
333 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800347
Lloyd Pique90c115d2018-09-18 21:39:42 -0700348 mPrimaryDispSync =
349 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
350 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 // debugging stuff...
353 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianb4b17302013-03-20 18:36:41 -0700355 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700356 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358 property_get("debug.sf.showupdates", value, "0");
359 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 property_get("debug.sf.ddms", value, "0");
362 mDebugDDMS = atoi(value);
363 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700364 if (!startDdmConnection()) {
365 // start failed, and DDMS debugging not enabled
366 mDebugDDMS = 0;
367 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700369 ALOGI_IF(mDebugRegion, "showupdates enabled");
370 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700371
372 property_get("debug.sf.disable_backpressure", value, "0");
373 mPropagateBackpressure = !atoi(value);
374 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700375
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800376 property_get("debug.sf.enable_hwc_vds", value, "0");
377 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800378 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800379
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800380 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800381 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800382 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700383
Yiwei Zhang243b3782018-05-15 17:40:04 -0700384 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700385 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
386 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
387
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200388 property_get("debug.sf.early_phase_offset_ns", value, "-1");
389 const int earlySfOffsetNs = atoi(value);
390
391 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
392 const int earlyGlSfOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
395 const int earlyAppOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
398 const int earlyGlAppOffsetNs = atoi(value);
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200403 const VSyncModulator::Offsets earlyOffsets =
404 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
405 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
406 const VSyncModulator::Offsets earlyGlOffsets =
407 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
408 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
409 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
410 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700411
Romain Guy11d63f42017-07-20 12:47:14 -0700412 // We should be reading 'persist.sys.sf.color_saturation' here
413 // but since /data may be encrypted, we need to wait until after vold
414 // comes online to attempt to read the property. The property is
415 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800416
417 if (useTrebleTestingOverride()) {
418 // Without the override SurfaceFlinger cannot connect to HIDL
419 // services that are not listed in the manifests. Considered
420 // deriving the setting from the set service name, but it
421 // would be brittle if the name that's not 'default' is used
422 // for production purposes later on.
423 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425}
426
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427void SurfaceFlinger::onFirstRef()
428{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800429 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432SurfaceFlinger::~SurfaceFlinger()
433{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434}
435
Dan Stozac7014012014-02-14 15:03:43 -0800436void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437{
438 // the window manager died on us. prepare its eulogy.
439
Andy McFadden13a082e2012-08-24 10:16:42 -0700440 // restore initial conditions (default device unblank, etc)
441 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442
443 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700444 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445}
446
Robert Carr1db73f62016-12-21 12:58:51 -0800447static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700448 status_t err = client->initCheck();
449 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 }
Robert Carr1db73f62016-12-21 12:58:51 -0800452 return nullptr;
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
456 return initClient(new Client(this));
457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 // Display ID is assigned when virtual display is allocated by HWC.
480 DisplayDeviceState state;
481 state.isSecure = secure;
482 state.displayName = displayName;
483 mCurrentState.displays.add(token, state);
484 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
492 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
498 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 mInterceptor->saveDisplayDeletion(state.sequenceId);
503 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 std::optional<DisplayId> displayId;
509
510 if (id == HWC_DISPLAY_PRIMARY) {
511 displayId = getInternalDisplayId();
512 } else if (id == HWC_DISPLAY_EXTERNAL) {
513 displayId = getExternalDisplayId();
514 }
515
516 if (!displayId) {
517 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800518 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520
521 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522}
523
Ady Abraham37965d42018-11-01 13:43:32 -0700524status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
525 if (!outGetColorManagement) {
526 return BAD_VALUE;
527 }
528 *outGetColorManagement = useColorManagement;
529 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700530}
531
Lloyd Pique441d5042018-10-18 16:49:51 -0700532HWComposer& SurfaceFlinger::getHwComposer() const {
533 return mCompositionEngine->getHwComposer();
534}
535
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700536renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
537 return mCompositionEngine->getRenderEngine();
538}
539
Lloyd Pique70d91362018-10-18 16:02:55 -0700540compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
541 return *mCompositionEngine.get();
542}
543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544void SurfaceFlinger::bootFinished()
545{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700546 if (mStartPropertySetThread->join() != NO_ERROR) {
547 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549 const nsecs_t now = systemTime();
550 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000551 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552
553 // wait patiently for the window manager death
554 const String16 name("window");
555 sp<IBinder> window(defaultServiceManager()->getService(name));
556 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700557 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558 }
Robert Carr720e5062018-07-30 17:45:14 -0700559 sp<IBinder> input(defaultServiceManager()->getService(
560 String16("inputflinger")));
561 if (input == nullptr) {
562 ALOGE("Failed to link to input service");
563 } else {
564 mInputFlinger = interface_cast<IInputFlinger>(input);
565 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700566
Steven Thomas050b2c82017-03-06 11:45:16 -0800567 if (mVrFlinger) {
568 mVrFlinger->OnBootFinished();
569 }
570
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700572 // formerly we would just kill the process, but we now ask it to exit so it
573 // can choose where to stop the animation.
574 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700575
576 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
577 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
578 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700579
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 postMessageAsync(new LambdaMessage([this] {
581 readPersistentProperties();
582 mBootStage = BootStage::FINISHED;
583 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584}
585
Dan Stoza436ccf32018-06-21 12:10:12 -0700586uint32_t SurfaceFlinger::getNewTexture() {
587 {
588 std::lock_guard lock(mTexturePoolMutex);
589 if (!mTexturePool.empty()) {
590 uint32_t name = mTexturePool.back();
591 mTexturePool.pop_back();
592 ATRACE_INT("TexturePoolSize", mTexturePool.size());
593 return name;
594 }
595
596 // The pool was too small, so increase it for the future
597 ++mTexturePoolSize;
598 }
599
600 // The pool was empty, so we need to get a new texture name directly using a
601 // blocking call to the main thread
602 uint32_t name = 0;
603 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
604 return name;
605}
606
Mathias Agopian3f844832013-08-07 21:24:32 -0700607void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700608 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700609}
610
Wei Wangf9b05ee2017-07-19 20:59:39 -0700611// Do not call property_set on main thread which will be blocked by init
612// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700614 ALOGI( "SurfaceFlinger's main thread ready to run. "
615 "Initializing graphics H/W...");
616
Thierry Strudel2924d012017-08-14 15:19:37 -0700617 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700622 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700623 mScheduler = getFactory().createScheduler([this](bool enabled) {
624 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
625 });
626
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700628 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 [this] { resyncWithRateLimit(); },
630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700632 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 [this] { resyncWithRateLimit(); },
634 [this](nsecs_t timestamp) {
635 mInterceptor->saveVSyncEvent(timestamp);
636 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800637
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700639 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
640 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 } else {
642 mEventThreadSource =
643 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
644 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
645 mEventThread =
646 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
647 [this] { resyncWithRateLimit(); },
648 impl::EventThread::InterceptVSyncsCallback(),
649 "appEventThread");
650 mSfEventThreadSource =
651 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
652 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
653
654 mSFEventThread =
655 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
656 [this] { resyncWithRateLimit(); },
657 [this](nsecs_t timestamp) {
658 mInterceptor->saveVSyncEvent(timestamp);
659 },
660 "sfEventThread");
661 mEventQueue->setEventThread(mSFEventThread.get());
662 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
663 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800664
Steven Thomasb02664d2017-07-26 18:48:28 -0700665 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700666 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700667 renderEngineFeature |= (useColorManagement ?
668 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700669 renderEngineFeature |= (useContextPriority ?
670 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700671
672 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700674 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700675 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700676
677 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
678 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700679 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
680 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800681 // Process any initial hotplug and resulting display changes.
682 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 const auto display = getDefaultDisplayDeviceLocked();
684 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 // This callback is called from the vr flinger dispatch thread. We
691 // need to call signalTransaction(), which requires holding
692 // mStateLock when we're not on the main thread. Acquiring
693 // mStateLock from the vr flinger dispatch thread might trigger a
694 // deadlock in surface flinger (see b/66916578), so post a message
695 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
698 mVrFlingerRequestsDisplay = requestDisplay;
699 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
703 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 .value_or(0),
706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Lloyd Pique90c115d2018-09-18 21:39:42 -0700712 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700713 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700714
Mathias Agopian92a979a2012-08-02 18:32:23 -0700715 // initialize our drawing state
716 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700717
Andy McFadden13a082e2012-08-24 10:16:42 -0700718 // set initial conditions (e.g. unblank default device)
719 initializeDisplays();
720
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700721 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700722
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700724
725 const bool presentFenceReliable =
726 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
727 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728
729 if (mStartPropertySetThread->Start() != NO_ERROR) {
730 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732
Ana Krulec7d1d6832018-12-27 11:10:09 -0800733 if (mUseScheduler) {
734 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
735 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
736 }
737
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700739}
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 Mutex::Autolock _l(mStateLock);
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744 char value[PROPERTY_VALUE_MAX];
745
746 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800747 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100750
751 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700752 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700770 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
809 Vector<DisplayInfo>* configs) {
810 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 const auto displayId = getPhysicalDisplayId(displayToken);
815 if (!displayId) {
816 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700817 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 // TODO: Not sure if display density should handled by SF any longer
820 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700823 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800824 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 }
827 return density;
828 }
829 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("ro.sf.lcd_density"); }
834 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Steven Thomas6d8110b2017-08-31 18:24:21 -0700838 ConditionalLock _l(mStateLock,
839 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700840 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 DisplayInfo info = DisplayInfo();
842
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 float xdpi = hwConfig->getDpiX();
844 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700846 info.w = hwConfig->getWidth();
847 info.h = hwConfig->getHeight();
848 // Default display viewport to display width and height
849 info.viewportW = info.w;
850 info.viewportH = info.h;
851
Dominik Laskowski075d3172018-05-24 15:50:06 -0700852 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 // The density of the device is provided by a build property
854 float density = Density::getBuildDensity() / 160.0f;
855 if (density == 0) {
856 // the build doesn't provide a density -- this is wrong!
857 // use xdpi instead
858 ALOGE("ro.sf.lcd_density must be defined as a build property");
859 density = xdpi / 160.0f;
860 }
861 if (Density::getEmuDensity()) {
862 // if "qemu.sf.lcd_density" is specified, it overrides everything
863 xdpi = ydpi = density = Density::getEmuDensity();
864 density /= 160.0f;
865 }
866 info.density = density;
867
868 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869 const auto display = getDefaultDisplayDeviceLocked();
870 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700871
872 // This is for screenrecord
873 const Rect viewport = display->getViewport();
874 if (viewport.isValid()) {
875 info.viewportW = uint32_t(viewport.getWidth());
876 info.viewportH = uint32_t(viewport.getHeight());
877 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 } else {
879 // TODO: where should this value come from?
880 static const int TV_DENSITY = 213;
881 info.density = TV_DENSITY / 160.0f;
882 info.orientation = 0;
883 }
884
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 info.xdpi = xdpi;
886 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900888 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800903 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700904
905 // All non-virtual displays are currently considered secure.
906 info.secure = true;
907
Dominik Laskowski075d3172018-05-24 15:50:06 -0700908 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700909 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800910 std::swap(info.w, info.h);
911 }
912
Michael Wright28f24d02016-07-12 13:30:53 -0700913 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 }
915
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 return NO_ERROR;
917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
920 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
Ana Krulece588e312018-09-18 12:32:24 -0700924 if (mUseScheduler) {
925 mScheduler->getDisplayStatInfo(stats);
926 } else {
927 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
928 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
929 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700930 return NO_ERROR;
931}
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
934 const auto display = getDisplayDevice(displayToken);
935 if (!display) {
936 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800937 return BAD_VALUE;
938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
944 ATRACE_NAME("setActiveConfigAsync");
945 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
946 return NO_ERROR;
947}
948
949status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
950 ATRACE_NAME("setActiveConfigSync");
951 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
952 return NO_ERROR;
953}
954
955void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
956 Vector<DisplayInfo> configs;
957 getDisplayConfigs(displayToken, &configs);
958 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
959 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
960 return;
961 }
962
963 const auto display = getDisplayDevice(displayToken);
964 if (!display) {
965 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
966 displayToken.get());
967 return;
968 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700969 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800970 ALOGW("Attempt to set active config %d for virtual display", mode);
971 return;
972 }
973 int currentDisplayPowerMode = display->getPowerMode();
974 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
975 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 return;
977 }
978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700980 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800981 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 return;
983 }
984
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 const auto displayId = display->getId();
986 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700990
Ana Krulec7d1d6832018-12-27 11:10:09 -0800991 ATRACE_INT("ActiveConfigMode", mode);
992 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700993}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
996 Vector<ColorMode>* outColorModes) {
997 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700998 return BAD_VALUE;
999 }
1000
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 const auto displayId = getPhysicalDisplayId(displayToken);
1002 if (!displayId) {
1003 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001004 }
1005
Peiyong Lina52f0292018-03-14 17:26:31 -07001006 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001007 {
1008 ConditionalLock _l(mStateLock,
1009 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001011 }
Michael Wright28f24d02016-07-12 13:30:53 -07001012 outColorModes->clear();
1013 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1014
1015 return NO_ERROR;
1016}
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1019 if (const auto display = getDisplayDevice(displayToken)) {
1020 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001021 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001023}
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1026 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001027 if (display->isVirtual()) {
1028 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1029 return;
1030 }
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 ColorMode currentMode = display->getActiveColorMode();
1033 Dataspace currentDataSpace = display->getCompositionDataSpace();
1034 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001035
Peiyong Lin38e9a562018-04-10 16:24:20 -07001036 if (mode == currentMode && dataSpace == currentDataSpace &&
1037 renderIntent == currentRenderIntent) {
1038 return;
1039 }
1040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 display->setActiveColorMode(mode);
1042 display->setCompositionDataSpace(dataSpace);
1043 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001044
Dominik Laskowski075d3172018-05-24 15:50:06 -07001045 const auto displayId = display->getId();
1046 LOG_ALWAYS_FATAL_IF(!displayId);
1047 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1048
Dominik Laskowski34157762018-10-31 13:07:19 -07001049 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001051 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001052}
1053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001055 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 Vector<ColorMode> modes;
1057 getDisplayColorModes(displayToken, &modes);
1058 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1059 if (mode < ColorMode::NATIVE || !exists) {
1060 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1061 decodeColorMode(mode).c_str(), mode, displayToken.get());
1062 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const auto display = getDisplayDevice(displayToken);
1065 if (!display) {
1066 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1067 decodeColorMode(mode).c_str(), mode, displayToken.get());
1068 } else if (display->isVirtual()) {
1069 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1070 decodeColorMode(mode).c_str(), mode);
1071 } else {
1072 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1073 RenderIntent::COLORIMETRIC);
1074 }
1075 }));
1076
Michael Wright28f24d02016-07-12 13:30:53 -07001077 return NO_ERROR;
1078}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001079
Svetoslavd85084b2014-03-20 10:28:31 -07001080status_t SurfaceFlinger::clearAnimationFrameStats() {
1081 Mutex::Autolock _l(mStateLock);
1082 mAnimFrameTracker.clearStats();
1083 return NO_ERROR;
1084}
1085
1086status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1087 Mutex::Autolock _l(mStateLock);
1088 mAnimFrameTracker.getStats(outStats);
1089 return NO_ERROR;
1090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1093 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001094 Mutex::Autolock _l(mStateLock);
1095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const auto display = getDisplayDeviceLocked(displayToken);
1097 if (!display) {
1098 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001099 return BAD_VALUE;
1100 }
1101
Peiyong Linfb069302018-04-25 14:34:31 -07001102 // At this point the DisplayDeivce should already be set up,
1103 // meaning the luminance information is already queried from
1104 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001106 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1107 capabilities.getDesiredMaxLuminance(),
1108 capabilities.getDesiredMaxAverageLuminance(),
1109 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110
1111 return NO_ERROR;
1112}
1113
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001114status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1115 ui::PixelFormat* outFormat,
1116 ui::Dataspace* outDataspace,
1117 uint8_t* outComponentMask) const {
1118 if (!outFormat || !outDataspace || !outComponentMask) {
1119 return BAD_VALUE;
1120 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001121 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001122 if (!display || !display->getId()) {
1123 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1124 return BAD_VALUE;
1125 }
1126 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1127 outDataspace, outComponentMask);
1128}
1129
Kevin DuBois74e53772018-11-19 10:52:38 -08001130status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1131 bool enable, uint8_t componentMask,
1132 uint64_t maxFrames) const {
1133 const auto display = getDisplayDevice(displayToken);
1134 if (!display || !display->getId()) {
1135 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1136 return BAD_VALUE;
1137 }
1138
1139 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1140 componentMask, maxFrames);
1141}
1142
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001143status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1144 uint64_t maxFrames, uint64_t timestamp,
1145 DisplayedFrameStats* outStats) const {
1146 const auto display = getDisplayDevice(displayToken);
1147 if (!display || !display->getId()) {
1148 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1149 return BAD_VALUE;
1150 }
1151
1152 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1153 outStats);
1154}
1155
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001156status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1157 if (!outSupported) {
1158 return BAD_VALUE;
1159 }
1160 *outSupported = getRenderEngine().supportsProtectedContent();
1161 return NO_ERROR;
1162}
1163
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001164status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001165 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 if (mInjectVSyncs == enable) {
1169 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001170 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001171
Ana Krulec98b5b242018-08-10 15:03:23 -07001172 // TODO(akrulec): Part of the Injector should be refactored, so that it
1173 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 if (enable) {
1175 ALOGV("VSync Injections enabled");
1176 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001177 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001178 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001179 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001180 impl::EventThread::InterceptVSyncsCallback(),
1181 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001183 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001184 } else {
1185 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001186 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 }
1188
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001189 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001190 }));
1191
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001192 return NO_ERROR;
1193}
1194
1195status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 Mutex::Autolock _l(mStateLock);
1197
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001198 if (!mInjectVSyncs) {
1199 ALOGE("VSync Injections not enabled");
1200 return BAD_VALUE;
1201 }
1202 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1203 ALOGV("Injecting VSync inside SurfaceFlinger");
1204 mVSyncInjector->onInjectSyncEvent(when);
1205 }
1206 return NO_ERROR;
1207}
1208
Lloyd Pique755e3192018-01-31 16:46:15 -08001209status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1210 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001211 // Try to acquire a lock for 1s, fail gracefully
1212 const status_t err = mStateLock.timedLock(s2ns(1));
1213 const bool locked = (err == NO_ERROR);
1214 if (!locked) {
1215 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1216 return TIMED_OUT;
1217 }
1218
1219 outLayers->clear();
1220 mCurrentState.traverseInZOrder([&](Layer* layer) {
1221 outLayers->push_back(layer->getLayerDebugInfo());
1222 });
1223
1224 mStateLock.unlock();
1225 return NO_ERROR;
1226}
1227
Peiyong Linc6780972018-10-28 15:24:08 -07001228status_t SurfaceFlinger::getCompositionPreference(
1229 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1230 Dataspace* outWideColorGamutDataspace,
1231 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001232 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001233 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001234 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001235 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001236 return NO_ERROR;
1237}
1238
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001239// ----------------------------------------------------------------------------
1240
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001241sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1242 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001243 if (mUseScheduler) {
1244 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1245 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1246 } else {
1247 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1248 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001249 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001250 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1251 return mSFEventThread->createEventConnection();
1252 } else {
1253 return mEventThread->createEventConnection();
1254 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001255 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001256}
1257
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259
1260void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001261 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001269 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001270}
1271
1272void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001273 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001274 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001275}
1276
1277status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001278 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001279 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001280}
1281
1282status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001283 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001284 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001285 if (res == NO_ERROR) {
1286 msg->wait();
1287 }
1288 return res;
1289}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001290
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001291void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001292 do {
1293 waitForEvent();
1294 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001295}
1296
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297void SurfaceFlinger::enableHardwareVsync() {
1298 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001300 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001301 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001303 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304}
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 Mutex::Autolock _l(mHWVsyncLock);
1308
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309 if (makeAvailable) {
1310 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001311 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1312 if (mUseScheduler) {
1313 mScheduler->makeHWSyncAvailable(true);
1314 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001315 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001316 // Hardware vsync is not currently available, so abort the resync
1317 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001318 return;
1319 }
1320
Dominik Laskowski075d3172018-05-24 15:50:06 -07001321 const auto displayId = getInternalDisplayId();
1322 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001323 return;
1324 }
1325
Dominik Laskowski075d3172018-05-24 15:50:06 -07001326 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001327 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328
Ana Krulece588e312018-09-18 12:32:24 -07001329 if (mUseScheduler) {
1330 mScheduler->setVsyncPeriod(period);
1331 } else {
1332 mPrimaryDispSync->reset();
1333 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334
Ana Krulece588e312018-09-18 12:32:24 -07001335 if (!mPrimaryHWVsyncEnabled) {
1336 mPrimaryDispSync->beginResync();
1337 mEventControlThread->setVsyncEnabled(true);
1338 mPrimaryHWVsyncEnabled = true;
1339 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340 }
1341}
1342
Jesse Hall948fe0c2013-10-14 12:56:09 -07001343void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 Mutex::Autolock _l(mHWVsyncLock);
1345 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001346 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001347 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001348 mPrimaryHWVsyncEnabled = false;
1349 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001350 if (makeUnavailable) {
1351 mHWVsyncAvailable = false;
1352 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353}
1354
Tim Murray4a4e4a22016-04-19 16:29:23 +00001355void SurfaceFlinger::resyncWithRateLimit() {
1356 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001357
1358 // No explicit locking is needed here since EventThread holds a lock while calling this method
1359 static nsecs_t sLastResyncAttempted = 0;
1360 const nsecs_t now = systemTime();
1361 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001362 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001363 }
Dan Stoza57164302017-05-08 14:03:54 -07001364 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001365}
1366
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001367void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1368 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001369 ATRACE_NAME("SF onVsync");
1370
Steven Thomas3cfac282017-02-06 12:29:30 -08001371 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001373 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 return;
1375 }
1376
Dominik Laskowski075d3172018-05-24 15:50:06 -07001377 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 return;
1379 }
1380
Dominik Laskowski075d3172018-05-24 15:50:06 -07001381 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001382 // For now, we don't do anything with external display vsyncs.
1383 return;
1384 }
1385
Ana Krulece588e312018-09-18 12:32:24 -07001386 if (mUseScheduler) {
1387 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001388 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001389 bool needsHwVsync = false;
1390 { // Scope for the lock
1391 Mutex::Autolock _l(mHWVsyncLock);
1392 if (mPrimaryHWVsyncEnabled) {
1393 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1394 }
1395 }
1396
1397 if (needsHwVsync) {
1398 enableHardwareVsync();
1399 } else {
1400 disableHardwareVsync(false);
1401 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001402 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001403}
1404
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001406 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1407 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408}
1409
Ana Krulec7d1d6832018-12-27 11:10:09 -08001410void SurfaceFlinger::setRefreshRateTo(float newFps) {
1411 const auto displayId = getInternalDisplayId();
1412 if (!displayId || mBootStage != BootStage::FINISHED) {
1413 return;
1414 }
1415 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1416 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1417 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1418 // refresh cycle.
1419
1420 // Don't do any updating if the current fps is the same as the new one.
1421 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1422 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1423 if (currentVsyncPeriod == 0) {
1424 return;
1425 }
1426 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1427 // floating numbers.
1428 const float currentFps = 1e9 / currentVsyncPeriod;
1429 if (std::abs(currentFps - newFps) <= 1) {
1430 return;
1431 }
1432
1433 auto configs = getHwComposer().getConfigs(*displayId);
1434 for (int i = 0; i < configs.size(); i++) {
1435 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1436 if (vsyncPeriod == 0) {
1437 continue;
1438 }
1439 const float fps = 1e9 / vsyncPeriod;
1440 // TODO(b/113612090): There should be a better way at determining which config
1441 // has the right refresh rate.
1442 if (std::abs(fps - newFps) <= 1) {
1443 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1444 if (!display) return;
1445 // This is posted in async function to avoid deadlock when getDisplayDevice
1446 // requires mStateLock.
1447 setActiveConfigAsync(display, i);
1448 ATRACE_INT("FPS", newFps);
1449 }
1450 }
1451}
1452
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001453void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001454 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001455 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001456 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457
Lloyd Piqueba04e622017-12-14 17:11:26 -08001458 // Ignore events that do not have the right sequenceId.
1459 if (sequenceId != getBE().mComposerSequenceId) {
1460 return;
1461 }
1462
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 // Only lock if we're not on the main thread. This function is normally
1464 // called on a hwbinder thread, but for the primary display it's called on
1465 // the main thread with the state lock already held, so don't attempt to
1466 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001467 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001468
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001469 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001470
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001471 if (std::this_thread::get_id() == mMainThreadId) {
1472 // Process all pending hot plug events immediately if we are on the main thread.
1473 processDisplayHotplugEventsLocked();
1474 }
1475
Lloyd Piqueba04e622017-12-14 17:11:26 -08001476 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001477}
1478
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001479void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001480 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001481 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001482 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001483 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001484 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001485}
1486
Dominik Laskowski075d3172018-05-24 15:50:06 -07001487void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001488 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001490 if (const auto displayId = getInternalDisplayId()) {
1491 getHwComposer().setVsyncEnabled(*displayId,
1492 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1493 }
Mathias Agopian86303202012-07-24 22:46:10 -07001494}
1495
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001496// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001497void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001498 if (mUseScheduler) {
1499 mScheduler->disableHardwareVsync(true);
1500 } else {
1501 disableHardwareVsync(true);
1502 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001503 // Clear the drawing state so that the logic inside of
1504 // handleTransactionLocked will fire. It will determine the delta between
1505 // mCurrentState and mDrawingState and re-apply all changes when we make the
1506 // transition.
1507 mDrawingState.displays.clear();
1508 mDisplays.clear();
1509}
1510
Steven Thomas050b2c82017-03-06 11:45:16 -08001511void SurfaceFlinger::updateVrFlinger() {
1512 if (!mVrFlinger)
1513 return;
1514 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001515 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001516 return;
1517 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518
Lloyd Pique441d5042018-10-18 16:49:51 -07001519 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 ALOGE("Vr flinger is only supported for remote hardware composer"
1521 " service connections. Ignoring request to transition to vr"
1522 " flinger.");
1523 mVrFlingerRequestsDisplay = false;
1524 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001525 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001527 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomas0123ac62018-07-12 11:32:34 -07001529 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001530 LOG_ALWAYS_FATAL_IF(!display);
1531 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001532 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1533 // called below. Clear the reference now so we don't accidentally use it
1534 // later.
1535 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001536
Steven Thomasb02664d2017-07-26 18:48:28 -07001537 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001542 // Delete the current instance before creating the new one
1543 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1544 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1545 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1546 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001547
Lloyd Pique441d5042018-10-18 16:49:51 -07001548 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001549 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001550
1551 if (vrFlingerRequestsDisplay) {
1552 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001554
1555 mVisibleRegionsDirty = true;
1556 invalidateHwcGeometry();
1557
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001558 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001559 display = getDefaultDisplayDeviceLocked();
1560 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001561 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001562
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001564 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 const nsecs_t period = activeConfig->getVsyncPeriod();
1566 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001567
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568 // The present fences returned from vr_hwc are not an accurate
1569 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001570 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001571 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1572 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001573 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001574 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001575 !hasSyncFramework);
1576 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001577
Steven Thomasb02664d2017-07-26 18:48:28 -07001578 // Use phase of 0 since phase is not known.
1579 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001580 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1581 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001582
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583 resyncToHardwareVsync(false);
1584
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001585 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001586 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001587}
1588
Mathias Agopian4fec8732012-06-29 14:12:52 -07001589void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001590 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001591 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001592 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001593 if (mUseScheduler) {
1594 // This call is made each time SF wakes up and creates a new frame.
1595 mScheduler->incrementFrameCounter();
1596 }
Dan Stoza50182882016-07-08 12:02:20 -07001597 bool frameMissed = !mHadClientComposition &&
1598 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 (mPreviousPresentFence->getSignalTime() ==
1600 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001601 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001602 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001603 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001604 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001605 if (mPropagateBackpressure) {
1606 signalLayerUpdate();
1607 break;
1608 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001609 }
Dan Stoza50182882016-07-08 12:02:20 -07001610
Steven Thomas050b2c82017-03-06 11:45:16 -08001611 // Now that we're going to make it to the handleMessageTransaction()
1612 // call below it's safe to call updateVrFlinger(), which will
1613 // potentially trigger a display handoff.
1614 updateVrFlinger();
1615
Dan Stoza6b9454d2014-11-07 16:00:59 -08001616 bool refreshNeeded = handleMessageTransaction();
1617 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001618 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001619 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001620 // Signal a refresh if a transaction modified the window state,
1621 // a new buffer was latched, or if HWC has requested a full
1622 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001623 signalRefresh();
1624 }
1625 break;
1626 }
1627 case MessageQueue::REFRESH: {
1628 handleMessageRefresh();
1629 break;
1630 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001631 }
1632}
1633
Dan Stoza6b9454d2014-11-07 16:00:59 -08001634bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001635 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001636
1637 // Apply any ready transactions in the queues if there are still transactions that have not been
1638 // applied, wake up during the next vsync period and check again
1639 bool transactionNeeded = false;
1640 if (!flushTransactionQueues()) {
1641 transactionNeeded = true;
1642 }
1643
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001645 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001647
1648 if (transactionNeeded) {
1649 setTransactionFlags(eTransactionNeeded);
1650 }
1651
1652 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001653}
1654
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001657
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001658 mRefreshPending = false;
1659
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001660 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001661 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001662 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001663 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001664 for (const auto& [token, display] : mDisplays) {
1665 beginFrame(display);
1666 prepareFrame(display);
1667 doDebugFlashRegions(display, repaintEverything);
1668 doComposition(display, repaintEverything);
1669 }
1670
Adrian Roos1e1a1282017-11-01 19:05:31 +01001671 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001672 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001673
1674 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001675 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001676
Dan Stozabfbffeb2016-07-21 14:49:33 -07001677 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001678 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001679 mHadClientComposition =
1680 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001681 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682
Alec Mouri86770e52018-09-24 22:40:58 +00001683 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001684 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001685 if (mHadClientComposition) {
1686 base::unique_fd flushFence(getRenderEngine().flush());
1687 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1688 getBE().flushFence = new Fence(std::move(flushFence));
1689 } else {
1690 // Cleanup for hygiene.
1691 getBE().flushFence = Fence::NO_FENCE;
1692 }
1693 }
1694
Jorim Jaggi90535212018-05-23 23:44:06 +02001695 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001696
David Sodman7e4ae112018-02-09 15:02:28 -08001697 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001698 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001699 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001700 compositionInfo.hwc.hwcLayer = nullptr;
1701 }
David Sodmanba340492018-08-05 21:51:33 -07001702 }
David Sodman7e4ae112018-02-09 15:02:28 -08001703
1704 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707
1708bool SurfaceFlinger::handleMessageInvalidate() {
1709 ATRACE_CALL();
1710 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711}
1712
David Sodman79bba0e2018-08-05 18:07:49 -07001713void SurfaceFlinger::calculateWorkingSet() {
1714 ATRACE_CALL();
1715 ALOGV(__FUNCTION__);
1716
David Sodman79bba0e2018-08-05 18:07:49 -07001717 // build the h/w work list
1718 if (CC_UNLIKELY(mGeometryInvalid)) {
1719 mGeometryInvalid = false;
1720 for (const auto& [token, display] : mDisplays) {
1721 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001722 if (!displayId) {
1723 continue;
1724 }
David Sodman79bba0e2018-08-05 18:07:49 -07001725
Dominik Laskowski075d3172018-05-24 15:50:06 -07001726 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1727 for (size_t i = 0; i < currentLayers.size(); i++) {
1728 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001729
Dominik Laskowski075d3172018-05-24 15:50:06 -07001730 if (!layer->hasHwcLayer(*displayId)) {
1731 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1732 layer->forceClientComposition(*displayId);
1733 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001734 }
1735 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001736
1737 layer->setGeometry(display, i);
1738 if (mDebugDisableHWC || mDebugRegion) {
1739 layer->forceClientComposition(*displayId);
1740 }
David Sodman79bba0e2018-08-05 18:07:49 -07001741 }
1742 }
1743 }
1744
1745 // Set the per-frame data
1746 for (const auto& [token, display] : mDisplays) {
1747 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001748 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001749 continue;
1750 }
1751
1752 if (mDrawingState.colorMatrixChanged) {
1753 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001754 status_t result =
1755 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001756 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1757 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001758 }
1759 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1760 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001761 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001762 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1763 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1764 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001765 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001766 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1767 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1768 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001770 }
1771
Peiyong Lind3788632018-09-18 16:01:31 -07001772 // TODO(b/111562338) remove when composer 2.3 is shipped.
1773 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001775 }
1776
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001777 if (layer->getRoundedCornerState().radius > 0.0f) {
1778 layer->forceClientComposition(*displayId);
1779 }
1780
Dominik Laskowski075d3172018-05-24 15:50:06 -07001781 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001782 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001783 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001784 continue;
1785 }
1786
Dominik Laskowski075d3172018-05-24 15:50:06 -07001787 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1788 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001789 }
1790
Peiyong Lin13effd12018-07-24 17:01:47 -07001791 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001792 ColorMode colorMode;
1793 Dataspace dataSpace;
1794 RenderIntent renderIntent;
1795 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1796 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1797 }
1798 }
1799
1800 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001801
1802 for (const auto& [token, display] : mDisplays) {
1803 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001804 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001805 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001806
1807 if (displayId) {
1808 if (!layer->setHwcLayer(*displayId)) {
1809 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1810 }
1811 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001812 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001813
Dominik Laskowski05275f12018-11-01 15:03:24 -07001814 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001815 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1816 }
1817 }
David Sodman79bba0e2018-08-05 18:07:49 -07001818}
1819
David Sodmanfa9b2af2017-12-24 13:28:59 -08001820void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821{
1822 // is debugging enabled
1823 if (CC_LIKELY(!mDebugRegion))
1824 return;
1825
David Sodmanfa9b2af2017-12-24 13:28:59 -08001826 if (display->isPoweredOn()) {
1827 // transform the dirty region into this screen's coordinate space
1828 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1829 if (!dirtyRegion.isEmpty()) {
1830 // redraw the whole screen
1831 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832
David Sodmanfa9b2af2017-12-24 13:28:59 -08001833 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001835 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001836
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001837 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001838 }
1839 }
1840
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001842
1843 if (mDebugRegion > 1) {
1844 usleep(mDebugRegion * 1000);
1845 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001846
Dominik Laskowski05275f12018-11-01 15:03:24 -07001847 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001848}
1849
Adrian Roos1e1a1282017-11-01 19:05:31 +01001850void SurfaceFlinger::doTracing(const char* where) {
1851 ATRACE_CALL();
1852 ATRACE_NAME(where);
1853 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001854 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001855 }
1856}
1857
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001858void SurfaceFlinger::logLayerStats() {
1859 ATRACE_CALL();
1860 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001861 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001862 if (display->isPrimary()) {
1863 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001864 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001865 }
1866 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001867
1868 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001869 }
1870}
1871
David Sodman2b406362017-12-15 13:33:47 -08001872void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 ATRACE_CALL();
1875 ALOGV("preComposition");
1876
David Sodman2b406362017-12-15 13:33:47 -08001877 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1878
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001880 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001881 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882 needExtraInvalidate = true;
1883 }
Robert Carr2047fae2016-11-28 14:09:09 -08001884 });
1885
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 if (needExtraInvalidate) {
1887 signalLayerUpdate();
1888 }
1889}
1890
Ana Krulece588e312018-09-18 12:32:24 -07001891void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1892 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001893 // Update queue of past composite+present times and determine the
1894 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001895 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001897 while (!getBE().mCompositePresentTimes.empty()) {
1898 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 // Cached values should have been updated before calling this method,
1900 // which helps avoid duplicate syscalls.
1901 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1902 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1903 break;
1904 }
1905 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001906 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001907 }
1908
1909 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001910 while (getBE().mCompositePresentTimes.size() > 16) {
1911 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 }
1913
Ana Krulece588e312018-09-18 12:32:24 -07001914 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001915}
1916
Ana Krulece588e312018-09-18 12:32:24 -07001917void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1918 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 // Integer division and modulo round toward 0 not -inf, so we need to
1920 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001921 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1922 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1923 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924
Brian Andersond0010582017-03-07 13:20:31 -08001925 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1926 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001927 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001928 }
1929
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930 // Snap the latency to a value that removes scheduling jitter from the
1931 // composition and present times, which often have >1ms of jitter.
1932 // Reducing jitter is important if an app attempts to extrapolate
1933 // something (such as user input) to an accurate diasplay time.
1934 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1935 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001936 nsecs_t bias = stats.vsyncPeriod / 2;
1937 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1938 nsecs_t snappedCompositeToPresentLatency =
1939 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001940
David Sodman99974d22017-11-28 12:04:33 -08001941 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001942 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1943 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001944 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001945}
1946
Ady Abraham8164d482019-01-11 14:47:59 -08001947// debug patch for b/119477596 - add stack guards to catch stack
1948// corruptions and disable clang optimizations.
1949// The code below is temporary and planned to be removed once stack
1950// corruptions are found.
1951#pragma clang optimize off
1952class StackGuard {
1953public:
1954 StackGuard(const char* name, const char* func, int line) {
1955 guarders.reserve(MIN_CAPACITY);
1956 guarders.push_back({this, name, func, line});
1957 validate();
1958 }
1959 ~StackGuard() {
1960 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1961 if (i->guard == this) {
1962 guarders.erase(i);
1963 break;
1964 }
1965 }
1966 }
1967
1968 static void validate() {
1969 for (const auto& guard : guarders) {
1970 if (guard.guard->cookie != COOKIE_VALUE) {
1971 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1972 CallStack stack(LOG_TAG);
1973 abort();
1974 }
1975 }
1976 }
1977
1978private:
1979 uint64_t cookie = COOKIE_VALUE;
1980 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1981 static constexpr size_t MIN_CAPACITY = 16;
1982
1983 struct GuarderElement {
1984 StackGuard* guard;
1985 const char* name;
1986 const char* func;
1987 int line;
1988 };
1989
1990 static std::vector<GuarderElement> guarders;
1991};
1992std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1993
1994#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1995
1996#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001997void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998{
Ady Abraham8164d482019-01-11 14:47:59 -08001999 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 ATRACE_CALL();
2001 ALOGV("postComposition");
2002
Brian Anderson3546a3f2016-07-14 11:51:14 -07002003 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002004 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002005 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002006 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002007 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002008 }
Ady Abraham8164d482019-01-11 14:47:59 -08002009 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002010
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002011 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002012 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002013 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002014
David Sodman73beded2017-11-15 11:56:06 -08002015 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002017 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2018
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002019 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002022 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 } else {
2024 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2025 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
Ady Abraham8164d482019-01-11 14:47:59 -08002027 ASSERT_ON_STACK_GUARD();
2028
David Sodman73beded2017-11-15 11:56:06 -08002029 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002030 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002031 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002032 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002033 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002034 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035
Ana Krulece588e312018-09-18 12:32:24 -07002036 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002037 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002038 if (mUseScheduler) {
2039 mScheduler->getDisplayStatInfo(&stats);
2040 } else {
2041 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2042 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2043 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044
Ady Abraham8164d482019-01-11 14:47:59 -08002045 ASSERT_ON_STACK_GUARD();
2046
David Sodman2b406362017-12-15 13:33:47 -08002047 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 // when we started doing work for this frame, but that should be okay
2049 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002050 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002051 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002052 DEFINE_STACK_GUARD(compositorTiming);
2053
Brian Andersond0010582017-03-07 13:20:31 -08002054 {
David Sodman99974d22017-11-28 12:04:33 -08002055 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002056 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002057 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002058
2059 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002060 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061
Robert Carr2047fae2016-11-28 14:09:09 -08002062 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002063 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2064 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002066 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002067 recordBufferingStats(layer->getName().string(),
2068 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002069 }
Ady Abraham8164d482019-01-11 14:47:59 -08002070 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002071 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002072
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002073 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002074 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002075 if (mUseScheduler) {
2076 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002077 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002078 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002079 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2080 enableHardwareVsync();
2081 } else {
2082 disableHardwareVsync(false);
2083 }
Ady Abraham8164d482019-01-11 14:47:59 -08002084 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002085 }
2086 }
2087
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002088 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002089 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002090 if (mUseScheduler) {
2091 mScheduler->enableHardwareVsync();
2092 } else {
2093 enableHardwareVsync();
2094 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002095 }
2096 }
2097
Ady Abraham8164d482019-01-11 14:47:59 -08002098 ASSERT_ON_STACK_GUARD();
2099
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002100 if (mAnimCompositionPending) {
2101 mAnimCompositionPending = false;
2102
Brian Anderson4e606e32017-03-16 15:34:57 -07002103 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002104 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002105 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002106
2107 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002108 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002109 // The HWC doesn't support present fences, so use the refresh
2110 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002111 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002112 DEFINE_STACK_GUARD(presentTime);
2113
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002114 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002115 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116 }
2117 mAnimFrameTracker.advanceFrame();
2118 }
Dan Stozab90cf072015-03-05 11:05:59 -08002119
Ady Abraham8164d482019-01-11 14:47:59 -08002120 ASSERT_ON_STACK_GUARD();
2121
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002122 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002123 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002124 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002125 }
2126
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
2128
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002129 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002130
Ady Abraham8164d482019-01-11 14:47:59 -08002131 ASSERT_ON_STACK_GUARD();
2132
Dominik Laskowski075d3172018-05-24 15:50:06 -07002133 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002134 return;
2135 }
2136
2137 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002138 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002139 if (mHasPoweredOff) {
2140 mHasPoweredOff = false;
2141 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002142 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002143 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002144 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002146 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2147 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002148 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002149 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002150 }
David Sodman4a36e932017-11-07 14:29:47 -08002151 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002152
2153 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002154 }
David Sodman4a36e932017-11-07 14:29:47 -08002155 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002156 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002157
2158 {
2159 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002161 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002162 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002163 if (refillCount > 0) {
2164 const size_t offset = mTexturePool.size();
2165 mTexturePool.resize(mTexturePoolSize);
2166 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2167 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2168 }
Ady Abraham8164d482019-01-11 14:47:59 -08002169 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002170 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002171
Marissa Wallfda30bb2018-10-12 11:34:28 -07002172 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002173 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002174
2175 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002176}
Ady Abraham8164d482019-01-11 14:47:59 -08002177#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002178
2179void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 ATRACE_CALL();
2181 ALOGV("rebuildLayerStacks");
2182
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002183 // We need to clear these out now as these may be holding on to a
2184 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2185 // also holds a reference. When the set of visible layers is recomputed,
2186 // some layers may be destroyed if the only thing keeping them alive was
2187 // that list of visible layers associated with each display. The layer
2188 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2189 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2190 for (const auto& [token, display] : mDisplays) {
2191 getBE().mCompositionInfo[token].clear();
2192 }
2193
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002195 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002196 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002197 mVisibleRegionsDirty = false;
2198 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002199
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002200 for (const auto& pair : mDisplays) {
2201 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002202 Region opaqueRegion;
2203 Region dirtyRegion;
2204 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002205 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002206 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002207 const Rect bounds = display->getBounds();
2208 if (display->isPoweredOn()) {
2209 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002212 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002213 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002214 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 Region drawRegion(tr.transform(
2216 layer->visibleNonTransparentRegion));
2217 drawRegion.andSelf(bounds);
2218 if (!drawRegion.isEmpty()) {
2219 layersSortedByZ.add(layer);
2220 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002221 // Clear out the HWC layer if this layer was
2222 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002223 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002224 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002225 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002226 // WM changes display->layerStack upon sleep/awake.
2227 // Here we make sure we delete the HWC layers even if
2228 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002229 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002230 }
2231
2232 // If a layer is not going to get a release fence because
2233 // it is invisible, but it is also going to release its
2234 // old buffer, add it to the list of layers needing
2235 // fences.
2236 if (hwcLayerDestroyed) {
2237 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2238 mLayersWithQueuedFrames.cend(), layer);
2239 if (found != mLayersWithQueuedFrames.cend()) {
2240 layersNeedingFences.add(layer);
2241 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002242 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002243 });
2244 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 display->setVisibleLayersSortedByZ(layersSortedByZ);
2246 display->setLayersNeedingFences(layersNeedingFences);
2247 display->undefinedRegion.set(bounds);
2248 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2249 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002250 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002251 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002252}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002253
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002254// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002256// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002258// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002259// The returned HDR data space is one of
2260// - Dataspace::UNKNOWN
2261// - Dataspace::BT2020_HLG
2262// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002263Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2264 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002265 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002266 *outHdrDataSpace = Dataspace::UNKNOWN;
2267
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002268 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002269 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002270 case Dataspace::V0_SCRGB:
2271 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002272 case Dataspace::BT2020:
2273 case Dataspace::BT2020_ITU:
2274 case Dataspace::BT2020_LINEAR:
2275 case Dataspace::DISPLAY_BT2020:
2276 bestDataSpace = Dataspace::DISPLAY_BT2020;
2277 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002279 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002280 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002281 case Dataspace::BT2020_PQ:
2282 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002285 case Dataspace::BT2020_HLG:
2286 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 // When there's mixed PQ content and HLG content, we set the HDR
2288 // data space to be BT2020_PQ and convert HLG to PQ.
2289 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2290 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002291 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002292 break;
2293 default:
2294 break;
2295 }
Romain Guy54f154a2017-10-24 21:40:32 +01002296 }
2297
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002299}
2300
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2303 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2305 *outMode = ColorMode::NATIVE;
2306 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002309 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002310
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313
Peiyong Lindfde5112018-06-05 10:58:41 -07002314 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002315 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002316 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002317 if (isHdr) {
2318 bestDataSpace = hdrDataSpace;
2319 }
2320
Chia-I Wu0d711262018-05-21 15:19:35 -07002321 RenderIntent intent;
2322 switch (mDisplayColorSetting) {
2323 case DisplayColorSetting::MANAGED:
2324 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002325 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002326 break;
2327 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002328 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002329 break;
2330 default: // vendor display color setting
2331 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2332 break;
2333 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002336}
2337
David Sodmanfa9b2af2017-12-24 13:28:59 -08002338void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002339{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002340 bool dirty = !display->getDirtyRegion(false).isEmpty();
2341 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2342 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002343
David Sodmanfa9b2af2017-12-24 13:28:59 -08002344 // If nothing has changed (!dirty), don't recompose.
2345 // If something changed, but we don't currently have any visible layers,
2346 // and didn't when we last did a composition, then skip it this time.
2347 // The second rule does two things:
2348 // - When all layers are removed from a display, we'll emit one black
2349 // frame, then nothing more until we get new layers.
2350 // - When a display is created with a private layer stack, we won't
2351 // emit any black frames until a layer is added to the layer stack.
2352 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002353
Dominik Laskowski075d3172018-05-24 15:50:06 -07002354 const char flagPrefix[] = {'-', '+'};
2355 static_cast<void>(flagPrefix);
2356 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2357 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2358 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002359
David Sodmanfa9b2af2017-12-24 13:28:59 -08002360 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002361
David Sodmanfa9b2af2017-12-24 13:28:59 -08002362 if (mustRecompose) {
2363 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002364 }
2365}
2366
David Sodmanfa9b2af2017-12-24 13:28:59 -08002367void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002368{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002369 if (!display->isPoweredOn()) {
2370 return;
David Sodman2b406362017-12-15 13:33:47 -08002371 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002372
Dominik Laskowski05275f12018-11-01 15:03:24 -07002373 status_t result = display->prepareFrame(getHwComposer(),
2374 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002375 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2376 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002377}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002378
David Sodmanfa9b2af2017-12-24 13:28:59 -08002379void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002380 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002381 ALOGV("doComposition");
2382
David Sodmanfa9b2af2017-12-24 13:28:59 -08002383 if (display->isPoweredOn()) {
2384 // transform the dirty region into this screen's coordinate space
2385 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002386
David Sodmanfa9b2af2017-12-24 13:28:59 -08002387 // repaint the framebuffer (if needed)
2388 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002389
David Sodmanfa9b2af2017-12-24 13:28:59 -08002390 display->dirtyRegion.clear();
2391 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002392 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002393 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002394}
2395
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396void SurfaceFlinger::postFrame()
2397{
2398 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 const auto display = getDefaultDisplayDeviceLocked();
2400 if (display && getHwComposer().isConnected(*display->getId())) {
2401 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002402 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2403 logFrameStats();
2404 }
2405 }
2406}
2407
2408void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409{
Mathias Agopian841cde52012-03-01 15:44:37 -08002410 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002412
David Sodmanfa9b2af2017-12-24 13:28:59 -08002413 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002414
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002416 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002417 if (displayId) {
2418 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002419 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002420 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002421 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002422 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002423
Chia-I Wu7b549592017-11-15 09:14:57 -08002424 // The layer buffer from the previous frame (if any) is released
2425 // by HWC only when the release fence from this frame (if any) is
2426 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 if (displayId && layer->hasHwcLayer(*displayId)) {
2428 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2429 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002430 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002431
2432 // If the layer was client composited in the previous frame, we
2433 // need to merge with the previous client target acquire fence.
2434 // Since we do not track that, always merge with the current
2435 // client target acquire fence when it is available, even though
2436 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002437 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002438 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002440 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002441
David Sodman15094112018-10-11 09:39:37 -07002442 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 }
Chia-I Wu83806892017-11-16 10:50:20 -08002444
2445 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002447 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002450 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002452 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002453 }
2454 }
2455
Dominik Laskowski075d3172018-05-24 15:50:06 -07002456 if (displayId) {
2457 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002458 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002459 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460}
2461
Mathias Agopian87baae12012-07-31 12:38:26 -07002462void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463{
Mathias Agopian841cde52012-03-01 15:44:37 -08002464 ATRACE_CALL();
2465
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002466 // here we keep a copy of the drawing state (that is the state that's
2467 // going to be overwritten by handleTransactionLocked()) outside of
2468 // mStateLock so that the side-effects of the State assignment
2469 // don't happen with mStateLock held (which can cause deadlocks).
2470 State drawingState(mDrawingState);
2471
Mathias Agopianca4d3602011-05-19 15:38:14 -07002472 Mutex::Autolock _l(mStateLock);
2473 const nsecs_t now = systemTime();
2474 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475
Mathias Agopianca4d3602011-05-19 15:38:14 -07002476 // Here we're guaranteed that some transaction flags are set
2477 // so we can call handleTransactionLocked() unconditionally.
2478 // We call getTransactionFlags(), which will also clear the flags,
2479 // with mStateLock held to guarantee that mCurrentState won't change
2480 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002481
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002482 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002483 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002484 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002485
Mathias Agopianca4d3602011-05-19 15:38:14 -07002486 mLastTransactionTime = systemTime() - now;
2487 mDebugInTransaction = 0;
2488 invalidateHwcGeometry();
2489 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002490}
2491
Lloyd Piqueba04e622017-12-14 17:11:26 -08002492void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2493 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 const std::optional<DisplayIdentificationInfo> info =
2495 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002496
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498 continue;
2499 }
2500
Lloyd Piqueba04e622017-12-14 17:11:26 -08002501 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002503 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 mPhysicalDisplayTokens[info->id] = new BBinder();
2505 DisplayDeviceState state;
2506 state.displayId = info->id;
2507 state.isSecure = true; // All physical displays are currently considered secure.
2508 state.displayName = info->name;
2509 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2510 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002511 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002512 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002513 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2516 if (index >= 0) {
2517 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2518 mInterceptor->saveDisplayDeletion(state.sequenceId);
2519 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002520 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002521 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002522 }
2523
2524 processDisplayChangesLocked();
2525 }
2526
2527 mPendingHotplugEvents.clear();
2528}
2529
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2532 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2533 const sp<IGraphicBufferProducer>& producer) {
2534 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002535 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002537 creationArgs.isSecure = state.isSecure;
2538 creationArgs.displaySurface = dispSurface;
2539 creationArgs.hasWideColorGamut = false;
2540 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002541
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2543 creationArgs.isPrimary = isInternalDisplay;
2544
2545 if (useColorManagement && displayId) {
2546 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002548 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002549 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002550 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002551
Dominik Laskowski7e045462018-05-30 13:02:02 -07002552 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002554 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555 }
tangrobin6753a022018-08-10 10:58:54 +08002556 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 if (displayId) {
2559 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002560 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002561 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002562 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563
Lloyd Pique90c115d2018-09-18 21:39:42 -07002564 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002565 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002566 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002567
Lloyd Pique99d3da52018-01-22 17:48:03 -08002568 // Make sure that composition can never be stalled by a virtual display
2569 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002570 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002571 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2573 }
2574
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 creationArgs.displayInstallOrientation =
2576 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002577
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002579 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002580
Lloyd Pique90c115d2018-09-18 21:39:42 -07002581 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582
2583 if (maxFrameBufferAcquiredBuffers >= 3) {
2584 nativeWindowSurface->preallocateBuffers();
2585 }
2586
2587 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002588 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002589 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002591 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002593 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002594 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 if (!state.isVirtual()) {
2596 LOG_ALWAYS_FATAL_IF(!displayId);
2597 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002598 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 display->setLayerStack(state.layerStack);
2601 display->setProjection(state.orientation, state.viewport, state.frame);
2602 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605}
2606
Lloyd Pique347200f2017-12-14 17:00:15 -08002607void SurfaceFlinger::processDisplayChangesLocked() {
2608 // here we take advantage of Vector's copy-on-write semantics to
2609 // improve performance by skipping the transaction entirely when
2610 // know that the lists are identical
2611 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2612 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2613 if (!curr.isIdenticalTo(draw)) {
2614 mVisibleRegionsDirty = true;
2615 const size_t cc = curr.size();
2616 size_t dc = draw.size();
2617
2618 // find the displays that were removed
2619 // (ie: in drawing state but not in current state)
2620 // also handle displays that changed
2621 // (ie: displays that are in both lists)
2622 for (size_t i = 0; i < dc;) {
2623 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2624 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 // Save display IDs before disconnecting.
2626 const auto internalDisplayId = getInternalDisplayId();
2627 const auto externalDisplayId = getExternalDisplayId();
2628
Lloyd Pique347200f2017-12-14 17:00:15 -08002629 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002630 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2631 display->disconnect(getHwComposer());
2632 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002634 if (mUseScheduler) {
2635 mScheduler->hotplugReceived(mAppConnectionHandle,
2636 EventThread::DisplayType::Primary, false);
2637 } else {
2638 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2639 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002641 if (mUseScheduler) {
2642 mScheduler->hotplugReceived(mAppConnectionHandle,
2643 EventThread::DisplayType::External, false);
2644 } else {
2645 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2646 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002647 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002648 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 } else {
2650 // this display is in both lists. see if something changed.
2651 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002653 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2654 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2655 if (state_binder != draw_binder) {
2656 // changing the surface is like destroying and
2657 // recreating the DisplayDevice, so we just remove it
2658 // from the drawing state, so that it get re-added
2659 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002660 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2661 display->disconnect(getHwComposer());
2662 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002663 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002664 mDrawingState.displays.removeItemsAt(i);
2665 dc--;
2666 // at this point we must loop to the next item
2667 continue;
2668 }
2669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002671 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 }
2674 if ((state.orientation != draw[i].orientation) ||
2675 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 }
2678 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002679 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 }
2681 }
2682 }
2683 ++i;
2684 }
2685
2686 // find displays that were added
2687 // (ie: in current state but not in drawing state)
2688 for (size_t i = 0; i < cc; i++) {
2689 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2690 const DisplayDeviceState& state(curr[i]);
2691
2692 sp<DisplaySurface> dispSurface;
2693 sp<IGraphicBufferProducer> producer;
2694 sp<IGraphicBufferProducer> bqProducer;
2695 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002696 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002697
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002699 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 // Virtual displays without a surface are dormant:
2701 // they have external state (layer stack, projection,
2702 // etc.) but no internal state (i.e. a DisplayDevice).
2703 if (state.surface != nullptr) {
2704 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 int width = 0;
2707 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2708 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2709 int height = 0;
2710 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2711 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2712 int intFormat = 0;
2713 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2714 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002715 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717 displayId =
2718 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002719 }
2720
2721 // TODO: Plumb requested format back up to consumer
2722
2723 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002724 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 bqProducer, bqConsumer,
2726 state.displayName);
2727
2728 dispSurface = vds;
2729 producer = vds;
2730 }
2731 } else {
2732 ALOGE_IF(state.surface != nullptr,
2733 "adding a supported display, but rendering "
2734 "surface is provided (%p), ignoring it",
2735 state.surface.get());
2736
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 displayId = state.displayId;
2738 LOG_ALWAYS_FATAL_IF(!displayId);
2739 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 producer = bqProducer;
2741 }
2742
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002743 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002745 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002746 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002747 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002748 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002749 LOG_ALWAYS_FATAL_IF(!displayId);
2750
2751 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002752 if (mUseScheduler) {
2753 mScheduler->hotplugReceived(mAppConnectionHandle,
2754 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002755 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002756 } else {
2757 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2758 true);
2759 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002760 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002761 if (mUseScheduler) {
2762 mScheduler->hotplugReceived(mAppConnectionHandle,
2763 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002764 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002765 } else {
2766 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2767 true);
2768 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002769 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002770 }
2771 }
2772 }
2773 }
2774 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002775
2776 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002777}
2778
Mathias Agopian87baae12012-07-31 12:38:26 -07002779void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002780{
Dan Stoza7dde5992015-05-22 09:51:44 -07002781 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002782 mCurrentState.traverseInZOrder([](Layer* layer) {
2783 layer->notifyAvailableFrames();
2784 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 /*
2787 * Traversal of the children
2788 * (perform the transaction for each of them if needed)
2789 */
2790
Robert Carr720e5062018-07-30 17:45:14 -07002791 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002792 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002793 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002795 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
2797 const uint32_t flags = layer->doTransaction(0);
2798 if (flags & Layer::eVisibleRegion)
2799 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002800
2801 if (flags & Layer::eInputInfoChanged) {
2802 inputChanged = true;
2803 }
Robert Carr2047fae2016-11-28 14:09:09 -08002804 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 }
2806
2807 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002808 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 */
2810
Mathias Agopiane57f2922012-08-09 16:29:12 -07002811 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002812 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002813 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002816 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002817 // The transform hint might have changed for some layers
2818 // (either because a display has changed, or because a layer
2819 // as changed).
2820 //
2821 // Walk through all the layers in currentLayers,
2822 // and update their transform hint.
2823 //
2824 // If a layer is visible only on a single display, then that
2825 // display is used to calculate the hint, otherwise we use the
2826 // default display.
2827 //
2828 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2829 // the hint is set before we acquire a buffer from the surface texture.
2830 //
2831 // NOTE: layer transactions have taken place already, so we use their
2832 // drawing state. However, SurfaceFlinger's own transaction has not
2833 // happened yet, so we must use the current state layer list
2834 // (soon to become the drawing state list).
2835 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002837 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002838 bool first = true;
2839 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002840 // NOTE: we rely on the fact that layers are sorted by
2841 // layerStack first (so we don't have to traverse the list
2842 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002844 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002845 currentlayerStack = layerStack;
2846 // figure out if this layerstack is mirrored
2847 // (more than one display) if so, pick the default display,
2848 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002849 hintDisplay = nullptr;
2850 for (const auto& [token, display] : mDisplays) {
2851 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2852 if (hintDisplay) {
2853 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002854 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002856 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002857 }
2858 }
2859 }
2860 }
Chet Haase91d25932013-04-11 15:24:55 -07002861
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002862 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002863 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2864 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002865
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002866 // could be null when this layer is using a layerStack
2867 // that is not visible on any display. Also can occur at
2868 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002870 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002871
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002872 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002873 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 if (hintDisplay) {
2875 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002876 }
Robert Carr2047fae2016-11-28 14:09:09 -08002877
2878 first = false;
2879 });
Mathias Agopian84300952012-11-21 16:02:13 -08002880 }
2881
2882
Mathias Agopian3559b072012-08-15 13:46:03 -07002883 /*
2884 * Perform our own transaction if needed
2885 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886
2887 if (mLayersAdded) {
2888 mLayersAdded = false;
2889 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002890 mVisibleRegionsDirty = true;
2891 }
2892
2893 // some layers might have been removed, so
2894 // we need to update the regions they're exposing.
2895 if (mLayersRemoved) {
2896 mLayersRemoved = false;
2897 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002898 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002899 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002900 // this layer is not visible anymore
2901 // TODO: we could traverse the tree from front to back and
2902 // compute the actual visible region
2903 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002904 Region visibleReg;
2905 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002906 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002907 }
Robert Carr2047fae2016-11-28 14:09:09 -08002908 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909 }
2910
2911 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002912
Vishnu Nairde19f852018-12-18 16:11:53 -08002913 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002914 updateInputWindows();
2915 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002916 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002917
Riley Andrews03414a12014-07-01 14:22:59 -07002918 updateCursorAsync();
2919}
2920
Robert Carr720e5062018-07-30 17:45:14 -07002921void SurfaceFlinger::updateInputWindows() {
2922 ATRACE_CALL();
2923
Vishnu Nairde19f852018-12-18 16:11:53 -08002924 if (mInputFlinger == nullptr) {
2925 return;
2926 }
2927
Robert Carr720e5062018-07-30 17:45:14 -07002928 Vector<InputWindowInfo> inputHandles;
2929
2930 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2931 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002932 // When calculating the screen bounds we ignore the transparent region since it may
2933 // result in an unwanted offset.
2934 inputHandles.add(layer->fillInputInfo(
2935 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002936 }
2937 });
2938 mInputFlinger->setInputWindows(inputHandles);
2939}
2940
chaviwfbe5d9c2018-12-26 12:23:37 -08002941void SurfaceFlinger::executeInputWindowCommands() {
2942 if (!mInputFlinger) {
2943 return;
2944 }
2945
2946 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2947 if (transferTouchFocusCommand.fromToken != nullptr &&
2948 transferTouchFocusCommand.toToken != nullptr &&
2949 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2950 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2951 transferTouchFocusCommand.toToken);
2952 }
2953 }
2954
2955 mInputWindowCommands.clear();
2956}
2957
Riley Andrews03414a12014-07-01 14:22:59 -07002958void SurfaceFlinger::updateCursorAsync()
2959{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002960 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002961 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002962 continue;
2963 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002965 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2966 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002967 }
2968 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002969}
2970
chaviw61626f22018-11-15 16:26:27 -08002971void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2972 if (layer->hasReadyFrame()) {
2973 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2974 if (layer->shouldPresentNow(expectedPresentTime)) {
2975 bool ignored = false;
2976 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2977 }
2978 }
2979 layer->releasePendingBuffer(systemTime());
2980}
2981
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982void SurfaceFlinger::commitTransaction()
2983{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002984 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002985 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002986 for (const auto& l : mLayersPendingRemoval) {
2987 recordBufferingStats(l->getName().string(),
2988 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002989
2990 // We need to release the HWC layers when the Layer is removed
2991 // from the current state otherwise the HWC layer just continues
2992 // showing at its last configured state until we eventually
2993 // abandon the buffer queue.
2994 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002995 l->destroyHwcLayersForAllDisplays();
2996 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002997 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 }
2999 mLayersPendingRemoval.clear();
3000 }
3001
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003002 // If this transaction is part of a window animation then the next frame
3003 // we composite should be considered an animation as well.
3004 mAnimCompositionPending = mAnimTransactionPending;
3005
Mathias Agopian4fec8732012-06-29 14:12:52 -07003006 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003007 // clear the "changed" flags in current state
3008 mCurrentState.colorMatrixChanged = false;
3009
Robert Carr1f0a16a2016-10-24 16:27:39 -07003010 mDrawingState.traverseInZOrder([](Layer* layer) {
3011 layer->commitChildList();
3012 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003013 mTransactionPending = false;
3014 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016}
3017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3019 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003020 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003022
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003023 Region aboveOpaqueLayers;
3024 Region aboveCoveredLayers;
3025 Region dirty;
3026
Mathias Agopian87baae12012-07-31 12:38:26 -07003027 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028
Robert Carr2047fae2016-11-28 14:09:09 -08003029 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003030 // start with the whole surface at its current location
3031 const Layer::State& s(layer->getDrawingState());
3032
Jesse Hall01e29052013-02-19 16:13:35 -08003033 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003035 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003037
Mathias Agopianab028732010-03-16 16:41:46 -07003038 /*
3039 * opaqueRegion: area of a surface that is fully opaque.
3040 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003042
3043 /*
3044 * visibleRegion: area of a surface that is visible on screen
3045 * and not fully transparent. This is essentially the layer's
3046 * footprint minus the opaque regions above it.
3047 * Areas covered by a translucent surface are considered visible.
3048 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003050
3051 /*
3052 * coveredRegion: area of a surface that is covered by all
3053 * visible regions above it (which includes the translucent areas).
3054 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003056
Jesse Halla8026d22012-09-25 13:25:04 -07003057 /*
3058 * transparentRegion: area of a surface that is hinted to be completely
3059 * transparent. This is only used to tell when the layer has no visible
3060 * non-transparent regions and can be removed from the layer list. It
3061 * does not affect the visibleRegion of this layer or any layers
3062 * beneath it. The hint may not be correct if apps don't respect the
3063 * SurfaceView restrictions (which, sadly, some don't).
3064 */
3065 Region transparentRegion;
3066
Mathias Agopianab028732010-03-16 16:41:46 -07003067
3068 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003069 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003070 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003074 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003075 if (!visibleRegion.isEmpty()) {
3076 // Remove the transparent area from the visible region
3077 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003078 if (tr.preserveRects()) {
3079 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003080 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003081 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003082 // transformation too complex, can't do the
3083 // transparent region optimization.
3084 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003085 }
Mathias Agopianab028732010-03-16 16:41:46 -07003086 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087
Mathias Agopianab028732010-03-16 16:41:46 -07003088 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003090 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003091 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003092 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003093 // the opaque region is the layer's footprint
3094 opaqueRegion = visibleRegion;
3095 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 }
3097 }
3098
Robert Carre5f4f692018-01-12 13:12:28 -08003099 if (visibleRegion.isEmpty()) {
3100 layer->clearVisibilityRegions();
3101 return;
3102 }
3103
Mathias Agopianab028732010-03-16 16:41:46 -07003104 // Clip the covered region to the visible region
3105 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3106
3107 // Update aboveCoveredLayers for next (lower) layer
3108 aboveCoveredLayers.orSelf(visibleRegion);
3109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 // subtract the opaque region covered by the layers above us
3111 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112
3113 // compute this layer's dirty region
3114 if (layer->contentDirty) {
3115 // we need to invalidate the whole region
3116 dirty = visibleRegion;
3117 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003118 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119 layer->contentDirty = false;
3120 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003121 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003122 * the exposed region consists of two components:
3123 * 1) what's VISIBLE now and was COVERED before
3124 * 2) what's EXPOSED now less what was EXPOSED before
3125 *
3126 * note that (1) is conservative, we start with the whole
3127 * visible region but only keep what used to be covered by
3128 * something -- which mean it may have been exposed.
3129 *
3130 * (2) handles areas that were not covered by anything but got
3131 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003132 */
Mathias Agopianab028732010-03-16 16:41:46 -07003133 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003134 const Region oldVisibleRegion = layer->visibleRegion;
3135 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003136 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3137 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 }
3139 dirty.subtractSelf(aboveOpaqueLayers);
3140
3141 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003142 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143
Mathias Agopianab028732010-03-16 16:41:46 -07003144 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003146
Jesse Halla8026d22012-09-25 13:25:04 -07003147 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 layer->setVisibleRegion(visibleRegion);
3149 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003150 layer->setVisibleNonTransparentRegion(
3151 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003152 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153
Mathias Agopian87baae12012-07-31 12:38:26 -07003154 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155}
3156
Chia-I Wuab0c3192017-08-01 11:29:00 -07003157void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003158 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003159 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3160 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003161 }
3162 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003163}
3164
Dan Stoza6b9454d2014-11-07 16:00:59 -08003165bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003167 ALOGV("handlePageFlip");
3168
Brian Andersond6927fb2016-07-23 23:37:30 -07003169 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
Mathias Agopian4fec8732012-06-29 14:12:52 -07003171 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003172 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003173 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003174
3175 // Store the set of layers that need updates. This set must not change as
3176 // buffers are being latched, as this could result in a deadlock.
3177 // Example: Two producers share the same command stream and:
3178 // 1.) Layer 0 is latched
3179 // 2.) Layer 0 gets a new frame
3180 // 2.) Layer 1 gets a new frame
3181 // 3.) Layer 1 is latched.
3182 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3183 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003184 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003185 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003186 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003187 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3188 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003189 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003190 } else {
3191 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003192 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003193 } else {
3194 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003195 }
Robert Carr2047fae2016-11-28 14:09:09 -08003196 });
3197
Lloyd Piquef2c79392018-12-20 16:23:33 -08003198 if (!mLayersWithQueuedFrames.empty()) {
3199 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3200 // writes to Layer current state. See also b/119481871
3201 Mutex::Autolock lock(mStateLock);
3202
3203 for (auto& layer : mLayersWithQueuedFrames) {
3204 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3205 layer->useSurfaceDamage();
3206 invalidateLayerStack(layer, dirty);
3207 if (layer->isBufferLatched()) {
3208 newDataLatched = true;
3209 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003210 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003211 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003212
Alec Mouri86770e52018-09-24 22:40:58 +00003213 // Clear the renderengine fence here...
3214 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3215 // clear instead of sp::clear.
3216 getBE().flushFence = Fence::NO_FENCE;
3217
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003218 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003219
Vishnu Nairde19f852018-12-18 16:11:53 -08003220 if (visibleRegions) {
3221 // Update input window info if the layer receives its first buffer.
3222 updateInputWindows();
3223 }
3224
Dan Stoza6b9454d2014-11-07 16:00:59 -08003225 // If we will need to wake up at some time in the future to deal with a
3226 // queued frame that shouldn't be displayed during this vsync period, wake
3227 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003228 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003229 signalLayerUpdate();
3230 }
3231
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003232 // enter boot animation on first buffer latch
3233 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3234 ALOGI("Enter boot animation");
3235 mBootStage = BootStage::BOOTANIMATION;
3236 }
3237
Dan Stoza6b9454d2014-11-07 16:00:59 -08003238 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003239 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Mathias Agopianad456f92011-01-13 17:53:01 -08003242void SurfaceFlinger::invalidateHwcGeometry()
3243{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003244 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003245}
3246
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003247void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003248 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003249 // We only need to actually compose the display if:
3250 // 1) It is being handled by hardware composer, which may need this to
3251 // keep its virtual display state machine in sync, or
3252 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003253 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003254 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003255 return;
3256 }
3257
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003259 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003260
3261 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003262 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263}
3264
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003265bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003266 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003267
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003268 const Region bounds(display->bounds());
3269 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003270 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003271 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003272 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003273
Peiyong Lind3788632018-09-18 16:01:31 -07003274 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003275 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003276
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003277 // Framebuffer will live in this scope for GPU composition.
3278 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3279
Dan Stoza9e56aa02015-11-02 13:00:03 -08003280 if (hasClientComposition) {
3281 ALOGV("hasClientComposition");
3282
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003283 sp<GraphicBuffer> buf = display->dequeueBuffer();
3284
3285 if (buf == nullptr) {
3286 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3287 "client composition for this frame",
3288 display->getDisplayName().c_str());
3289 return false;
3290 }
3291
3292 // Bind the framebuffer in this scope.
3293 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3294 buf->getNativeBuffer());
3295
3296 if (fbo->getStatus() != NO_ERROR) {
3297 ALOGW("Binding buffer for display [%s] failed with status: %d",
3298 display->getDisplayName().c_str(), fbo->getStatus());
3299 return false;
3300 }
3301
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003302 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003303 if (display->hasWideColorGamut()) {
3304 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003305 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003306 getRenderEngine().setOutputDataSpace(outputDataspace);
3307 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003308 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003309
Lloyd Pique441d5042018-10-18 16:49:51 -07003310 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003311 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 getHwComposer()
3313 .hasDisplayCapability(displayId,
3314 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003315
Peiyong Lind3788632018-09-18 16:01:31 -07003316 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003317 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3318 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003319 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003320 }
3321
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003322 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003323
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003324 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003325 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003326 // when using overlays, we assume a fully transparent framebuffer
3327 // NOTE: we could reduce how much we need to clear, for instance
3328 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003329 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003330 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003331 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003332 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003333 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003334 // we're left with the letterbox region
3335 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003336 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003337
3338 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003339 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003340
Mathias Agopianb9494d52012-04-18 02:28:45 -07003341 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003342 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003343 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003344 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003345 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003346 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003347
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003348 const Rect& bounds = display->getBounds();
3349 const Rect& scissor = display->getScissor();
3350 if (scissor != bounds) {
3351 // scissor doesn't match the screen's dimensions, so we
3352 // need to clear everything outside of it and enable
3353 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003354
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003355 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003356 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003357 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003358 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003359
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 /*
3361 * and then, render the layers targeted at the framebuffer
3362 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003365 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003366 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003367 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003368 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003369 displayTransform.transform(layer->visibleRegion)));
3370 ALOGV("Layer: %s", layer->getName().string());
3371 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003372 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003373 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003374 case HWC2::Composition::Cursor:
3375 case HWC2::Composition::Device:
3376 case HWC2::Composition::Sideband:
3377 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003378 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003379 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003380 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003382 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003383 // never clear the very first layer since we're
3384 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003385 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003386 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003387 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003388 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003389 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003390 if (layer->hasColorTransform()) {
3391 mat4 tmpMatrix;
3392 if (applyColorMatrix) {
3393 tmpMatrix = mDrawingState.colorMatrix;
3394 }
3395 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003396 getRenderEngine().setColorTransform(tmpMatrix);
3397 } else {
3398 getRenderEngine().setColorTransform(colorMatrix);
3399 }
David Sodmanc1498e62018-09-12 14:36:26 -07003400 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 break;
3402 }
3403 default:
3404 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003405 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 } else {
3407 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003408 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003410 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003411
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003412 // Perform some cleanup steps if we used client composition.
3413 if (hasClientComposition) {
3414 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003415 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003416 display->finishBuffer();
3417 // Clear out error flags here so that we don't wait until next
3418 // composition to log.
3419 getRenderEngine().checkErrors();
3420 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003421 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422}
3423
Chia-I Wu28e3a252018-09-07 12:05:02 -07003424void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003425 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003426 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003427}
3428
Dan Stoza7d89d062015-04-30 13:29:25 -07003429status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003430 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003431 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003432 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003433 const sp<Layer>& parent,
3434 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003435{
Dan Stoza7d89d062015-04-30 13:29:25 -07003436 // add this layer to the current state list
3437 {
3438 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003439 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003440 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3441 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003442 return NO_MEMORY;
3443 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003444 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003445 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003446 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003447 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003448 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003449 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 parent->addChild(lbc);
3451 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003452
Yiwei Zhang243b3782018-05-15 17:40:04 -07003453 if (gbc != nullptr) {
3454 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3455 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3456 mMaxGraphicBufferProducerListSize,
3457 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3458 mGraphicBufferProducerList.size(),
3459 mMaxGraphicBufferProducerListSize, mNumLayers);
3460 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003461 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003462 }
3463
Mathias Agopian96f08192010-06-02 23:28:45 -07003464 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003465 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003466
Dan Stoza7d89d062015-04-30 13:29:25 -07003467 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003468}
3469
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003470uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003471 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003472}
3473
Mathias Agopian3f844832013-08-07 21:24:32 -07003474uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003475 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476}
3477
Mathias Agopian3f844832013-08-07 21:24:32 -07003478uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003479 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003480}
3481
3482uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003483 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003484 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003485 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003487 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488 }
3489 return old;
3490}
3491
Marissa Wall713b63f2018-10-17 15:42:43 -07003492bool SurfaceFlinger::flushTransactionQueues() {
3493 Mutex::Autolock _l(mStateLock);
3494 auto it = mTransactionQueues.begin();
3495 while (it != mTransactionQueues.end()) {
3496 auto& [applyToken, transactionQueue] = *it;
3497
3498 while (!transactionQueue.empty()) {
3499 const auto& [states, displays, flags] = transactionQueue.front();
3500 if (composerStateContainsUnsignaledFences(states)) {
3501 break;
3502 }
chaviw273171b2018-12-26 11:46:30 -08003503 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003504 transactionQueue.pop();
3505 }
3506
3507 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3508 }
3509 return mTransactionQueues.empty();
3510}
3511
chaviwca27f252018-02-06 16:46:39 -08003512bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3513 for (const ComposerState& state : states) {
3514 // Here we need to check that the interface we're given is indeed
3515 // one of our own. A malicious client could give us a nullptr
3516 // IInterface, or one of its own or even one of our own but a
3517 // different type. All these situations would cause us to crash.
3518 if (state.client == nullptr) {
3519 return true;
3520 }
3521
3522 sp<IBinder> binder = IInterface::asBinder(state.client);
3523 if (binder == nullptr) {
3524 return true;
3525 }
3526
3527 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3528 return true;
3529 }
3530 }
3531 return false;
3532}
3533
Marissa Wall713b63f2018-10-17 15:42:43 -07003534bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3535 for (const ComposerState& state : states) {
3536 const layer_state_t& s = state.state;
3537 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3538 continue;
3539 }
3540 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3541 return true;
3542 }
3543 }
3544 return false;
3545}
3546
3547void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3548 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003549 const sp<IBinder>& applyToken,
3550 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003551 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003552 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003553
chaviwca27f252018-02-06 16:46:39 -08003554 if (containsAnyInvalidClientState(states)) {
3555 return;
3556 }
3557
Marissa Wall713b63f2018-10-17 15:42:43 -07003558 // If its TransactionQueue already has a pending TransactionState or if it is pending
3559 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3560 composerStateContainsUnsignaledFences(states)) {
3561 mTransactionQueues[applyToken].emplace(states, displays, flags);
3562 setTransactionFlags(eTransactionNeeded);
3563 return;
3564 }
3565
chaviw273171b2018-12-26 11:46:30 -08003566 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003567}
3568
3569void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003570 const Vector<DisplayState>& displays, uint32_t flags,
3571 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003572 uint32_t transactionFlags = 0;
3573
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003574 if (flags & eAnimation) {
3575 // For window updates that are part of an animation we must wait for
3576 // previous animation "frames" to be handled.
3577 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003578 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003579 if (CC_UNLIKELY(err != NO_ERROR)) {
3580 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003581 // caller after a few seconds.
3582 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3583 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003584 mAnimTransactionPending = false;
3585 break;
3586 }
3587 }
3588 }
3589
chaviwca27f252018-02-06 16:46:39 -08003590 for (const DisplayState& display : displays) {
3591 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003592 }
3593
Marissa Walle2ffb422018-10-12 11:33:52 -07003594 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003595 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003596 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003597 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003598 // If the state doesn't require a traversal and there are callbacks, send them now
3599 if (!(clientStateFlags & eTraversalNeeded)) {
3600 mTransactionCompletedThread.sendCallbacks();
3601 }
3602 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003603
chaviw273171b2018-12-26 11:46:30 -08003604 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3605
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003606 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3607 // anyway. This can be used as a flush mechanism for previous async transactions.
3608 // Empty animation transaction can be used to simulate back-pressure, so also force a
3609 // transaction for empty animation transactions.
3610 if (transactionFlags == 0 &&
3611 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003612 transactionFlags = eTransactionNeeded;
3613 }
3614
Mathias Agopian386aa982011-11-07 21:58:03 -08003615 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003616 if (mInterceptor->isEnabled()) {
3617 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003618 }
Irvel468051e2016-06-13 16:44:44 -07003619
Mathias Agopian386aa982011-11-07 21:58:03 -08003620 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003621 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3622 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003623 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003624
3625 // if this is a synchronous transaction, wait for it to take effect
3626 // before returning.
3627 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003628 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003629 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 if (flags & eAnimation) {
3631 mAnimTransactionPending = true;
3632 }
3633 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003634 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3635 if (CC_UNLIKELY(err != NO_ERROR)) {
3636 // just in case something goes wrong in SF, return to the
3637 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003638 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3639 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003640 break;
3641 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 }
3644}
3645
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003646uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3647 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3648 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003649
Mathias Agopiane57f2922012-08-09 16:29:12 -07003650 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003651 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3652
3653 const uint32_t what = s.what;
3654 if (what & DisplayState::eSurfaceChanged) {
3655 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3656 state.surface = s.surface;
3657 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003658 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003659 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003660 if (what & DisplayState::eLayerStackChanged) {
3661 if (state.layerStack != s.layerStack) {
3662 state.layerStack = s.layerStack;
3663 flags |= eDisplayTransactionNeeded;
3664 }
3665 }
3666 if (what & DisplayState::eDisplayProjectionChanged) {
3667 if (state.orientation != s.orientation) {
3668 state.orientation = s.orientation;
3669 flags |= eDisplayTransactionNeeded;
3670 }
3671 if (state.frame != s.frame) {
3672 state.frame = s.frame;
3673 flags |= eDisplayTransactionNeeded;
3674 }
3675 if (state.viewport != s.viewport) {
3676 state.viewport = s.viewport;
3677 flags |= eDisplayTransactionNeeded;
3678 }
3679 }
3680 if (what & DisplayState::eDisplaySizeChanged) {
3681 if (state.width != s.width) {
3682 state.width = s.width;
3683 flags |= eDisplayTransactionNeeded;
3684 }
3685 if (state.height != s.height) {
3686 state.height = s.height;
3687 flags |= eDisplayTransactionNeeded;
3688 }
3689 }
3690
Mathias Agopiane57f2922012-08-09 16:29:12 -07003691 return flags;
3692}
3693
Robert Carrd4ae7f32018-06-07 16:10:57 -07003694bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3695 IPCThreadState* ipc = IPCThreadState::self();
3696 const int pid = ipc->getCallingPid();
3697 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003698 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003699 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003700 return false;
3701 }
3702 return true;
3703}
3704
chaviwca27f252018-02-06 16:46:39 -08003705uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3706 const layer_state_t& s = composerState.state;
3707 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3708
Mathias Agopian13127d82013-03-05 17:47:11 -08003709 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003710 if (layer == nullptr) {
3711 return 0;
3712 }
3713
chaviw8b3871a2017-11-01 17:41:01 -07003714 uint32_t flags = 0;
3715
Garfield Tan8a3083e2018-12-03 13:21:07 -08003716 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003717 bool geometryAppliesWithResize =
3718 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003719
3720 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3721 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003722 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003723 layer->pushPendingState();
3724 }
3725
chaviw8b3871a2017-11-01 17:41:01 -07003726 if (what & layer_state_t::ePositionChanged) {
3727 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3728 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003729 }
chaviw8b3871a2017-11-01 17:41:01 -07003730 }
3731 if (what & layer_state_t::eLayerChanged) {
3732 // NOTE: index needs to be calculated before we update the state
3733 const auto& p = layer->getParent();
3734 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003735 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003736 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003737 mCurrentState.layersSortedByZ.removeAt(idx);
3738 mCurrentState.layersSortedByZ.add(layer);
3739 // we need traversal (state changed)
3740 // AND transaction (list changed)
3741 flags |= eTransactionNeeded|eTraversalNeeded;
3742 }
chaviw8b3871a2017-11-01 17:41:01 -07003743 } else {
3744 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003745 flags |= eTransactionNeeded|eTraversalNeeded;
3746 }
3747 }
chaviw8b3871a2017-11-01 17:41:01 -07003748 }
3749 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003750 // NOTE: index needs to be calculated before we update the state
3751 const auto& p = layer->getParent();
3752 if (p == nullptr) {
3753 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3754 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3755 mCurrentState.layersSortedByZ.removeAt(idx);
3756 mCurrentState.layersSortedByZ.add(layer);
3757 // we need traversal (state changed)
3758 // AND transaction (list changed)
3759 flags |= eTransactionNeeded|eTraversalNeeded;
3760 }
3761 } else {
3762 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3763 flags |= eTransactionNeeded|eTraversalNeeded;
3764 }
chaviw8b3871a2017-11-01 17:41:01 -07003765 }
3766 }
3767 if (what & layer_state_t::eSizeChanged) {
3768 if (layer->setSize(s.w, s.h)) {
3769 flags |= eTraversalNeeded;
3770 }
3771 }
3772 if (what & layer_state_t::eAlphaChanged) {
3773 if (layer->setAlpha(s.alpha))
3774 flags |= eTraversalNeeded;
3775 }
3776 if (what & layer_state_t::eColorChanged) {
3777 if (layer->setColor(s.color))
3778 flags |= eTraversalNeeded;
3779 }
Peiyong Lind3788632018-09-18 16:01:31 -07003780 if (what & layer_state_t::eColorTransformChanged) {
3781 if (layer->setColorTransform(s.colorTransform)) {
3782 flags |= eTraversalNeeded;
3783 }
3784 }
chaviw8b3871a2017-11-01 17:41:01 -07003785 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003786 // TODO: b/109894387
3787 //
3788 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3789 // rotation. To see the problem observe that if we have a square parent, and a child
3790 // of the same size, then we rotate the child 45 degrees around it's center, the child
3791 // must now be cropped to a non rectangular 8 sided region.
3792 //
3793 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3794 // private API, and the WindowManager only uses rotation in one case, which is on a top
3795 // level layer in which cropping is not an issue.
3796 //
3797 // However given that abuse of rotation matrices could lead to surfaces extending outside
3798 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3799 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3800 // transformations.
3801 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003802 flags |= eTraversalNeeded;
3803 }
3804 if (what & layer_state_t::eTransparentRegionChanged) {
3805 if (layer->setTransparentRegionHint(s.transparentRegion))
3806 flags |= eTraversalNeeded;
3807 }
3808 if (what & layer_state_t::eFlagsChanged) {
3809 if (layer->setFlags(s.flags, s.mask))
3810 flags |= eTraversalNeeded;
3811 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003812 if (what & layer_state_t::eCropChanged_legacy) {
3813 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003814 flags |= eTraversalNeeded;
3815 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003816 if (what & layer_state_t::eCornerRadiusChanged) {
3817 if (layer->setCornerRadius(s.cornerRadius))
3818 flags |= eTraversalNeeded;
3819 }
chaviw8b3871a2017-11-01 17:41:01 -07003820 if (what & layer_state_t::eLayerStackChanged) {
3821 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3822 // We only allow setting layer stacks for top level layers,
3823 // everything else inherits layer stack from its parent.
3824 if (layer->hasParent()) {
3825 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3826 layer->getName().string());
3827 } else if (idx < 0) {
3828 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3829 "that also does not appear in the top level layer list. Something"
3830 " has gone wrong.", layer->getName().string());
3831 } else if (layer->setLayerStack(s.layerStack)) {
3832 mCurrentState.layersSortedByZ.removeAt(idx);
3833 mCurrentState.layersSortedByZ.add(layer);
3834 // we need traversal (state changed)
3835 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003836 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003837 }
3838 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003839 if (what & layer_state_t::eDeferTransaction_legacy) {
3840 if (s.barrierHandle_legacy != nullptr) {
3841 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3842 } else if (s.barrierGbp_legacy != nullptr) {
3843 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003844 if (authenticateSurfaceTextureLocked(gbp)) {
3845 const auto& otherLayer =
3846 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003847 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003848 } else {
3849 ALOGE("Attempt to defer transaction to to an"
3850 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003851 }
3852 }
chaviw8b3871a2017-11-01 17:41:01 -07003853 // We don't trigger a traversal here because if no other state is
3854 // changed, we don't want this to cause any more work
3855 }
3856 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003857 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003858 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003859 if (!hadParent) {
3860 mCurrentState.layersSortedByZ.remove(layer);
3861 }
chaviw8b3871a2017-11-01 17:41:01 -07003862 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003863 }
chaviw8b3871a2017-11-01 17:41:01 -07003864 }
3865 if (what & layer_state_t::eReparentChildren) {
3866 if (layer->reparentChildren(s.reparentHandle)) {
3867 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003868 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003869 }
chaviw8b3871a2017-11-01 17:41:01 -07003870 if (what & layer_state_t::eDetachChildren) {
3871 layer->detachChildren();
3872 }
3873 if (what & layer_state_t::eOverrideScalingModeChanged) {
3874 layer->setOverrideScalingMode(s.overrideScalingMode);
3875 // We don't trigger a traversal here because if no other state is
3876 // changed, we don't want this to cause any more work
3877 }
Marissa Wall61c58622018-07-18 10:12:20 -07003878 if (what & layer_state_t::eTransformChanged) {
3879 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3880 }
3881 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3882 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3883 flags |= eTraversalNeeded;
3884 }
3885 if (what & layer_state_t::eCropChanged) {
3886 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3887 }
Marissa Wall861616d2018-10-22 12:52:23 -07003888 if (what & layer_state_t::eFrameChanged) {
3889 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3890 }
Marissa Wall61c58622018-07-18 10:12:20 -07003891 if (what & layer_state_t::eBufferChanged) {
3892 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3893 }
3894 if (what & layer_state_t::eAcquireFenceChanged) {
3895 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3896 }
3897 if (what & layer_state_t::eDataspaceChanged) {
3898 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3899 }
3900 if (what & layer_state_t::eHdrMetadataChanged) {
3901 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3902 }
3903 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3904 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3905 }
3906 if (what & layer_state_t::eApiChanged) {
3907 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3908 }
3909 if (what & layer_state_t::eSidebandStreamChanged) {
3910 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3911 }
Robert Carr720e5062018-07-30 17:45:14 -07003912 if (what & layer_state_t::eInputInfoChanged) {
3913 layer->setInputInfo(s.inputInfo);
3914 flags |= eTraversalNeeded;
3915 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003916 std::vector<sp<CallbackHandle>> callbackHandles;
3917 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3918 mTransactionCompletedThread.run();
3919 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3920 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3921 }
3922 }
3923 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3924 // Do not put anything that updates layer state or modifies flags after
3925 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003926 return flags;
3927}
3928
chaviw273171b2018-12-26 11:46:30 -08003929uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3930 uint32_t flags = 0;
3931 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3932 flags |= eTraversalNeeded;
3933 }
3934
3935 mInputWindowCommands.merge(inputWindowCommands);
3936 return flags;
3937}
3938
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003939status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003940 const String8& name,
3941 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003942 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003943 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003944 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003946 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003947 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003948 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003949 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003950 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003951
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003952 status_t result = NO_ERROR;
3953
3954 sp<Layer> layer;
3955
Cody Northropbc755282017-03-31 12:00:08 -06003956 String8 uniqueName = getUniqueLayerName(name);
3957
Mathias Agopian3165cc22012-08-08 19:42:09 -07003958 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003959 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003960 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3961 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003962
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003964 case ISurfaceComposerClient::eFXSurfaceBufferState:
3965 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3966 break;
chaviw13fdc492017-06-27 12:40:18 -07003967 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003968 // check if buffer size is set for color layer.
3969 if (w > 0 || h > 0) {
3970 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3971 int(w), int(h));
3972 return BAD_VALUE;
3973 }
3974
chaviw13fdc492017-06-27 12:40:18 -07003975 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003976 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003977 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003978 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003979 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003980 // check if buffer size is set for container layer.
3981 if (w > 0 || h > 0) {
3982 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3983 int(w), int(h));
3984 return BAD_VALUE;
3985 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003986 result = createContainerLayer(client,
3987 uniqueName, w, h, flags,
3988 handle, &layer);
3989 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990 default:
3991 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 break;
3993 }
3994
Dan Stoza7d89d062015-04-30 13:29:25 -07003995 if (result != NO_ERROR) {
3996 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003998
Chia-I Wuab0c3192017-08-01 11:29:00 -07003999 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4000 // TODO b/64227542
4001 if (windowType == 441731) {
4002 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4003 layer->setPrimaryDisplayOnly();
4004 }
4005
Albert Chaulk479c60c2017-01-27 14:21:34 -05004006 layer->setInfo(windowType, ownerUid);
4007
Robert Carrb89ea9d2018-12-10 13:01:14 -08004008 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4009 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4010 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004011 if (result != NO_ERROR) {
4012 return result;
4013 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004014 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004015
4016 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018}
4019
Cody Northropbc755282017-03-31 12:00:08 -06004020String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4021{
4022 bool matchFound = true;
4023 uint32_t dupeCounter = 0;
4024
4025 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4026 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4027
Dan Stoza436ccf32018-06-21 12:10:12 -07004028 // Grab the state lock since we're accessing mCurrentState
4029 Mutex::Autolock lock(mStateLock);
4030
Cody Northropbc755282017-03-31 12:00:08 -06004031 // Loop over layers until we're sure there is no matching name
4032 while (matchFound) {
4033 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004034 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004035 if (layer->getName() == uniqueName) {
4036 matchFound = true;
4037 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4038 }
4039 });
4040 }
4041
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004042 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4043 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004044
4045 return uniqueName;
4046}
4047
Marissa Wallfd668622018-05-10 10:21:13 -07004048status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4049 uint32_t w, uint32_t h, uint32_t flags,
4050 PixelFormat& format, sp<IBinder>* handle,
4051 sp<IGraphicBufferProducer>* gbp,
4052 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004054 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 case PIXEL_FORMAT_TRANSPARENT:
4056 case PIXEL_FORMAT_TRANSLUCENT:
4057 format = PIXEL_FORMAT_RGBA_8888;
4058 break;
4059 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004060 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 break;
4062 }
4063
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004064 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004065 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004066 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004067 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004068 *handle = layer->getHandle();
4069 *gbp = layer->getProducer();
4070 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072
Marissa Wallfd668622018-05-10 10:21:13 -07004073 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075}
4076
Marissa Wall61c58622018-07-18 10:12:20 -07004077status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4078 uint32_t w, uint32_t h, uint32_t flags,
4079 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004080 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004081 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004082 *handle = layer->getHandle();
4083 *outLayer = layer;
4084
4085 return NO_ERROR;
4086}
4087
chaviw13fdc492017-06-27 12:40:18 -07004088status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004090 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004092 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004093 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004094 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004095}
4096
Robert Carr6b3f6c52018-08-13 13:05:17 -07004097status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4098 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4099 sp<IBinder>* handle, sp<Layer>* outLayer)
4100{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004101 *outLayer =
4102 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004103 *handle = (*outLayer)->getHandle();
4104 return NO_ERROR;
4105}
4106
4107
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004108void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004109 mLayersPendingRemoval.add(layer);
4110 mLayersRemoved = true;
4111 setTransactionFlags(eTransactionNeeded);
4112}
4113
Robert Carr695d5282018-12-18 15:27:58 -08004114void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004115{
Robert Carr2e102c92018-10-23 12:11:15 -07004116 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004117 // If a layer has a parent, we allow it to out-live it's handle
4118 // with the idea that the parent holds a reference and will eventually
4119 // be cleaned up. However no one cleans up the top-level so we do so
4120 // here.
4121 if (layer->getParent() == nullptr) {
4122 mCurrentState.layersSortedByZ.remove(layer);
4123 }
4124 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004125 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004126}
4127
Mathias Agopianb60314a2012-04-10 22:09:54 -07004128// ---------------------------------------------------------------------------
4129
Andy McFadden13a082e2012-08-24 10:16:42 -07004130void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004131 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004132 if (!displayToken) return;
4133
Jesse Hall01e29052013-02-19 16:13:35 -08004134 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004135 Vector<ComposerState> state;
4136 Vector<DisplayState> displays;
4137 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004138 d.what = DisplayState::eDisplayProjectionChanged |
4139 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004140 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004141 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004142 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004143 d.frame.makeInvalid();
4144 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004145 d.width = 0;
4146 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004147 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004148 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004149
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004150 const auto display = getDisplayDevice(displayToken);
4151 if (!display) return;
4152
Dominik Laskowskie9774092018-12-11 10:04:24 -08004153 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004154
Dominik Laskowski075d3172018-05-24 15:50:06 -07004155 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004156 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004157 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004158
Brian Andersond0010582017-03-07 13:20:31 -08004159 // Use phase of 0 since phase is not known.
4160 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004161 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4162 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004163}
4164
4165void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004166 // Async since we may be called from the main thread.
4167 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004168}
4169
Dominik Laskowskie9774092018-12-11 10:04:24 -08004170void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004171 if (display->isVirtual()) {
4172 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004173 return;
4174 }
4175
Dominik Laskowski075d3172018-05-24 15:50:06 -07004176 const auto displayId = display->getId();
4177 LOG_ALWAYS_FATAL_IF(!displayId);
4178
Dominik Laskowski34157762018-10-31 13:07:19 -07004179 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004180
4181 int currentMode = display->getPowerMode();
4182 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004183 return;
4184 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004186 display->setPowerMode(mode);
4187
Lloyd Pique4dccc412018-01-22 17:21:36 -08004188 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004189 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004190 }
4191
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004192 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004193 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004194 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004195 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004196 if (mUseScheduler) {
4197 mScheduler->onScreenAcquired(mAppConnectionHandle);
4198 } else {
4199 mEventThread->onScreenAcquired();
4200 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004201 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004202 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004204 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004205 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004206 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004207
4208 struct sched_param param = {0};
4209 param.sched_priority = 1;
4210 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4211 ALOGW("Couldn't set SCHED_FIFO on display on");
4212 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004213 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004214 // Turn off the display
4215 struct sched_param param = {0};
4216 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4217 ALOGW("Couldn't set SCHED_OTHER on display off");
4218 }
4219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004221 if (mUseScheduler) {
4222 mScheduler->disableHardwareVsync(true);
4223 } else {
4224 disableHardwareVsync(true); // also cancels any in-progress resync
4225 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004226 if (mUseScheduler) {
4227 mScheduler->onScreenReleased(mAppConnectionHandle);
4228 } else {
4229 mEventThread->onScreenReleased();
4230 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004231 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004232
Dominik Laskowski075d3172018-05-24 15:50:06 -07004233 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004234 mVisibleRegionsDirty = true;
4235 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004236 } else if (mode == HWC_POWER_MODE_DOZE ||
4237 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004238 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004239 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004240 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004241 if (mUseScheduler) {
4242 mScheduler->onScreenAcquired(mAppConnectionHandle);
4243 } else {
4244 mEventThread->onScreenAcquired();
4245 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004246 resyncToHardwareVsync(true);
4247 }
4248 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4249 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004250 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004251 if (mUseScheduler) {
4252 mScheduler->disableHardwareVsync(true);
4253 } else {
4254 disableHardwareVsync(true); // also cancels any in-progress resync
4255 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004256 if (mUseScheduler) {
4257 mScheduler->onScreenReleased(mAppConnectionHandle);
4258 } else {
4259 mEventThread->onScreenReleased();
4260 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004261 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004262 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004263 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004264 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004266 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004267
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004268 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004269 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004270 }
4271
Dominik Laskowski34157762018-10-31 13:07:19 -07004272 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004273}
4274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004276 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 const auto display = getDisplayDevice(displayToken);
4278 if (!display) {
4279 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4280 displayToken.get());
4281 } else if (display->isVirtual()) {
4282 ALOGW("Attempt to set power mode %d for virtual display", mode);
4283 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004285 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004286 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004287}
4288
4289// ---------------------------------------------------------------------------
4290
Lloyd Pique755e3192018-01-31 16:46:15 -08004291status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4292 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004293 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004294
Mathias Agopianbd115332013-04-18 16:41:04 -07004295 IPCThreadState* ipc = IPCThreadState::self();
4296 const int pid = ipc->getCallingPid();
4297 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004298
Mathias Agopianbd115332013-04-18 16:41:04 -07004299 if ((uid != AID_SHELL) &&
4300 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004301 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4302 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004304 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004305 // (this would indicate SF is stuck, but we want to be able to
4306 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004307 status_t err = mStateLock.timedLock(s2ns(1));
4308 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004309 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004310 StringAppendF(&result,
4311 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4312 "(no locks held)\n",
4313 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004314 }
4315
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316 bool dumpAll = true;
4317 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004318 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004319
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004320 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004321 if ((index < numArgs) &&
4322 (args[index] == String16("--list"))) {
4323 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004324 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004325 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004326 }
4327
4328 if ((index < numArgs) &&
4329 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004332 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004334
4335 if ((index < numArgs) &&
4336 (args[index] == String16("--latency-clear"))) {
4337 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004338 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004339 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004340 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004341
4342 if ((index < numArgs) &&
4343 (args[index] == String16("--dispsync"))) {
4344 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004345 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004346 dumpAll = false;
4347 }
Dan Stozab90cf072015-03-05 11:05:59 -08004348
4349 if ((index < numArgs) &&
4350 (args[index] == String16("--static-screen"))) {
4351 index++;
4352 dumpStaticScreenStats(result);
4353 dumpAll = false;
4354 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004355
4356 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004357 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004358 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004359 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004360 dumpAll = false;
4361 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004362
4363 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4364 index++;
4365 dumpWideColorInfo(result);
4366 dumpAll = false;
4367 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004368
4369 if ((index < numArgs) &&
4370 (args[index] == String16("--enable-layer-stats"))) {
4371 index++;
4372 mLayerStats.enable();
4373 dumpAll = false;
4374 }
4375
4376 if ((index < numArgs) &&
4377 (args[index] == String16("--disable-layer-stats"))) {
4378 index++;
4379 mLayerStats.disable();
4380 dumpAll = false;
4381 }
4382
4383 if ((index < numArgs) &&
4384 (args[index] == String16("--clear-layer-stats"))) {
4385 index++;
4386 mLayerStats.clear();
4387 dumpAll = false;
4388 }
4389
4390 if ((index < numArgs) &&
4391 (args[index] == String16("--dump-layer-stats"))) {
4392 index++;
4393 mLayerStats.dump(result);
4394 dumpAll = false;
4395 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004396
4397 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004398 (args[index] == String16("--frame-composition"))) {
4399 index++;
4400 dumpFrameCompositionInfo(result);
4401 dumpAll = false;
4402 }
4403
4404 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004405 (args[index] == String16("--display-identification"))) {
4406 index++;
4407 dumpDisplayIdentificationData(result);
4408 dumpAll = false;
4409 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004410
4411 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4412 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004413 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004414 dumpAll = false;
4415 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004417
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004419 if (asProto) {
4420 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4421 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4422 } else {
4423 dumpAllLocked(args, index, result);
4424 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004425 }
4426
Mathias Agopian9795c422009-08-26 16:36:26 -07004427 if (locked) {
4428 mStateLock.unlock();
4429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 return NO_ERROR;
4433}
4434
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4436 std::string& result) const {
4437 mCurrentState.traverseInZOrder(
4438 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004439}
4440
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443 String8 name;
4444 if (index < args.size()) {
4445 name = String8(args[index]);
4446 index++;
4447 }
4448
Dominik Laskowski075d3172018-05-24 15:50:06 -07004449 if (const auto displayId = getInternalDisplayId();
4450 displayId && getHwComposer().isConnected(*displayId)) {
4451 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004452 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004455
4456 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004457 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004458 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004459 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004460 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004461 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004462 }
Robert Carr2047fae2016-11-28 14:09:09 -08004463 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004464 }
4465}
4466
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004467void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004469 String8 name;
4470 if (index < args.size()) {
4471 name = String8(args[index]);
4472 index++;
4473 }
4474
Robert Carr2047fae2016-11-28 14:09:09 -08004475 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004476 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004477 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478 }
Robert Carr2047fae2016-11-28 14:09:09 -08004479 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004480
Svetoslavd85084b2014-03-20 10:28:31 -07004481 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004482}
4483
Jamie Gennis6547ff42013-07-16 20:12:42 -07004484// This should only be called from the main thread. Otherwise it would need
4485// the lock and should use mCurrentState rather than mDrawingState.
4486void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004487 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004488 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004489 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490
4491 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004495 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004496
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 if (isLayerTripleBufferingDisabled())
4498 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4501 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4502 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4503 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4504 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4505 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004506 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004507}
4508
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4510 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004511 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4512 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004513 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004514 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004516 }
David Sodman4a36e932017-11-07 14:29:47 -08004517 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004518 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004519 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4521 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004522}
4523
Dan Stozae77c7662016-05-13 11:37:28 -07004524void SurfaceFlinger::recordBufferingStats(const char* layerName,
4525 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004526 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4527 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004528 for (const auto& segment : history) {
4529 if (!segment.usedThirdBuffer) {
4530 stats.twoBufferTime += segment.totalTime;
4531 }
4532 if (segment.occupancyAverage < 1.0f) {
4533 stats.doubleBufferedTime += segment.totalTime;
4534 } else if (segment.occupancyAverage < 2.0f) {
4535 stats.tripleBufferedTime += segment.totalTime;
4536 }
4537 ++stats.numSegments;
4538 stats.totalTime += segment.totalTime;
4539 }
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4543 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004544
4545 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4546 const size_t count = currentLayers.size();
4547 for (size_t i=0 ; i<count ; i++) {
4548 currentLayers[i]->dumpFrameEvents(result);
4549 }
4550}
4551
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004553 result.append("Buffering stats:\n");
4554 result.append(" [Layer name] <Active time> <Two buffer> "
4555 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004556 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004557 typedef std::tuple<std::string, float, float, float> BufferTuple;
4558 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004559 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004560 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004561 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004562 if (stats.numSegments == 0) {
4563 continue;
4564 }
4565 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4566 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4567 stats.totalTime;
4568 float doubleBufferRatio = static_cast<float>(
4569 stats.doubleBufferedTime) / stats.totalTime;
4570 float tripleBufferRatio = static_cast<float>(
4571 stats.tripleBufferedTime) / stats.totalTime;
4572 sorted.insert({activeTime, {name, twoBufferRatio,
4573 doubleBufferRatio, tripleBufferRatio}});
4574 }
4575 for (const auto& sortedPair : sorted) {
4576 float activeTime = sortedPair.first;
4577 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4579 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004580 }
4581 result.append("\n");
4582}
4583
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004585 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004586 const auto displayId = display->getId();
4587 if (!displayId) {
4588 continue;
4589 }
4590 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004591 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004592 continue;
4593 }
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result,
4596 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4597 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004598 uint8_t port;
4599 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004600 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 result.append("no identification data\n");
4602 continue;
4603 }
4604
4605 if (!isEdid(data)) {
4606 result.append("unknown identification data: ");
4607 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 }
4610 result.append("\n");
4611 continue;
4612 }
4613
4614 const auto edid = parseEdid(data);
4615 if (!edid) {
4616 result.append("invalid EDID: ");
4617 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619 }
4620 result.append("\n");
4621 continue;
4622 }
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004625 result.append(edid->displayName.data(), edid->displayName.length());
4626 result.append("\"\n");
4627 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004628}
4629
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4631 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4632 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4633 StringAppendF(&result, "DisplayColorSetting: %s\n",
4634 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004635
4636 // TODO: print out if wide-color mode is active or not
4637
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004638 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004639 const auto displayId = display->getId();
4640 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004645 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004646 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004648 }
4649
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004650 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, " Current color mode: %s (%d)\n",
4652 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004653 }
4654 result.append("\n");
4655}
4656
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004658 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004659 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4660 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004661 continue;
4662 }
4663
Dominik Laskowski05275f12018-11-01 15:03:24 -07004664 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4666 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004667 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 compositionInfo.dump(result, nullptr);
4669 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004670 }
4671 }
David Sodman7e4ae112018-02-09 15:02:28 -08004672}
4673
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004674LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004675 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004676 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4677 const State& state = useDrawing ? mDrawingState : mCurrentState;
4678 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004679 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004680 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004681 });
4682
4683 return layersProto;
4684}
4685
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004686LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004687 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004688
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004690 resolution->set_w(display.getWidth());
4691 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004692
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004693 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4694 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4695 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004696
Dominik Laskowski075d3172018-05-24 15:50:06 -07004697 const auto displayId = display.getId();
4698 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004699 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004700 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004701 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004702 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004703 }
4704 });
4705
4706 return layersProto;
4707}
4708
Mathias Agopian74d211a2013-04-22 16:55:35 +02004709void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711 bool colorize = false;
4712 if (index < args.size()
4713 && (args[index] == String16("--color"))) {
4714 colorize = true;
4715 index++;
4716 }
4717
4718 Colorizer colorizer(colorize);
4719
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720 // figure out if we're stuck somewhere
4721 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004723 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4724
4725 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004726 * Dump library configuration.
4727 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004728
4729 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004730 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004731 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004732 appendSfConfigString(result);
4733 appendUiConfigString(result);
4734 appendGuiConfigString(result);
4735 result.append("\n");
4736
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004737 result.append("\nDisplay identification data:\n");
4738 dumpDisplayIdentificationData(result);
4739
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004740 result.append("\nWide-Color information:\n");
4741 dumpWideColorInfo(result);
4742
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004743 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004744 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004746 result.append(SyncFeatures::getInstance().toString());
4747 result.append("\n");
4748
Andy McFadden41d67d72014-04-25 16:58:34 -07004749 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004750 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004751 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004752
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004753 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4754 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004755 if (const auto displayId = getInternalDisplayId();
4756 displayId && getHwComposer().isConnected(*displayId)) {
4757 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result,
4759 "Display %s: app phase %" PRId64 " ns, "
4760 "sf phase %" PRId64 " ns, "
4761 "early app phase %" PRId64 " ns, "
4762 "early sf phase %" PRId64 " ns, "
4763 "early app gl phase %" PRId64 " ns, "
4764 "early sf gl phase %" PRId64 " ns, "
4765 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4766 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4767 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4768 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004769 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004770 result.append("\n");
4771
Dan Stozab90cf072015-03-05 11:05:59 -08004772 // Dump static screen stats
4773 result.append("\n");
4774 dumpStaticScreenStats(result);
4775 result.append("\n");
4776
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004778
Dan Stozae77c7662016-05-13 11:37:28 -07004779 dumpBufferingStats(result);
4780
Andy McFadden4803b742012-09-24 19:07:20 -07004781 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004782 * Dump the visible layer list
4783 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004784 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4786 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4787 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004788 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004789
Chia-I Wu2f884132018-09-13 15:17:58 -07004790 {
4791 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4792 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004794 result.append("\n");
4795 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004796
David Sodman7e4ae112018-02-09 15:02:28 -08004797 result.append("\nFrame-Composition information:\n");
4798 dumpFrameCompositionInfo(result);
4799 result.append("\n");
4800
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004801 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004802 * Dump Display state
4803 */
4804
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004805 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004807 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004808 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004809 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004810 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004811 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004812
4813 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814 * Dump SurfaceFlinger global state
4815 */
4816
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004817 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004818 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004819 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004820
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004821 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822
Dominik Laskowski075d3172018-05-24 15:50:06 -07004823 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4826 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004827 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 StringAppendF(&result,
4829 " transaction-flags : %08x\n"
4830 " gpu_to_cpu_unsupported : %d\n",
4831 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004832
Dominik Laskowski075d3172018-05-24 15:50:06 -07004833 if (const auto displayId = getInternalDisplayId();
4834 displayId && getHwComposer().isConnected(*displayId)) {
4835 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result,
4837 " refresh-rate : %f fps\n"
4838 " x-dpi : %f\n"
4839 " y-dpi : %f\n",
4840 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4841 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004842 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004843
Yiwei Zhang5434a782018-12-05 18:06:32 -08004844 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004845
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847 /*
4848 * VSYNC state
4849 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004850 if (mUseScheduler) {
4851 mScheduler->dump(mAppConnectionHandle, result);
4852 } else {
4853 mEventThread->dump(result);
4854 }
Dan Stozae22aec72016-08-01 13:20:59 -07004855 result.append("\n");
4856
4857 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004858 * Tracing state
4859 */
4860 mTracing.dump(result);
4861 result.append("\n");
4862
4863 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004864 * HWC layer minidump
4865 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004866 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004867 const auto displayId = display->getId();
4868 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004869 continue;
4870 }
4871
Yiwei Zhang5434a782018-12-05 18:06:32 -08004872 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004873 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004875 result.append("\n");
4876 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004877
4878 /*
4879 * Dump HWComposer state
4880 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004881 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004882 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004883 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004884 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004885 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004887
4888 /*
4889 * Dump gralloc state
4890 */
4891 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4892 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004893
4894 /*
4895 * Dump VrFlinger state if in use.
4896 */
4897 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4898 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004899 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004900 result.append("\n");
4901 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004902}
4903
Dominik Laskowski075d3172018-05-24 15:50:06 -07004904const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004905 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004906 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004907 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004908 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004909 }
4910 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004911
Dominik Laskowski34157762018-10-31 13:07:19 -07004912 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004913 static const Vector<sp<Layer>> empty;
4914 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004915}
4916
Keun young Park63f165f2012-08-31 10:53:36 -07004917bool SurfaceFlinger::startDdmConnection()
4918{
4919 void* libddmconnection_dso =
4920 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4921 if (!libddmconnection_dso) {
4922 return false;
4923 }
4924 void (*DdmConnection_start)(const char* name);
4925 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004926 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004927 if (!DdmConnection_start) {
4928 dlclose(libddmconnection_dso);
4929 return false;
4930 }
4931 (*DdmConnection_start)(getServiceName());
4932 return true;
4933}
4934
Chia-I Wu28f320b2018-05-03 11:02:56 -07004935void SurfaceFlinger::updateColorMatrixLocked() {
4936 mat4 colorMatrix;
4937 if (mGlobalSaturationFactor != 1.0f) {
4938 // Rec.709 luma coefficients
4939 float3 luminance{0.213f, 0.715f, 0.072f};
4940 luminance *= 1.0f - mGlobalSaturationFactor;
4941 mat4 saturationMatrix = mat4(
4942 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4943 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4944 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4945 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4946 );
4947 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4948 } else {
4949 colorMatrix = mClientColorMatrix * mDaltonizer();
4950 }
4951
4952 if (mCurrentState.colorMatrix != colorMatrix) {
4953 mCurrentState.colorMatrix = colorMatrix;
4954 mCurrentState.colorMatrixChanged = true;
4955 setTransactionFlags(eTransactionNeeded);
4956 }
4957}
4958
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004959status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960#pragma clang diagnostic push
4961#pragma clang diagnostic error "-Wswitch-enum"
4962 switch (static_cast<ISurfaceComposerTag>(code)) {
4963 // These methods should at minimum make sure that the client requested
4964 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004965 case BOOT_FINISHED:
4966 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 case CREATE_DISPLAY:
4968 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004969 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970 case GET_ACTIVE_COLOR_MODE:
4971 case GET_ANIMATION_FRAME_STATS:
4972 case GET_HDR_CAPABILITIES:
4973 case SET_ACTIVE_CONFIG:
4974 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004975 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004976 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004977 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004978 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4979 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004980 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4981 IPCThreadState* ipc = IPCThreadState::self();
4982 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4983 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004984 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 }
Robert Carr1db73f62016-12-21 12:58:51 -08004986 return OK;
4987 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004989 IPCThreadState* ipc = IPCThreadState::self();
4990 const int pid = ipc->getCallingPid();
4991 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4993 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004994 return PERMISSION_DENIED;
4995 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004996 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 // Used by apps to hook Choreographer to SurfaceFlinger.
4999 case CREATE_DISPLAY_EVENT_CONNECTION:
5000 // The following calls are currently used by clients that do not
5001 // request necessary permissions. However, they do not expose any secret
5002 // information, so it is OK to pass them.
5003 case AUTHENTICATE_SURFACE:
5004 case GET_ACTIVE_CONFIG:
5005 case GET_BUILT_IN_DISPLAY:
5006 case GET_DISPLAY_COLOR_MODES:
5007 case GET_DISPLAY_CONFIGS:
5008 case GET_DISPLAY_STATS:
5009 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5010 // Calling setTransactionState is safe, because you need to have been
5011 // granted a reference to Client* and Handle* to do anything with it.
5012 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005013 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005014 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005015 case GET_COMPOSITION_PREFERENCE:
5016 case GET_PROTECTED_CONTENT_SUPPORT: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017 return OK;
5018 }
5019 case CAPTURE_LAYERS:
5020 case CAPTURE_SCREEN: {
5021 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005022 IPCThreadState* ipc = IPCThreadState::self();
5023 const int pid = ipc->getCallingPid();
5024 const int uid = ipc->getCallingUid();
5025 if ((uid != AID_GRAPHICS) &&
5026 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5027 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5028 return PERMISSION_DENIED;
5029 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030 return OK;
5031 }
5032 // The following codes are deprecated and should never be allowed to access SF.
5033 case CONNECT_DISPLAY_UNUSED:
5034 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5035 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5036 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005039
5040 // These codes are used for the IBinder protocol to either interrogate the recipient
5041 // side of the transaction for its canonical interface descriptor or to dump its state.
5042 // We let them pass by default.
5043 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5044 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5045 code == IBinder::SYSPROPS_TRANSACTION) {
5046 return OK;
5047 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005048 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005049 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005050 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5052 return OK;
5053 }
5054 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5055 return PERMISSION_DENIED;
5056#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005057}
5058
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5060 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005061 status_t credentialCheck = CheckTransactCodeCredentials(code);
5062 if (credentialCheck != OK) {
5063 return credentialCheck;
5064 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005065
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005066 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5067 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005068 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005069 IPCThreadState* ipc = IPCThreadState::self();
5070 const int uid = ipc->getCallingUid();
5071 if (CC_UNLIKELY(uid != AID_SYSTEM
5072 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005073 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005074 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005075 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076 return PERMISSION_DENIED;
5077 }
5078 int n;
5079 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005080 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005081 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005082 return NO_ERROR;
5083 case 1002: // SHOW_UPDATES
5084 n = data.readInt32();
5085 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005086 invalidateHwcGeometry();
5087 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005088 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005089 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005090 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005091 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005092 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005093 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005094 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005095 setTransactionFlags(
5096 eTransactionNeeded|
5097 eDisplayTransactionNeeded|
5098 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005099 return NO_ERROR;
5100 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005101 case 1006:{ // send empty update
5102 signalRefresh();
5103 return NO_ERROR;
5104 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005105 case 1008: // toggle use of hw composer
5106 n = data.readInt32();
5107 mDebugDisableHWC = n ? 1 : 0;
5108 invalidateHwcGeometry();
5109 repaintEverything();
5110 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005111 case 1009: // toggle use of transform hint
5112 n = data.readInt32();
5113 mDebugDisableTransformHint = n ? 1 : 0;
5114 invalidateHwcGeometry();
5115 repaintEverything();
5116 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005118 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005119 reply->writeInt32(0);
5120 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005121 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005122 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005123 return NO_ERROR;
5124 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005125 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005126 if (!display) {
5127 return NAME_NOT_FOUND;
5128 }
5129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005130 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005131 return NO_ERROR;
5132 }
5133 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005134 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005135 // daltonize
5136 n = data.readInt32();
5137 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005138 case 1:
5139 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5140 break;
5141 case 2:
5142 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5143 break;
5144 case 3:
5145 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5146 break;
5147 default:
5148 mDaltonizer.setType(ColorBlindnessType::None);
5149 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005150 }
5151 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005152 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005153 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005154 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005155 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005156
5157 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005158 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005159 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005160 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005161 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005162 // apply a color matrix
5163 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005164 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005165 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005166 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005167 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005168 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005169 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005170 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005171 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005172 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005174
5175 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5176 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005177 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005178 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5179 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5180 }
5181
Chia-I Wu28f320b2018-05-03 11:02:56 -07005182 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005183 return NO_ERROR;
5184 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005185 // This is an experimental interface
5186 // Needs to be shifted to proper binder interface when we productize
5187 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005188 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005189 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005190 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005191 return NO_ERROR;
5192 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005193 case 1017: {
5194 n = data.readInt32();
5195 mForceFullDamage = static_cast<bool>(n);
5196 return NO_ERROR;
5197 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005198 case 1018: { // Modify Choreographer's phase offset
5199 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005200 if (mUseScheduler) {
5201 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5202 } else {
5203 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5204 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005205 return NO_ERROR;
5206 }
5207 case 1019: { // Modify SurfaceFlinger's phase offset
5208 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005209 if (mUseScheduler) {
5210 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5211 } else {
5212 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5213 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005214 return NO_ERROR;
5215 }
Irvel468051e2016-06-13 16:44:44 -07005216 case 1020: { // Layer updates interceptor
5217 n = data.readInt32();
5218 if (n) {
5219 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005220 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005221 }
5222 else{
5223 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005224 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005225 }
5226 return NO_ERROR;
5227 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005228 case 1021: { // Disable HWC virtual displays
5229 n = data.readInt32();
5230 mUseHwcVirtualDisplays = !n;
5231 return NO_ERROR;
5232 }
Romain Guy0147a172017-06-01 13:53:56 -07005233 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005234 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005235 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005236
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005238 return NO_ERROR;
5239 }
Romain Guy54f154a2017-10-24 21:40:32 +01005240 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005241 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005242 invalidateHwcGeometry();
5243 repaintEverything();
5244 return NO_ERROR;
5245 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005246 // Deprecate, use 1030 to check whether the device is color managed.
5247 case 1024: {
5248 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005249 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005250 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005251 n = data.readInt32();
5252 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005253 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005254 mTracing.enable();
5255 doTracing("tracing.enable");
5256 reply->writeInt32(NO_ERROR);
5257 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005258 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005259 status_t err = mTracing.disable();
5260 reply->writeInt32(err);
5261 }
5262 return NO_ERROR;
5263 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005264 case 1026: { // Get layer tracing status
5265 reply->writeBool(mTracing.isEnabled());
5266 return NO_ERROR;
5267 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005268 // Is a DisplayColorSetting supported?
5269 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005270 const auto display = getDefaultDisplayDevice();
5271 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005272 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005273 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005274
5275 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5276 switch (setting) {
5277 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005278 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005279 break;
5280 case DisplayColorSetting::UNMANAGED:
5281 reply->writeBool(true);
5282 break;
5283 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005284 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005285 break;
5286 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005287 reply->writeBool(
5288 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005289 break;
5290 }
5291 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005292 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005293 // Is VrFlinger active?
5294 case 1028: {
5295 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005296 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005297 return NO_ERROR;
5298 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005299 // Is device color managed?
5300 case 1030: {
5301 reply->writeBool(useColorManagement);
5302 return NO_ERROR;
5303 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005304 // Override default composition data space
5305 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5306 // && adb shell stop zygote && adb shell start zygote
5307 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5308 // adb shell stop zygote && adb shell start zygote
5309 case 1031: {
5310 Mutex::Autolock _l(mStateLock);
5311 n = data.readInt32();
5312 if (n) {
5313 n = data.readInt32();
5314 if (n) {
5315 Dataspace dataspace = static_cast<Dataspace>(n);
5316 if (!validateCompositionDataspace(dataspace)) {
5317 return BAD_VALUE;
5318 }
5319 mDefaultCompositionDataspace = dataspace;
5320 }
5321 n = data.readInt32();
5322 if (n) {
5323 Dataspace dataspace = static_cast<Dataspace>(n);
5324 if (!validateCompositionDataspace(dataspace)) {
5325 return BAD_VALUE;
5326 }
5327 mWideColorGamutCompositionDataspace = dataspace;
5328 }
5329 } else {
5330 // restore composition data space.
5331 mDefaultCompositionDataspace = defaultCompositionDataspace;
5332 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5333 }
5334 return NO_ERROR;
5335 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005336 }
5337 }
5338 return err;
5339}
5340
Steven Thomas6d8110b2017-08-31 18:24:21 -07005341void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005342 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005343 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005344}
5345
Ana Krulec7d1d6832018-12-27 11:10:09 -08005346void SurfaceFlinger::repaintEverythingForHWC() {
5347 mRepaintEverything = true;
5348 mEventQueue->invalidateForHWC();
5349}
5350
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005351// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5352class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005353public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005354 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5355 ~WindowDisconnector() {
5356 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005357 }
5358
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005359private:
5360 ANativeWindow* mWindow;
5361 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005362};
5363
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005364status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005365 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5366 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005367 uint32_t reqWidth, uint32_t reqHeight,
5368 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005369 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005370 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005371
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005372 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005373
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005374 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5375
Chia-I Wu20261cb2018-08-23 12:55:44 -07005376 sp<DisplayDevice> display;
5377 {
5378 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005379
Chia-I Wu20261cb2018-08-23 12:55:44 -07005380 display = getDisplayDeviceLocked(displayToken);
5381 if (!display) return BAD_VALUE;
5382
Chia-I Wucb023152018-08-28 12:57:23 -07005383 // set the requested width/height to the logical display viewport size
5384 // by default
5385 if (reqWidth == 0 || reqHeight == 0) {
5386 reqWidth = uint32_t(display->getViewport().width());
5387 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005388 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005389 }
5390
Peiyong Lin0e003c92018-09-17 11:09:51 -07005391 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5392 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005393
5394 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005395 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005396 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5397 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005398}
5399
5400status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005401 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5402 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005403 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005404 ATRACE_CALL();
5405
5406 class LayerRenderArea : public RenderArea {
5407 public:
Robert Carr578038f2018-03-09 12:25:24 -08005408 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005409 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5410 bool childrenOnly)
5411 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005412 mLayer(layer),
5413 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005414 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005415 mFlinger(flinger),
5416 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005417 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005418 Rect getBounds() const override {
5419 const Layer::State& layerState(mLayer->getDrawingState());
5420 return mLayer->getBufferSize(layerState);
5421 }
Marissa Wall61c58622018-07-18 10:12:20 -07005422 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005423 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005424 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005425 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005426 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005427 }
chaviwa76b2712017-09-20 12:02:26 -07005428 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005429 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005430 Rect getSourceCrop() const override {
5431 if (mCrop.isEmpty()) {
5432 return getBounds();
5433 } else {
5434 return mCrop;
5435 }
5436 }
Robert Carr578038f2018-03-09 12:25:24 -08005437 class ReparentForDrawing {
5438 public:
5439 const sp<Layer>& oldParent;
5440 const sp<Layer>& newParent;
5441
5442 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5443 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005444 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005445 }
Robert Carr15eae092018-03-23 13:43:53 -07005446 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005447 };
5448
5449 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005450 const Rect sourceCrop = getSourceCrop();
5451 // no need to check rotation because there is none
5452 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5453 sourceCrop.height() != getReqHeight();
5454
Robert Carr578038f2018-03-09 12:25:24 -08005455 if (!mChildrenOnly) {
5456 mTransform = mLayer->getTransform().inverse();
5457 drawLayers();
5458 } else {
5459 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005460 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005461 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5462 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005463
5464 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5465 drawLayers();
5466 }
5467 }
chaviwa76b2712017-09-20 12:02:26 -07005468
chaviwa76b2712017-09-20 12:02:26 -07005469 private:
chaviw7206d492017-11-10 16:16:12 -08005470 const sp<Layer> mLayer;
5471 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005472
5473 // In the "childrenOnly" case we reparent the children to a screenshot
5474 // layer which has no properties set and which does not draw.
5475 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005476 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005477 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005478
5479 SurfaceFlinger* mFlinger;
5480 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005481 };
5482
5483 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5484 auto parent = layerHandle->owner.promote();
5485
Robert Carr2e102c92018-10-23 12:11:15 -07005486 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005487 ALOGE("captureLayers called with a removed parent");
5488 return NAME_NOT_FOUND;
5489 }
5490
Robert Carr578038f2018-03-09 12:25:24 -08005491 const int uid = IPCThreadState::self()->getCallingUid();
5492 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005493 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005494 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5495 return PERMISSION_DENIED;
5496 }
5497
chaviw7206d492017-11-10 16:16:12 -08005498 Rect crop(sourceCrop);
5499 if (sourceCrop.width() <= 0) {
5500 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005501 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005502 }
5503
5504 if (sourceCrop.height() <= 0) {
5505 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005506 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005507 }
5508
5509 int32_t reqWidth = crop.width() * frameScale;
5510 int32_t reqHeight = crop.height() * frameScale;
5511
Chia-I Wu20261cb2018-08-23 12:55:44 -07005512 // really small crop or frameScale
5513 if (reqWidth <= 0) {
5514 reqWidth = 1;
5515 }
5516 if (reqHeight <= 0) {
5517 reqHeight = 1;
5518 }
5519
Peiyong Lin0e003c92018-09-17 11:09:51 -07005520 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005521
Robert Carr578038f2018-03-09 12:25:24 -08005522 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005523 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5524 if (!layer->isVisible()) {
5525 return;
Robert Carr578038f2018-03-09 12:25:24 -08005526 } else if (childrenOnly && layer == parent.get()) {
5527 return;
chaviwa76b2712017-09-20 12:02:26 -07005528 }
5529 visitor(layer);
5530 });
5531 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005532 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005533}
5534
5535status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5536 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005537 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005538 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005539 bool useIdentityTransform) {
5540 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005541
Peiyong Lin0e003c92018-09-17 11:09:51 -07005542 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005543 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5544 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005545 *outBuffer =
5546 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5547 static_cast<android_pixel_format>(reqPixelFormat), 1,
5548 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005549
5550 // This mutex protects syncFd and captureResult for communication of the return values from the
5551 // main thread back to this Binder thread
5552 std::mutex captureMutex;
5553 std::condition_variable captureCondition;
5554 std::unique_lock<std::mutex> captureLock(captureMutex);
5555 int syncFd = -1;
5556 std::optional<status_t> captureResult;
5557
Robert Carr03480e22018-01-04 16:02:06 -08005558 const int uid = IPCThreadState::self()->getCallingUid();
5559 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5560
Dominik Laskowski8c001672018-05-30 16:52:06 -07005561 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562 // If there is a refresh pending, bug out early and tell the binder thread to try again
5563 // after the refresh.
5564 if (mRefreshPending) {
5565 ATRACE_NAME("Skipping screenshot for now");
5566 std::unique_lock<std::mutex> captureLock(captureMutex);
5567 captureResult = std::make_optional<status_t>(EAGAIN);
5568 captureCondition.notify_one();
5569 return;
5570 }
5571
5572 status_t result = NO_ERROR;
5573 int fd = -1;
5574 {
5575 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005576 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005577 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5578 useIdentityTransform, forSystem, &fd);
5579 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005580 }
5581
5582 {
5583 std::unique_lock<std::mutex> captureLock(captureMutex);
5584 syncFd = fd;
5585 captureResult = std::make_optional<status_t>(result);
5586 captureCondition.notify_one();
5587 }
5588 });
5589
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005590 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005591 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005592 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 while (*captureResult == EAGAIN) {
5594 captureResult.reset();
5595 result = postMessageAsync(message);
5596 if (result != NO_ERROR) {
5597 return result;
5598 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005599 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005600 }
5601 result = *captureResult;
5602 }
5603
5604 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005605 sync_wait(syncFd, -1);
5606 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005607 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005608
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005610}
5611
chaviwa76b2712017-09-20 12:02:26 -07005612void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005613 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005614 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005615 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005616
Lloyd Pique144e1162017-12-20 16:44:52 -08005617 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005618
chaviwa76b2712017-09-20 12:02:26 -07005619 const auto reqWidth = renderArea.getReqWidth();
5620 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005621 const auto sourceCrop = renderArea.getSourceCrop();
5622 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005623
Peiyong Lin0e003c92018-09-17 11:09:51 -07005624 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005625 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005626
Mathias Agopian180f10d2013-04-10 22:55:41 -07005627 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005628 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005629
5630 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005631 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005632 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005633
chaviw50da5042018-04-09 13:49:37 -07005634 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005635 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005636 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637
chaviwa76b2712017-09-20 12:02:26 -07005638 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005639 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005640 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005641 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005642 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005643}
5644
chaviwa76b2712017-09-20 12:02:26 -07005645status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5646 TraverseLayersFunction traverseLayers,
5647 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005648 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005649 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005650 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005651 ATRACE_CALL();
5652
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005653 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005654
5655 traverseLayers([&](Layer* layer) {
5656 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5657 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005658
Robert Carr03480e22018-01-04 16:02:06 -08005659 // We allow the system server to take screenshots of secure layers for
5660 // use in situations like the Screen-rotation animation and place
5661 // the impetus on WindowManager to not persist them.
5662 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005663 ALOGW("FB is protected: PERMISSION_DENIED");
5664 return PERMISSION_DENIED;
5665 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005666 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005667
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005668 // this binds the given EGLImage as a framebuffer for the
5669 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005670 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005671 if (bufferBond.getStatus() != NO_ERROR) {
5672 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005673 return INVALID_OPERATION;
5674 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005675
Dan Stozaabcda352017-06-01 14:37:39 -07005676 // this will in fact render into our dequeued buffer
5677 // via an FBO, which means we didn't have to create
5678 // an EGLSurface and therefore we're not
5679 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005680 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005681
Peiyong Linfb530cf2018-12-15 05:07:38 +00005682 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005683 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005684 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005685 }
Alec Mouri492bc572018-09-11 21:40:04 +00005686 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005687
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005688 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005689}
5690
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005691// ---------------------------------------------------------------------------
5692
Dan Stoza412903f2017-04-27 13:42:17 -07005693void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5694 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005695}
5696
Dan Stoza412903f2017-04-27 13:42:17 -07005697void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5698 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005699}
5700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005701void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005702 const LayerVector::Visitor& visitor) {
5703 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005704 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005705 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005706 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005707 continue;
5708 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005709 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005710 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005711 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005712 return;
5713 }
chaviwa76b2712017-09-20 12:02:26 -07005714 if (!layer->isVisible()) {
5715 return;
5716 }
5717 visitor(layer);
5718 });
5719 }
5720}
5721
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005722}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005723
Lloyd Pique074e8122018-07-26 12:57:23 -07005724
Mathias Agopian3f844832013-08-07 21:24:32 -07005725#if defined(__gl_h_)
5726#error "don't include gl/gl.h in this file"
5727#endif
5728
5729#if defined(__gl2_h_)
5730#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005731#endif