blob: 5cac524460b0430fe8730ac013828d975677f5fb [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
Dan Stoza9e56aa02015-11-02 13:00:03 -0800733 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700734}
735
Romain Guy11d63f42017-07-20 12:47:14 -0700736void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700737 Mutex::Autolock _l(mStateLock);
738
Romain Guy11d63f42017-07-20 12:47:14 -0700739 char value[PROPERTY_VALUE_MAX];
740
741 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700743 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800744 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100745
746 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700747 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700748}
749
Mathias Agopiana67e4182012-06-19 17:26:12 -0700750void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800751 // Start boot animation service by setting a property mailbox
752 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700753 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800754 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700755 if (mStartPropertySetThread->join() != NO_ERROR) {
756 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800757 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700758}
759
Mathias Agopian875d8e12013-06-07 15:35:48 -0700760size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700761 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700765 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800768// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800769
Jamie Gennis582270d2011-08-17 18:19:00 -0700770bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800771 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800772 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800773 return authenticateSurfaceTextureLocked(bufferProducer);
774}
775
776bool SurfaceFlinger::authenticateSurfaceTextureLocked(
777 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800778 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800779 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800780}
781
Brian Anderson6b376712017-04-04 10:51:39 -0700782status_t SurfaceFlinger::getSupportedFrameTimestamps(
783 std::vector<FrameEvent>* outSupported) const {
784 *outSupported = {
785 FrameEvent::REQUESTED_PRESENT,
786 FrameEvent::ACQUIRE,
787 FrameEvent::LATCH,
788 FrameEvent::FIRST_REFRESH_START,
789 FrameEvent::LAST_REFRESH_START,
790 FrameEvent::GPU_COMPOSITION_DONE,
791 FrameEvent::DEQUEUE_READY,
792 FrameEvent::RELEASE,
793 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700794 ConditionalLock _l(mStateLock,
795 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700796 if (!getHwComposer().hasCapability(
797 HWC2::Capability::PresentFenceIsNotReliable)) {
798 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
799 }
800 return NO_ERROR;
801}
802
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700803status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
804 Vector<DisplayInfo>* configs) {
805 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 return BAD_VALUE;
807 }
808
Dominik Laskowski075d3172018-05-24 15:50:06 -0700809 const auto displayId = getPhysicalDisplayId(displayToken);
810 if (!displayId) {
811 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700812 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 // TODO: Not sure if display density should handled by SF any longer
815 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700816 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700818 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800819 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 }
822 return density;
823 }
824 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700825 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700827 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 return getDensityFromProperty("ro.sf.lcd_density"); }
829 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Steven Thomas6d8110b2017-08-31 18:24:21 -0700833 ConditionalLock _l(mStateLock,
834 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700835 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 DisplayInfo info = DisplayInfo();
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 float xdpi = hwConfig->getDpiX();
839 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700841 info.w = hwConfig->getWidth();
842 info.h = hwConfig->getHeight();
843 // Default display viewport to display width and height
844 info.viewportW = info.w;
845 info.viewportH = info.h;
846
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 // The density of the device is provided by a build property
849 float density = Density::getBuildDensity() / 160.0f;
850 if (density == 0) {
851 // the build doesn't provide a density -- this is wrong!
852 // use xdpi instead
853 ALOGE("ro.sf.lcd_density must be defined as a build property");
854 density = xdpi / 160.0f;
855 }
856 if (Density::getEmuDensity()) {
857 // if "qemu.sf.lcd_density" is specified, it overrides everything
858 xdpi = ydpi = density = Density::getEmuDensity();
859 density /= 160.0f;
860 }
861 info.density = density;
862
863 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700864 const auto display = getDefaultDisplayDeviceLocked();
865 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700866
867 // This is for screenrecord
868 const Rect viewport = display->getViewport();
869 if (viewport.isValid()) {
870 info.viewportW = uint32_t(viewport.getWidth());
871 info.viewportH = uint32_t(viewport.getHeight());
872 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700873 } else {
874 // TODO: where should this value come from?
875 static const int TV_DENSITY = 213;
876 info.density = TV_DENSITY / 160.0f;
877 info.orientation = 0;
878 }
879
Dan Stoza7f7da322014-05-02 15:26:25 -0700880 info.xdpi = xdpi;
881 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900883 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884
Andy McFadden91b2ca82014-06-13 14:04:23 -0700885 // This is how far in advance a buffer must be queued for
886 // presentation at a given time. If you want a buffer to appear
887 // on the screen at time N, you must submit the buffer before
888 // (N - presentationDeadline).
889 //
890 // Normally it's one full refresh period (to give SF a chance to
891 // latch the buffer), but this can be reduced by configuring a
892 // DispSync offset. Any additional delays introduced by the hardware
893 // composer or panel must be accounted for here.
894 //
895 // We add an additional 1ms to allow for processing time and
896 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800898 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
900 // All non-virtual displays are currently considered secure.
901 info.secure = true;
902
Dominik Laskowski075d3172018-05-24 15:50:06 -0700903 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700904 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800905 std::swap(info.w, info.h);
906 }
907
Michael Wright28f24d02016-07-12 13:30:53 -0700908 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700909 }
910
Dan Stoza7f7da322014-05-02 15:26:25 -0700911 return NO_ERROR;
912}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
915 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700916 return BAD_VALUE;
917 }
918
Ana Krulece588e312018-09-18 12:32:24 -0700919 if (mUseScheduler) {
920 mScheduler->getDisplayStatInfo(stats);
921 } else {
922 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
923 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
924 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700925 return NO_ERROR;
926}
927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
929 const auto display = getDisplayDevice(displayToken);
930 if (!display) {
931 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800932 return BAD_VALUE;
933 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700936}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700939 if (display->isVirtual()) {
940 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
941 return;
942 }
943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700946 return;
947 }
948
Dominik Laskowski075d3172018-05-24 15:50:06 -0700949 const auto displayId = display->getId();
950 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700951
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700953 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700954}
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700957 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 Vector<DisplayInfo> configs;
959 getDisplayConfigs(displayToken, &configs);
960 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
961 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
962 configs.size());
963 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 const auto display = getDisplayDevice(displayToken);
966 if (!display) {
967 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
968 displayToken.get());
969 } else if (display->isVirtual()) {
970 ALOGW("Attempt to set active config %d for virtual display", mode);
971 } else {
972 setActiveConfigInternal(display, mode);
973 }
974 }));
975
Mathias Agopian888c8222012-08-04 21:10:38 -0700976 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700977}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
980 Vector<ColorMode>* outColorModes) {
981 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 return BAD_VALUE;
983 }
984
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 const auto displayId = getPhysicalDisplayId(displayToken);
986 if (!displayId) {
987 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700988 }
989
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700991 {
992 ConditionalLock _l(mStateLock,
993 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700994 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -0700995 }
Michael Wright28f24d02016-07-12 13:30:53 -0700996 outColorModes->clear();
997 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
998
999 return NO_ERROR;
1000}
1001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1003 if (const auto display = getDisplayDevice(displayToken)) {
1004 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001005 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001006 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1010 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001011 if (display->isVirtual()) {
1012 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1013 return;
1014 }
1015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 ColorMode currentMode = display->getActiveColorMode();
1017 Dataspace currentDataSpace = display->getCompositionDataSpace();
1018 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001019
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 if (mode == currentMode && dataSpace == currentDataSpace &&
1021 renderIntent == currentRenderIntent) {
1022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 display->setActiveColorMode(mode);
1026 display->setCompositionDataSpace(dataSpace);
1027 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028
Dominik Laskowski075d3172018-05-24 15:50:06 -07001029 const auto displayId = display->getId();
1030 LOG_ALWAYS_FATAL_IF(!displayId);
1031 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1032
Dominik Laskowski34157762018-10-31 13:07:19 -07001033 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001035 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001036}
1037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001039 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 Vector<ColorMode> modes;
1041 getDisplayColorModes(displayToken, &modes);
1042 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1043 if (mode < ColorMode::NATIVE || !exists) {
1044 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1045 decodeColorMode(mode).c_str(), mode, displayToken.get());
1046 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001047 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048 const auto display = getDisplayDevice(displayToken);
1049 if (!display) {
1050 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1051 decodeColorMode(mode).c_str(), mode, displayToken.get());
1052 } else if (display->isVirtual()) {
1053 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1054 decodeColorMode(mode).c_str(), mode);
1055 } else {
1056 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1057 RenderIntent::COLORIMETRIC);
1058 }
1059 }));
1060
Michael Wright28f24d02016-07-12 13:30:53 -07001061 return NO_ERROR;
1062}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001063
Svetoslavd85084b2014-03-20 10:28:31 -07001064status_t SurfaceFlinger::clearAnimationFrameStats() {
1065 Mutex::Autolock _l(mStateLock);
1066 mAnimFrameTracker.clearStats();
1067 return NO_ERROR;
1068}
1069
1070status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1071 Mutex::Autolock _l(mStateLock);
1072 mAnimFrameTracker.getStats(outStats);
1073 return NO_ERROR;
1074}
1075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1077 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001078 Mutex::Autolock _l(mStateLock);
1079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 const auto display = getDisplayDeviceLocked(displayToken);
1081 if (!display) {
1082 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001083 return BAD_VALUE;
1084 }
1085
Peiyong Linfb069302018-04-25 14:34:31 -07001086 // At this point the DisplayDeivce should already be set up,
1087 // meaning the luminance information is already queried from
1088 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001089 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001090 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1091 capabilities.getDesiredMaxLuminance(),
1092 capabilities.getDesiredMaxAverageLuminance(),
1093 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001094
1095 return NO_ERROR;
1096}
1097
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001098status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1099 ui::PixelFormat* outFormat,
1100 ui::Dataspace* outDataspace,
1101 uint8_t* outComponentMask) const {
1102 if (!outFormat || !outDataspace || !outComponentMask) {
1103 return BAD_VALUE;
1104 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001105 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001106 if (!display || !display->getId()) {
1107 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1108 return BAD_VALUE;
1109 }
1110 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1111 outDataspace, outComponentMask);
1112}
1113
Kevin DuBois74e53772018-11-19 10:52:38 -08001114status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1115 bool enable, uint8_t componentMask,
1116 uint64_t maxFrames) const {
1117 const auto display = getDisplayDevice(displayToken);
1118 if (!display || !display->getId()) {
1119 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1120 return BAD_VALUE;
1121 }
1122
1123 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1124 componentMask, maxFrames);
1125}
1126
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001127status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1128 uint64_t maxFrames, uint64_t timestamp,
1129 DisplayedFrameStats* outStats) const {
1130 const auto display = getDisplayDevice(displayToken);
1131 if (!display || !display->getId()) {
1132 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1133 return BAD_VALUE;
1134 }
1135
1136 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1137 outStats);
1138}
1139
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001140status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001141 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001142 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001143
Chia-I Wu90f669f2017-10-05 14:24:41 -07001144 if (mInjectVSyncs == enable) {
1145 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147
Ana Krulec98b5b242018-08-10 15:03:23 -07001148 // TODO(akrulec): Part of the Injector should be refactored, so that it
1149 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150 if (enable) {
1151 ALOGV("VSync Injections enabled");
1152 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001153 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001154 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001155 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001156 impl::EventThread::InterceptVSyncsCallback(),
1157 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001159 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 } else {
1161 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 }
1164
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001165 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001166 }));
1167
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001168 return NO_ERROR;
1169}
1170
1171status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 Mutex::Autolock _l(mStateLock);
1173
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001174 if (!mInjectVSyncs) {
1175 ALOGE("VSync Injections not enabled");
1176 return BAD_VALUE;
1177 }
1178 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1179 ALOGV("Injecting VSync inside SurfaceFlinger");
1180 mVSyncInjector->onInjectSyncEvent(when);
1181 }
1182 return NO_ERROR;
1183}
1184
Lloyd Pique755e3192018-01-31 16:46:15 -08001185status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1186 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001187 // Try to acquire a lock for 1s, fail gracefully
1188 const status_t err = mStateLock.timedLock(s2ns(1));
1189 const bool locked = (err == NO_ERROR);
1190 if (!locked) {
1191 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1192 return TIMED_OUT;
1193 }
1194
1195 outLayers->clear();
1196 mCurrentState.traverseInZOrder([&](Layer* layer) {
1197 outLayers->push_back(layer->getLayerDebugInfo());
1198 });
1199
1200 mStateLock.unlock();
1201 return NO_ERROR;
1202}
1203
Peiyong Linc6780972018-10-28 15:24:08 -07001204status_t SurfaceFlinger::getCompositionPreference(
1205 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1206 Dataspace* outWideColorGamutDataspace,
1207 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001208 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001209 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001210 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001211 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001212 return NO_ERROR;
1213}
1214
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001215// ----------------------------------------------------------------------------
1216
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001217sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1218 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001219 if (mUseScheduler) {
1220 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1221 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1222 } else {
1223 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1224 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001225 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001226 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1227 return mSFEventThread->createEventConnection();
1228 } else {
1229 return mEventThread->createEventConnection();
1230 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001231 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001232}
1233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001234// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001235
1236void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001237 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001238}
1239
1240void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001245 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001246}
1247
1248void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001249 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001250 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001251}
1252
1253status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001254 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001255 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256}
1257
1258status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001259 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001260 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261 if (res == NO_ERROR) {
1262 msg->wait();
1263 }
1264 return res;
1265}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001266
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001267void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001268 do {
1269 waitForEvent();
1270 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001271}
1272
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273void SurfaceFlinger::enableHardwareVsync() {
1274 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001275 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001276 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001277 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001279 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280}
1281
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 Mutex::Autolock _l(mHWVsyncLock);
1284
Jesse Hall948fe0c2013-10-14 12:56:09 -07001285 if (makeAvailable) {
1286 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001287 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1288 if (mUseScheduler) {
1289 mScheduler->makeHWSyncAvailable(true);
1290 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001292 // Hardware vsync is not currently available, so abort the resync
1293 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001294 return;
1295 }
1296
Dominik Laskowski075d3172018-05-24 15:50:06 -07001297 const auto displayId = getInternalDisplayId();
1298 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001299 return;
1300 }
1301
Dominik Laskowski075d3172018-05-24 15:50:06 -07001302 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304
Ana Krulece588e312018-09-18 12:32:24 -07001305 if (mUseScheduler) {
1306 mScheduler->setVsyncPeriod(period);
1307 } else {
1308 mPrimaryDispSync->reset();
1309 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310
Ana Krulece588e312018-09-18 12:32:24 -07001311 if (!mPrimaryHWVsyncEnabled) {
1312 mPrimaryDispSync->beginResync();
1313 mEventControlThread->setVsyncEnabled(true);
1314 mPrimaryHWVsyncEnabled = true;
1315 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 }
1317}
1318
Jesse Hall948fe0c2013-10-14 12:56:09 -07001319void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320 Mutex::Autolock _l(mHWVsyncLock);
1321 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001322 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001323 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324 mPrimaryHWVsyncEnabled = false;
1325 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001326 if (makeUnavailable) {
1327 mHWVsyncAvailable = false;
1328 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329}
1330
Tim Murray4a4e4a22016-04-19 16:29:23 +00001331void SurfaceFlinger::resyncWithRateLimit() {
1332 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001333
1334 // No explicit locking is needed here since EventThread holds a lock while calling this method
1335 static nsecs_t sLastResyncAttempted = 0;
1336 const nsecs_t now = systemTime();
1337 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001338 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001339 }
Dan Stoza57164302017-05-08 14:03:54 -07001340 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001341}
1342
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001343void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1344 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001345 ATRACE_NAME("SF onVsync");
1346
Steven Thomas3cfac282017-02-06 12:29:30 -08001347 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001349 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001350 return;
1351 }
1352
Dominik Laskowski075d3172018-05-24 15:50:06 -07001353 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001354 return;
1355 }
1356
Dominik Laskowski075d3172018-05-24 15:50:06 -07001357 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001358 // For now, we don't do anything with external display vsyncs.
1359 return;
1360 }
1361
Ana Krulece588e312018-09-18 12:32:24 -07001362 if (mUseScheduler) {
1363 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001364 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001365 bool needsHwVsync = false;
1366 { // Scope for the lock
1367 Mutex::Autolock _l(mHWVsyncLock);
1368 if (mPrimaryHWVsyncEnabled) {
1369 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1370 }
1371 }
1372
1373 if (needsHwVsync) {
1374 enableHardwareVsync();
1375 } else {
1376 disableHardwareVsync(false);
1377 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001378 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001379}
1380
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001381void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001382 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1383 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001384}
1385
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001386void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001387 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001388 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001389 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390
Lloyd Piqueba04e622017-12-14 17:11:26 -08001391 // Ignore events that do not have the right sequenceId.
1392 if (sequenceId != getBE().mComposerSequenceId) {
1393 return;
1394 }
1395
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 // Only lock if we're not on the main thread. This function is normally
1397 // called on a hwbinder thread, but for the primary display it's called on
1398 // the main thread with the state lock already held, so don't attempt to
1399 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001400 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001401
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001402 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001403
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001404 if (std::this_thread::get_id() == mMainThreadId) {
1405 // Process all pending hot plug events immediately if we are on the main thread.
1406 processDisplayHotplugEventsLocked();
1407 }
1408
Lloyd Piqueba04e622017-12-14 17:11:26 -08001409 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001410}
1411
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001412void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001413 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001414 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001416 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001417 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001418}
1419
Dominik Laskowski075d3172018-05-24 15:50:06 -07001420void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001421 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001423 if (const auto displayId = getInternalDisplayId()) {
1424 getHwComposer().setVsyncEnabled(*displayId,
1425 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1426 }
Mathias Agopian86303202012-07-24 22:46:10 -07001427}
1428
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001430void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001431 if (mUseScheduler) {
1432 mScheduler->disableHardwareVsync(true);
1433 } else {
1434 disableHardwareVsync(true);
1435 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436 // Clear the drawing state so that the logic inside of
1437 // handleTransactionLocked will fire. It will determine the delta between
1438 // mCurrentState and mDrawingState and re-apply all changes when we make the
1439 // transition.
1440 mDrawingState.displays.clear();
1441 mDisplays.clear();
1442}
1443
Steven Thomas050b2c82017-03-06 11:45:16 -08001444void SurfaceFlinger::updateVrFlinger() {
1445 if (!mVrFlinger)
1446 return;
1447 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001448 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001449 return;
1450 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451
Lloyd Pique441d5042018-10-18 16:49:51 -07001452 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 ALOGE("Vr flinger is only supported for remote hardware composer"
1454 " service connections. Ignoring request to transition to vr"
1455 " flinger.");
1456 mVrFlingerRequestsDisplay = false;
1457 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001458 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001460 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001461
Steven Thomas0123ac62018-07-12 11:32:34 -07001462 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001463 LOG_ALWAYS_FATAL_IF(!display);
1464 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001465 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1466 // called below. Clear the reference now so we don't accidentally use it
1467 // later.
1468 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473
Steven Thomasb02664d2017-07-26 18:48:28 -07001474 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001475 // Delete the current instance before creating the new one
1476 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1477 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1478 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1479 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001480
Lloyd Pique441d5042018-10-18 16:49:51 -07001481 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001482 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001483
1484 if (vrFlingerRequestsDisplay) {
1485 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001486 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001487
1488 mVisibleRegionsDirty = true;
1489 invalidateHwcGeometry();
1490
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001491 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001492 display = getDefaultDisplayDeviceLocked();
1493 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001494 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001495
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001497 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 const nsecs_t period = activeConfig->getVsyncPeriod();
1499 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001500
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001501 // The present fences returned from vr_hwc are not an accurate
1502 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001503 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001504 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1505 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001506 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001507 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001508 !hasSyncFramework);
1509 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001510
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 // Use phase of 0 since phase is not known.
1512 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001513 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1514 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001515
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001516 resyncToHardwareVsync(false);
1517
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001518 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001520}
1521
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001523 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001524 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001526 if (mUseScheduler) {
1527 // This call is made each time SF wakes up and creates a new frame.
1528 mScheduler->incrementFrameCounter();
1529 }
Dan Stoza50182882016-07-08 12:02:20 -07001530 bool frameMissed = !mHadClientComposition &&
1531 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 (mPreviousPresentFence->getSignalTime() ==
1533 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001534 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001535 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001536 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001537 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001538 if (mPropagateBackpressure) {
1539 signalLayerUpdate();
1540 break;
1541 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001542 }
Dan Stoza50182882016-07-08 12:02:20 -07001543
Steven Thomas050b2c82017-03-06 11:45:16 -08001544 // Now that we're going to make it to the handleMessageTransaction()
1545 // call below it's safe to call updateVrFlinger(), which will
1546 // potentially trigger a display handoff.
1547 updateVrFlinger();
1548
Dan Stoza6b9454d2014-11-07 16:00:59 -08001549 bool refreshNeeded = handleMessageTransaction();
1550 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001551 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001552 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001553 // Signal a refresh if a transaction modified the window state,
1554 // a new buffer was latched, or if HWC has requested a full
1555 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 signalRefresh();
1557 }
1558 break;
1559 }
1560 case MessageQueue::REFRESH: {
1561 handleMessageRefresh();
1562 break;
1563 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001564 }
1565}
1566
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001568 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001569
1570 // Apply any ready transactions in the queues if there are still transactions that have not been
1571 // applied, wake up during the next vsync period and check again
1572 bool transactionNeeded = false;
1573 if (!flushTransactionQueues()) {
1574 transactionNeeded = true;
1575 }
1576
Mathias Agopian4fec8732012-06-29 14:12:52 -07001577 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001578 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001580
1581 if (transactionNeeded) {
1582 setTransactionFlags(eTransactionNeeded);
1583 }
1584
1585 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001586}
1587
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001590
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001591 mRefreshPending = false;
1592
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001593 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001594 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001595 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001596 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001597 for (const auto& [token, display] : mDisplays) {
1598 beginFrame(display);
1599 prepareFrame(display);
1600 doDebugFlashRegions(display, repaintEverything);
1601 doComposition(display, repaintEverything);
1602 }
1603
Adrian Roos1e1a1282017-11-01 19:05:31 +01001604 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001605 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001606
1607 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001608 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001609
Dan Stozabfbffeb2016-07-21 14:49:33 -07001610 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001611 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001612 mHadClientComposition =
1613 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001614 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001615
Alec Mouri86770e52018-09-24 22:40:58 +00001616 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001617 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001618 if (mHadClientComposition) {
1619 base::unique_fd flushFence(getRenderEngine().flush());
1620 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1621 getBE().flushFence = new Fence(std::move(flushFence));
1622 } else {
1623 // Cleanup for hygiene.
1624 getBE().flushFence = Fence::NO_FENCE;
1625 }
1626 }
1627
Jorim Jaggi90535212018-05-23 23:44:06 +02001628 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001629
David Sodman7e4ae112018-02-09 15:02:28 -08001630 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001631 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001632 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001633 compositionInfo.hwc.hwcLayer = nullptr;
1634 }
David Sodmanba340492018-08-05 21:51:33 -07001635 }
David Sodman7e4ae112018-02-09 15:02:28 -08001636
1637 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001639
David Sodmanfa9b2af2017-12-24 13:28:59 -08001640
1641bool SurfaceFlinger::handleMessageInvalidate() {
1642 ATRACE_CALL();
1643 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644}
1645
David Sodman79bba0e2018-08-05 18:07:49 -07001646void SurfaceFlinger::calculateWorkingSet() {
1647 ATRACE_CALL();
1648 ALOGV(__FUNCTION__);
1649
David Sodman79bba0e2018-08-05 18:07:49 -07001650 // build the h/w work list
1651 if (CC_UNLIKELY(mGeometryInvalid)) {
1652 mGeometryInvalid = false;
1653 for (const auto& [token, display] : mDisplays) {
1654 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001655 if (!displayId) {
1656 continue;
1657 }
David Sodman79bba0e2018-08-05 18:07:49 -07001658
Dominik Laskowski075d3172018-05-24 15:50:06 -07001659 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1660 for (size_t i = 0; i < currentLayers.size(); i++) {
1661 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001662
Dominik Laskowski075d3172018-05-24 15:50:06 -07001663 if (!layer->hasHwcLayer(*displayId)) {
1664 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1665 layer->forceClientComposition(*displayId);
1666 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001667 }
1668 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001669
1670 layer->setGeometry(display, i);
1671 if (mDebugDisableHWC || mDebugRegion) {
1672 layer->forceClientComposition(*displayId);
1673 }
David Sodman79bba0e2018-08-05 18:07:49 -07001674 }
1675 }
1676 }
1677
1678 // Set the per-frame data
1679 for (const auto& [token, display] : mDisplays) {
1680 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001681 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001682 continue;
1683 }
1684
1685 if (mDrawingState.colorMatrixChanged) {
1686 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001687 status_t result =
1688 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001689 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1690 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001691 }
1692 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1693 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001694 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001695 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1696 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1697 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001698 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001699 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1700 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1701 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001702 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001703 }
1704
Peiyong Lind3788632018-09-18 16:01:31 -07001705 // TODO(b/111562338) remove when composer 2.3 is shipped.
1706 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001707 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001708 }
1709
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001710 if (layer->getRoundedCornerState().radius > 0.0f) {
1711 layer->forceClientComposition(*displayId);
1712 }
1713
Dominik Laskowski075d3172018-05-24 15:50:06 -07001714 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001715 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001716 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001717 continue;
1718 }
1719
Dominik Laskowski075d3172018-05-24 15:50:06 -07001720 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1721 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001722 }
1723
Peiyong Lin13effd12018-07-24 17:01:47 -07001724 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001725 ColorMode colorMode;
1726 Dataspace dataSpace;
1727 RenderIntent renderIntent;
1728 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1729 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1730 }
1731 }
1732
1733 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001734
1735 for (const auto& [token, display] : mDisplays) {
1736 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001737 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001738 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739
1740 if (displayId) {
1741 if (!layer->setHwcLayer(*displayId)) {
1742 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1743 }
1744 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001745 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746
Dominik Laskowski05275f12018-11-01 15:03:24 -07001747 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001748 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1749 }
1750 }
David Sodman79bba0e2018-08-05 18:07:49 -07001751}
1752
David Sodmanfa9b2af2017-12-24 13:28:59 -08001753void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754{
1755 // is debugging enabled
1756 if (CC_LIKELY(!mDebugRegion))
1757 return;
1758
David Sodmanfa9b2af2017-12-24 13:28:59 -08001759 if (display->isPoweredOn()) {
1760 // transform the dirty region into this screen's coordinate space
1761 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1762 if (!dirtyRegion.isEmpty()) {
1763 // redraw the whole screen
1764 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765
David Sodmanfa9b2af2017-12-24 13:28:59 -08001766 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001767 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001768 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001769
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001770 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771 }
1772 }
1773
David Sodmanfa9b2af2017-12-24 13:28:59 -08001774 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775
1776 if (mDebugRegion > 1) {
1777 usleep(mDebugRegion * 1000);
1778 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001779
Dominik Laskowski05275f12018-11-01 15:03:24 -07001780 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001781}
1782
Adrian Roos1e1a1282017-11-01 19:05:31 +01001783void SurfaceFlinger::doTracing(const char* where) {
1784 ATRACE_CALL();
1785 ATRACE_NAME(where);
1786 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001787 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001788 }
1789}
1790
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001791void SurfaceFlinger::logLayerStats() {
1792 ATRACE_CALL();
1793 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001794 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001795 if (display->isPrimary()) {
1796 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001797 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001798 }
1799 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001800
1801 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001802 }
1803}
1804
David Sodman2b406362017-12-15 13:33:47 -08001805void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 ATRACE_CALL();
1808 ALOGV("preComposition");
1809
David Sodman2b406362017-12-15 13:33:47 -08001810 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1811
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001813 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001814 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815 needExtraInvalidate = true;
1816 }
Robert Carr2047fae2016-11-28 14:09:09 -08001817 });
1818
Mathias Agopiancd60f992012-08-16 16:28:27 -07001819 if (needExtraInvalidate) {
1820 signalLayerUpdate();
1821 }
1822}
1823
Ana Krulece588e312018-09-18 12:32:24 -07001824void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1825 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826 // Update queue of past composite+present times and determine the
1827 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001828 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001829 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001830 while (!getBE().mCompositePresentTimes.empty()) {
1831 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 // Cached values should have been updated before calling this method,
1833 // which helps avoid duplicate syscalls.
1834 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1835 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1836 break;
1837 }
1838 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001839 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 }
1841
1842 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001843 while (getBE().mCompositePresentTimes.size() > 16) {
1844 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001845 }
1846
Ana Krulece588e312018-09-18 12:32:24 -07001847 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001848}
1849
Ana Krulece588e312018-09-18 12:32:24 -07001850void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1851 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 // Integer division and modulo round toward 0 not -inf, so we need to
1853 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001854 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1855 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1856 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857
Brian Andersond0010582017-03-07 13:20:31 -08001858 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1859 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001860 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001861 }
1862
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001863 // Snap the latency to a value that removes scheduling jitter from the
1864 // composition and present times, which often have >1ms of jitter.
1865 // Reducing jitter is important if an app attempts to extrapolate
1866 // something (such as user input) to an accurate diasplay time.
1867 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1868 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001869 nsecs_t bias = stats.vsyncPeriod / 2;
1870 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1871 nsecs_t snappedCompositeToPresentLatency =
1872 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001873
David Sodman99974d22017-11-28 12:04:33 -08001874 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001875 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1876 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001877 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001878}
1879
Ady Abraham8164d482019-01-11 14:47:59 -08001880// debug patch for b/119477596 - add stack guards to catch stack
1881// corruptions and disable clang optimizations.
1882// The code below is temporary and planned to be removed once stack
1883// corruptions are found.
1884#pragma clang optimize off
1885class StackGuard {
1886public:
1887 StackGuard(const char* name, const char* func, int line) {
1888 guarders.reserve(MIN_CAPACITY);
1889 guarders.push_back({this, name, func, line});
1890 validate();
1891 }
1892 ~StackGuard() {
1893 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1894 if (i->guard == this) {
1895 guarders.erase(i);
1896 break;
1897 }
1898 }
1899 }
1900
1901 static void validate() {
1902 for (const auto& guard : guarders) {
1903 if (guard.guard->cookie != COOKIE_VALUE) {
1904 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1905 CallStack stack(LOG_TAG);
1906 abort();
1907 }
1908 }
1909 }
1910
1911private:
1912 uint64_t cookie = COOKIE_VALUE;
1913 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1914 static constexpr size_t MIN_CAPACITY = 16;
1915
1916 struct GuarderElement {
1917 StackGuard* guard;
1918 const char* name;
1919 const char* func;
1920 int line;
1921 };
1922
1923 static std::vector<GuarderElement> guarders;
1924};
1925std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1926
1927#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1928
1929#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001930void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931{
Ady Abraham8164d482019-01-11 14:47:59 -08001932 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 ATRACE_CALL();
1934 ALOGV("postComposition");
1935
Brian Anderson3546a3f2016-07-14 11:51:14 -07001936 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001937 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001938 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001939 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001940 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001941 }
Ady Abraham8164d482019-01-11 14:47:59 -08001942 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001943
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001944 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001945 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08001946 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001947
David Sodman73beded2017-11-15 11:56:06 -08001948 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001949 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08001950 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
1951
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001952 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001953 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001954 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001955 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001956 } else {
1957 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1958 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001959
Ady Abraham8164d482019-01-11 14:47:59 -08001960 ASSERT_ON_STACK_GUARD();
1961
David Sodman73beded2017-11-15 11:56:06 -08001962 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001963 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001964 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001965 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08001966 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08001967 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001968
Ana Krulece588e312018-09-18 12:32:24 -07001969 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08001970 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07001971 if (mUseScheduler) {
1972 mScheduler->getDisplayStatInfo(&stats);
1973 } else {
1974 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1975 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1976 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977
Ady Abraham8164d482019-01-11 14:47:59 -08001978 ASSERT_ON_STACK_GUARD();
1979
David Sodman2b406362017-12-15 13:33:47 -08001980 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 // when we started doing work for this frame, but that should be okay
1982 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001983 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001984 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08001985 DEFINE_STACK_GUARD(compositorTiming);
1986
Brian Andersond0010582017-03-07 13:20:31 -08001987 {
David Sodman99974d22017-11-28 12:04:33 -08001988 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08001989 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08001990 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08001991
1992 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08001993 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994
Robert Carr2047fae2016-11-28 14:09:09 -08001995 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001996 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1997 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08001998 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07001999 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002000 recordBufferingStats(layer->getName().string(),
2001 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002002 }
Ady Abraham8164d482019-01-11 14:47:59 -08002003 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002004 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002005
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002006 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002007 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002008 if (mUseScheduler) {
2009 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002010 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002011 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002012 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2013 enableHardwareVsync();
2014 } else {
2015 disableHardwareVsync(false);
2016 }
Ady Abraham8164d482019-01-11 14:47:59 -08002017 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002018 }
2019 }
2020
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002021 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002022 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002023 if (mUseScheduler) {
2024 mScheduler->enableHardwareVsync();
2025 } else {
2026 enableHardwareVsync();
2027 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002028 }
2029 }
2030
Ady Abraham8164d482019-01-11 14:47:59 -08002031 ASSERT_ON_STACK_GUARD();
2032
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002033 if (mAnimCompositionPending) {
2034 mAnimCompositionPending = false;
2035
Brian Anderson4e606e32017-03-16 15:34:57 -07002036 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002038 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002039
2040 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002041 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002042 // The HWC doesn't support present fences, so use the refresh
2043 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002044 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002045 DEFINE_STACK_GUARD(presentTime);
2046
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002047 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002048 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002049 }
2050 mAnimFrameTracker.advanceFrame();
2051 }
Dan Stozab90cf072015-03-05 11:05:59 -08002052
Ady Abraham8164d482019-01-11 14:47:59 -08002053 ASSERT_ON_STACK_GUARD();
2054
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002055 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002056 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002057 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002058 }
2059
Ady Abraham8164d482019-01-11 14:47:59 -08002060 ASSERT_ON_STACK_GUARD();
2061
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002062 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002063
Ady Abraham8164d482019-01-11 14:47:59 -08002064 ASSERT_ON_STACK_GUARD();
2065
Dominik Laskowski075d3172018-05-24 15:50:06 -07002066 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002067 return;
2068 }
2069
2070 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002071 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002072 if (mHasPoweredOff) {
2073 mHasPoweredOff = false;
2074 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002075 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002076 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002077 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002078 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002079 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2080 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002081 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002082 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002083 }
David Sodman4a36e932017-11-07 14:29:47 -08002084 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002085
2086 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002087 }
David Sodman4a36e932017-11-07 14:29:47 -08002088 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002089 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002090
2091 {
2092 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002093 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002094 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002095 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002096 if (refillCount > 0) {
2097 const size_t offset = mTexturePool.size();
2098 mTexturePool.resize(mTexturePoolSize);
2099 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2100 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2101 }
Ady Abraham8164d482019-01-11 14:47:59 -08002102 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002103 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002104
Marissa Wallfda30bb2018-10-12 11:34:28 -07002105 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002106 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002107
2108 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002109}
Ady Abraham8164d482019-01-11 14:47:59 -08002110#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002111
2112void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002113 ATRACE_CALL();
2114 ALOGV("rebuildLayerStacks");
2115
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002116 // We need to clear these out now as these may be holding on to a
2117 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2118 // also holds a reference. When the set of visible layers is recomputed,
2119 // some layers may be destroyed if the only thing keeping them alive was
2120 // that list of visible layers associated with each display. The layer
2121 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2122 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2123 for (const auto& [token, display] : mDisplays) {
2124 getBE().mCompositionInfo[token].clear();
2125 }
2126
Mathias Agopiancd60f992012-08-16 16:28:27 -07002127 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002128 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002129 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002130 mVisibleRegionsDirty = false;
2131 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002132
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002133 for (const auto& pair : mDisplays) {
2134 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002135 Region opaqueRegion;
2136 Region dirtyRegion;
2137 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002138 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002139 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002140 const Rect bounds = display->getBounds();
2141 if (display->isPoweredOn()) {
2142 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002143
Jeff Sharkey76488112017-02-27 14:15:18 -07002144 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002145 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002146 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002147 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002148 Region drawRegion(tr.transform(
2149 layer->visibleNonTransparentRegion));
2150 drawRegion.andSelf(bounds);
2151 if (!drawRegion.isEmpty()) {
2152 layersSortedByZ.add(layer);
2153 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002154 // Clear out the HWC layer if this layer was
2155 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002156 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002157 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002158 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002159 // WM changes display->layerStack upon sleep/awake.
2160 // Here we make sure we delete the HWC layers even if
2161 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002162 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002163 }
2164
2165 // If a layer is not going to get a release fence because
2166 // it is invisible, but it is also going to release its
2167 // old buffer, add it to the list of layers needing
2168 // fences.
2169 if (hwcLayerDestroyed) {
2170 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2171 mLayersWithQueuedFrames.cend(), layer);
2172 if (found != mLayersWithQueuedFrames.cend()) {
2173 layersNeedingFences.add(layer);
2174 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002175 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002176 });
2177 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 display->setVisibleLayersSortedByZ(layersSortedByZ);
2179 display->setLayersNeedingFences(layersNeedingFences);
2180 display->undefinedRegion.set(bounds);
2181 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2182 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002183 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002184 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002185}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002186
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002187// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002188// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002189// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002190// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002191// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002192// The returned HDR data space is one of
2193// - Dataspace::UNKNOWN
2194// - Dataspace::BT2020_HLG
2195// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2197 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002198 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002199 *outHdrDataSpace = Dataspace::UNKNOWN;
2200
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002201 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002202 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002203 case Dataspace::V0_SCRGB:
2204 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002205 case Dataspace::BT2020:
2206 case Dataspace::BT2020_ITU:
2207 case Dataspace::BT2020_LINEAR:
2208 case Dataspace::DISPLAY_BT2020:
2209 bestDataSpace = Dataspace::DISPLAY_BT2020;
2210 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002211 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002212 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002213 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002214 case Dataspace::BT2020_PQ:
2215 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002216 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002217 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002218 case Dataspace::BT2020_HLG:
2219 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002220 // When there's mixed PQ content and HLG content, we set the HDR
2221 // data space to be BT2020_PQ and convert HLG to PQ.
2222 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2223 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002224 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002225 break;
2226 default:
2227 break;
2228 }
Romain Guy54f154a2017-10-24 21:40:32 +01002229 }
2230
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002231 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002232}
2233
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002234// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002235void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2236 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002237 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2238 *outMode = ColorMode::NATIVE;
2239 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002240 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002241 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002242 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002243
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002244 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002246
Peiyong Lindfde5112018-06-05 10:58:41 -07002247 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002248 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002249 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002250 if (isHdr) {
2251 bestDataSpace = hdrDataSpace;
2252 }
2253
Chia-I Wu0d711262018-05-21 15:19:35 -07002254 RenderIntent intent;
2255 switch (mDisplayColorSetting) {
2256 case DisplayColorSetting::MANAGED:
2257 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002258 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002259 break;
2260 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002261 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002262 break;
2263 default: // vendor display color setting
2264 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2265 break;
2266 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002267
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002268 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002269}
2270
David Sodmanfa9b2af2017-12-24 13:28:59 -08002271void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002272{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273 bool dirty = !display->getDirtyRegion(false).isEmpty();
2274 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2275 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002276
David Sodmanfa9b2af2017-12-24 13:28:59 -08002277 // If nothing has changed (!dirty), don't recompose.
2278 // If something changed, but we don't currently have any visible layers,
2279 // and didn't when we last did a composition, then skip it this time.
2280 // The second rule does two things:
2281 // - When all layers are removed from a display, we'll emit one black
2282 // frame, then nothing more until we get new layers.
2283 // - When a display is created with a private layer stack, we won't
2284 // emit any black frames until a layer is added to the layer stack.
2285 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002286
Dominik Laskowski075d3172018-05-24 15:50:06 -07002287 const char flagPrefix[] = {'-', '+'};
2288 static_cast<void>(flagPrefix);
2289 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2290 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2291 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002292
David Sodmanfa9b2af2017-12-24 13:28:59 -08002293 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002294
David Sodmanfa9b2af2017-12-24 13:28:59 -08002295 if (mustRecompose) {
2296 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002297 }
2298}
2299
David Sodmanfa9b2af2017-12-24 13:28:59 -08002300void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002301{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002302 if (!display->isPoweredOn()) {
2303 return;
David Sodman2b406362017-12-15 13:33:47 -08002304 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002305
Dominik Laskowski05275f12018-11-01 15:03:24 -07002306 status_t result = display->prepareFrame(getHwComposer(),
2307 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2309 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002310}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002311
David Sodmanfa9b2af2017-12-24 13:28:59 -08002312void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002313 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 ALOGV("doComposition");
2315
David Sodmanfa9b2af2017-12-24 13:28:59 -08002316 if (display->isPoweredOn()) {
2317 // transform the dirty region into this screen's coordinate space
2318 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002319
David Sodmanfa9b2af2017-12-24 13:28:59 -08002320 // repaint the framebuffer (if needed)
2321 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002322
David Sodmanfa9b2af2017-12-24 13:28:59 -08002323 display->dirtyRegion.clear();
2324 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002325 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002326 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002327}
2328
David Sodmanfa9b2af2017-12-24 13:28:59 -08002329void SurfaceFlinger::postFrame()
2330{
2331 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 const auto display = getDefaultDisplayDeviceLocked();
2333 if (display && getHwComposer().isConnected(*display->getId())) {
2334 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002335 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2336 logFrameStats();
2337 }
2338 }
2339}
2340
2341void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342{
Mathias Agopian841cde52012-03-01 15:44:37 -08002343 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002345
David Sodmanfa9b2af2017-12-24 13:28:59 -08002346 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002347
David Sodmanfa9b2af2017-12-24 13:28:59 -08002348 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002349 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002350 if (displayId) {
2351 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002352 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002353 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002354 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002355 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002356
Chia-I Wu7b549592017-11-15 09:14:57 -08002357 // The layer buffer from the previous frame (if any) is released
2358 // by HWC only when the release fence from this frame (if any) is
2359 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002360 if (displayId && layer->hasHwcLayer(*displayId)) {
2361 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2362 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002363 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002364
2365 // If the layer was client composited in the previous frame, we
2366 // need to merge with the previous client target acquire fence.
2367 // Since we do not track that, always merge with the current
2368 // client target acquire fence when it is available, even though
2369 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002370 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002371 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002373 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002374
David Sodman15094112018-10-11 09:39:37 -07002375 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 }
Chia-I Wu83806892017-11-16 10:50:20 -08002377
2378 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002380 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002382 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002383 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002384 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002385 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002386 }
2387 }
2388
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 if (displayId) {
2390 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002391 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393}
2394
Mathias Agopian87baae12012-07-31 12:38:26 -07002395void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396{
Mathias Agopian841cde52012-03-01 15:44:37 -08002397 ATRACE_CALL();
2398
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002399 // here we keep a copy of the drawing state (that is the state that's
2400 // going to be overwritten by handleTransactionLocked()) outside of
2401 // mStateLock so that the side-effects of the State assignment
2402 // don't happen with mStateLock held (which can cause deadlocks).
2403 State drawingState(mDrawingState);
2404
Mathias Agopianca4d3602011-05-19 15:38:14 -07002405 Mutex::Autolock _l(mStateLock);
2406 const nsecs_t now = systemTime();
2407 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408
Mathias Agopianca4d3602011-05-19 15:38:14 -07002409 // Here we're guaranteed that some transaction flags are set
2410 // so we can call handleTransactionLocked() unconditionally.
2411 // We call getTransactionFlags(), which will also clear the flags,
2412 // with mStateLock held to guarantee that mCurrentState won't change
2413 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002414
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002415 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002416 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002417 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002418
Mathias Agopianca4d3602011-05-19 15:38:14 -07002419 mLastTransactionTime = systemTime() - now;
2420 mDebugInTransaction = 0;
2421 invalidateHwcGeometry();
2422 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002423}
2424
Lloyd Piqueba04e622017-12-14 17:11:26 -08002425void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2426 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 const std::optional<DisplayIdentificationInfo> info =
2428 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002429
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431 continue;
2432 }
2433
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002436 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002437 mPhysicalDisplayTokens[info->id] = new BBinder();
2438 DisplayDeviceState state;
2439 state.displayId = info->id;
2440 state.isSecure = true; // All physical displays are currently considered secure.
2441 state.displayName = info->name;
2442 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2443 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002444 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002445 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002446 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2449 if (index >= 0) {
2450 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2451 mInterceptor->saveDisplayDeletion(state.sequenceId);
2452 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002453 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002455 }
2456
2457 processDisplayChangesLocked();
2458 }
2459
2460 mPendingHotplugEvents.clear();
2461}
2462
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002464 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2465 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2466 const sp<IGraphicBufferProducer>& producer) {
2467 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002468 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002470 creationArgs.isSecure = state.isSecure;
2471 creationArgs.displaySurface = dispSurface;
2472 creationArgs.hasWideColorGamut = false;
2473 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002474
Dominik Laskowski075d3172018-05-24 15:50:06 -07002475 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2476 creationArgs.isPrimary = isInternalDisplay;
2477
2478 if (useColorManagement && displayId) {
2479 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002480 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002481 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002482 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002483 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002484
Dominik Laskowski7e045462018-05-30 13:02:02 -07002485 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002487 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488 }
tangrobin6753a022018-08-10 10:58:54 +08002489 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 if (displayId) {
2492 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002493 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002495 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002496
Lloyd Pique90c115d2018-09-18 21:39:42 -07002497 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002498 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500
Lloyd Pique99d3da52018-01-22 17:48:03 -08002501 // Make sure that composition can never be stalled by a virtual display
2502 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002503 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002504 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2506 }
2507
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 creationArgs.displayInstallOrientation =
2509 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002510
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002512 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513
Lloyd Pique90c115d2018-09-18 21:39:42 -07002514 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515
2516 if (maxFrameBufferAcquiredBuffers >= 3) {
2517 nativeWindowSurface->preallocateBuffers();
2518 }
2519
2520 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002521 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002522 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002524 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002526 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002527 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 if (!state.isVirtual()) {
2529 LOG_ALWAYS_FATAL_IF(!displayId);
2530 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002531 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002533 display->setLayerStack(state.layerStack);
2534 display->setProjection(state.orientation, state.viewport, state.frame);
2535 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002536
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002538}
2539
Lloyd Pique347200f2017-12-14 17:00:15 -08002540void SurfaceFlinger::processDisplayChangesLocked() {
2541 // here we take advantage of Vector's copy-on-write semantics to
2542 // improve performance by skipping the transaction entirely when
2543 // know that the lists are identical
2544 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2545 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2546 if (!curr.isIdenticalTo(draw)) {
2547 mVisibleRegionsDirty = true;
2548 const size_t cc = curr.size();
2549 size_t dc = draw.size();
2550
2551 // find the displays that were removed
2552 // (ie: in drawing state but not in current state)
2553 // also handle displays that changed
2554 // (ie: displays that are in both lists)
2555 for (size_t i = 0; i < dc;) {
2556 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2557 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 // Save display IDs before disconnecting.
2559 const auto internalDisplayId = getInternalDisplayId();
2560 const auto externalDisplayId = getExternalDisplayId();
2561
Lloyd Pique347200f2017-12-14 17:00:15 -08002562 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002563 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2564 display->disconnect(getHwComposer());
2565 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002567 if (mUseScheduler) {
2568 mScheduler->hotplugReceived(mAppConnectionHandle,
2569 EventThread::DisplayType::Primary, false);
2570 } else {
2571 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2572 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002574 if (mUseScheduler) {
2575 mScheduler->hotplugReceived(mAppConnectionHandle,
2576 EventThread::DisplayType::External, false);
2577 } else {
2578 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2579 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002580 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002581 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002582 } else {
2583 // this display is in both lists. see if something changed.
2584 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002585 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2587 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2588 if (state_binder != draw_binder) {
2589 // changing the surface is like destroying and
2590 // recreating the DisplayDevice, so we just remove it
2591 // from the drawing state, so that it get re-added
2592 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002593 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2594 display->disconnect(getHwComposer());
2595 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002596 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 mDrawingState.displays.removeItemsAt(i);
2598 dc--;
2599 // at this point we must loop to the next item
2600 continue;
2601 }
2602
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002603 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002605 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 }
2607 if ((state.orientation != draw[i].orientation) ||
2608 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002610 }
2611 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614 }
2615 }
2616 ++i;
2617 }
2618
2619 // find displays that were added
2620 // (ie: in current state but not in drawing state)
2621 for (size_t i = 0; i < cc; i++) {
2622 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2623 const DisplayDeviceState& state(curr[i]);
2624
2625 sp<DisplaySurface> dispSurface;
2626 sp<IGraphicBufferProducer> producer;
2627 sp<IGraphicBufferProducer> bqProducer;
2628 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002629 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002630
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002632 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002633 // Virtual displays without a surface are dormant:
2634 // they have external state (layer stack, projection,
2635 // etc.) but no internal state (i.e. a DisplayDevice).
2636 if (state.surface != nullptr) {
2637 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002639 int width = 0;
2640 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2641 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2642 int height = 0;
2643 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2644 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2645 int intFormat = 0;
2646 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2647 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002648 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002649
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 displayId =
2651 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002652 }
2653
2654 // TODO: Plumb requested format back up to consumer
2655
2656 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002657 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002658 bqProducer, bqConsumer,
2659 state.displayName);
2660
2661 dispSurface = vds;
2662 producer = vds;
2663 }
2664 } else {
2665 ALOGE_IF(state.surface != nullptr,
2666 "adding a supported display, but rendering "
2667 "surface is provided (%p), ignoring it",
2668 state.surface.get());
2669
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670 displayId = state.displayId;
2671 LOG_ALWAYS_FATAL_IF(!displayId);
2672 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 producer = bqProducer;
2674 }
2675
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002679 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002680 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002681 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002682 LOG_ALWAYS_FATAL_IF(!displayId);
2683
2684 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002685 if (mUseScheduler) {
2686 mScheduler->hotplugReceived(mAppConnectionHandle,
2687 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002688 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002689 } else {
2690 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2691 true);
2692 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002693 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002694 if (mUseScheduler) {
2695 mScheduler->hotplugReceived(mAppConnectionHandle,
2696 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002697 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002698 } else {
2699 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2700 true);
2701 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002702 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 }
2704 }
2705 }
2706 }
2707 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002708
2709 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002710}
2711
Mathias Agopian87baae12012-07-31 12:38:26 -07002712void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002713{
Dan Stoza7dde5992015-05-22 09:51:44 -07002714 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002715 mCurrentState.traverseInZOrder([](Layer* layer) {
2716 layer->notifyAvailableFrames();
2717 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002718
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 /*
2720 * Traversal of the children
2721 * (perform the transaction for each of them if needed)
2722 */
2723
Robert Carr720e5062018-07-30 17:45:14 -07002724 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002725 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002726 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002728 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729
2730 const uint32_t flags = layer->doTransaction(0);
2731 if (flags & Layer::eVisibleRegion)
2732 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002733
2734 if (flags & Layer::eInputInfoChanged) {
2735 inputChanged = true;
2736 }
Robert Carr2047fae2016-11-28 14:09:09 -08002737 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 }
2739
2740 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 */
2743
Mathias Agopiane57f2922012-08-09 16:29:12 -07002744 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002746 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002749 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002750 // The transform hint might have changed for some layers
2751 // (either because a display has changed, or because a layer
2752 // as changed).
2753 //
2754 // Walk through all the layers in currentLayers,
2755 // and update their transform hint.
2756 //
2757 // If a layer is visible only on a single display, then that
2758 // display is used to calculate the hint, otherwise we use the
2759 // default display.
2760 //
2761 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2762 // the hint is set before we acquire a buffer from the surface texture.
2763 //
2764 // NOTE: layer transactions have taken place already, so we use their
2765 // drawing state. However, SurfaceFlinger's own transaction has not
2766 // happened yet, so we must use the current state layer list
2767 // (soon to become the drawing state list).
2768 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002769 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002770 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002771 bool first = true;
2772 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002773 // NOTE: we rely on the fact that layers are sorted by
2774 // layerStack first (so we don't have to traverse the list
2775 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002776 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002777 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002778 currentlayerStack = layerStack;
2779 // figure out if this layerstack is mirrored
2780 // (more than one display) if so, pick the default display,
2781 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 hintDisplay = nullptr;
2783 for (const auto& [token, display] : mDisplays) {
2784 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2785 if (hintDisplay) {
2786 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002787 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002788 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002789 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002790 }
2791 }
2792 }
2793 }
Chet Haase91d25932013-04-11 15:24:55 -07002794
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002795 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002796 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2797 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002798
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002799 // could be null when this layer is using a layerStack
2800 // that is not visible on any display. Also can occur at
2801 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002802 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002803 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002804
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002805 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002806 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002807 if (hintDisplay) {
2808 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002809 }
Robert Carr2047fae2016-11-28 14:09:09 -08002810
2811 first = false;
2812 });
Mathias Agopian84300952012-11-21 16:02:13 -08002813 }
2814
2815
Mathias Agopian3559b072012-08-15 13:46:03 -07002816 /*
2817 * Perform our own transaction if needed
2818 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819
2820 if (mLayersAdded) {
2821 mLayersAdded = false;
2822 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002823 mVisibleRegionsDirty = true;
2824 }
2825
2826 // some layers might have been removed, so
2827 // we need to update the regions they're exposing.
2828 if (mLayersRemoved) {
2829 mLayersRemoved = false;
2830 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002833 // this layer is not visible anymore
2834 // TODO: we could traverse the tree from front to back and
2835 // compute the actual visible region
2836 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 Region visibleReg;
2838 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002839 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002840 }
Robert Carr2047fae2016-11-28 14:09:09 -08002841 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 }
2843
2844 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002845
Vishnu Nairde19f852018-12-18 16:11:53 -08002846 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002847 updateInputWindows();
2848 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002849 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002850
Riley Andrews03414a12014-07-01 14:22:59 -07002851 updateCursorAsync();
2852}
2853
Robert Carr720e5062018-07-30 17:45:14 -07002854void SurfaceFlinger::updateInputWindows() {
2855 ATRACE_CALL();
2856
Vishnu Nairde19f852018-12-18 16:11:53 -08002857 if (mInputFlinger == nullptr) {
2858 return;
2859 }
2860
Robert Carr720e5062018-07-30 17:45:14 -07002861 Vector<InputWindowInfo> inputHandles;
2862
2863 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2864 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002865 // When calculating the screen bounds we ignore the transparent region since it may
2866 // result in an unwanted offset.
2867 inputHandles.add(layer->fillInputInfo(
2868 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002869 }
2870 });
2871 mInputFlinger->setInputWindows(inputHandles);
2872}
2873
chaviwfbe5d9c2018-12-26 12:23:37 -08002874void SurfaceFlinger::executeInputWindowCommands() {
2875 if (!mInputFlinger) {
2876 return;
2877 }
2878
2879 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2880 if (transferTouchFocusCommand.fromToken != nullptr &&
2881 transferTouchFocusCommand.toToken != nullptr &&
2882 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2883 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2884 transferTouchFocusCommand.toToken);
2885 }
2886 }
2887
2888 mInputWindowCommands.clear();
2889}
2890
Riley Andrews03414a12014-07-01 14:22:59 -07002891void SurfaceFlinger::updateCursorAsync()
2892{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002894 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002895 continue;
2896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002898 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2899 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002900 }
2901 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002902}
2903
chaviw61626f22018-11-15 16:26:27 -08002904void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2905 if (layer->hasReadyFrame()) {
2906 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2907 if (layer->shouldPresentNow(expectedPresentTime)) {
2908 bool ignored = false;
2909 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2910 }
2911 }
2912 layer->releasePendingBuffer(systemTime());
2913}
2914
Mathias Agopian4fec8732012-06-29 14:12:52 -07002915void SurfaceFlinger::commitTransaction()
2916{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002917 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002919 for (const auto& l : mLayersPendingRemoval) {
2920 recordBufferingStats(l->getName().string(),
2921 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002922
2923 // We need to release the HWC layers when the Layer is removed
2924 // from the current state otherwise the HWC layer just continues
2925 // showing at its last configured state until we eventually
2926 // abandon the buffer queue.
2927 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002928 l->destroyHwcLayersForAllDisplays();
2929 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002930 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002931 }
2932 mLayersPendingRemoval.clear();
2933 }
2934
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002935 // If this transaction is part of a window animation then the next frame
2936 // we composite should be considered an animation as well.
2937 mAnimCompositionPending = mAnimTransactionPending;
2938
Mathias Agopian4fec8732012-06-29 14:12:52 -07002939 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002940 // clear the "changed" flags in current state
2941 mCurrentState.colorMatrixChanged = false;
2942
Robert Carr1f0a16a2016-10-24 16:27:39 -07002943 mDrawingState.traverseInZOrder([](Layer* layer) {
2944 layer->commitChildList();
2945 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002946 mTransactionPending = false;
2947 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002948 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949}
2950
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002951void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2952 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002953 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002955
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 Region aboveOpaqueLayers;
2957 Region aboveCoveredLayers;
2958 Region dirty;
2959
Mathias Agopian87baae12012-07-31 12:38:26 -07002960 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961
Robert Carr2047fae2016-11-28 14:09:09 -08002962 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002963 // start with the whole surface at its current location
2964 const Layer::State& s(layer->getDrawingState());
2965
Jesse Hall01e29052013-02-19 16:13:35 -08002966 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002967 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002968 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002969 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002970
Mathias Agopianab028732010-03-16 16:41:46 -07002971 /*
2972 * opaqueRegion: area of a surface that is fully opaque.
2973 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002975
2976 /*
2977 * visibleRegion: area of a surface that is visible on screen
2978 * and not fully transparent. This is essentially the layer's
2979 * footprint minus the opaque regions above it.
2980 * Areas covered by a translucent surface are considered visible.
2981 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002983
2984 /*
2985 * coveredRegion: area of a surface that is covered by all
2986 * visible regions above it (which includes the translucent areas).
2987 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002989
Jesse Halla8026d22012-09-25 13:25:04 -07002990 /*
2991 * transparentRegion: area of a surface that is hinted to be completely
2992 * transparent. This is only used to tell when the layer has no visible
2993 * non-transparent regions and can be removed from the layer list. It
2994 * does not affect the visibleRegion of this layer or any layers
2995 * beneath it. The hint may not be correct if apps don't respect the
2996 * SurfaceView restrictions (which, sadly, some don't).
2997 */
2998 Region transparentRegion;
2999
Mathias Agopianab028732010-03-16 16:41:46 -07003000
3001 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003002 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003003 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003004 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003005
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003007 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003008 if (!visibleRegion.isEmpty()) {
3009 // Remove the transparent area from the visible region
3010 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003011 if (tr.preserveRects()) {
3012 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003013 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003015 // transformation too complex, can't do the
3016 // transparent region optimization.
3017 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 }
Mathias Agopianab028732010-03-16 16:41:46 -07003019 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020
Mathias Agopianab028732010-03-16 16:41:46 -07003021 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003022 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003023 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003024 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003025 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003026 // the opaque region is the layer's footprint
3027 opaqueRegion = visibleRegion;
3028 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029 }
3030 }
3031
Robert Carre5f4f692018-01-12 13:12:28 -08003032 if (visibleRegion.isEmpty()) {
3033 layer->clearVisibilityRegions();
3034 return;
3035 }
3036
Mathias Agopianab028732010-03-16 16:41:46 -07003037 // Clip the covered region to the visible region
3038 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3039
3040 // Update aboveCoveredLayers for next (lower) layer
3041 aboveCoveredLayers.orSelf(visibleRegion);
3042
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 // subtract the opaque region covered by the layers above us
3044 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045
3046 // compute this layer's dirty region
3047 if (layer->contentDirty) {
3048 // we need to invalidate the whole region
3049 dirty = visibleRegion;
3050 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003051 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 layer->contentDirty = false;
3053 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003054 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003055 * the exposed region consists of two components:
3056 * 1) what's VISIBLE now and was COVERED before
3057 * 2) what's EXPOSED now less what was EXPOSED before
3058 *
3059 * note that (1) is conservative, we start with the whole
3060 * visible region but only keep what used to be covered by
3061 * something -- which mean it may have been exposed.
3062 *
3063 * (2) handles areas that were not covered by anything but got
3064 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003065 */
Mathias Agopianab028732010-03-16 16:41:46 -07003066 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003067 const Region oldVisibleRegion = layer->visibleRegion;
3068 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3070 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 }
3072 dirty.subtractSelf(aboveOpaqueLayers);
3073
3074 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003075 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076
Mathias Agopianab028732010-03-16 16:41:46 -07003077 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003079
Jesse Halla8026d22012-09-25 13:25:04 -07003080 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 layer->setVisibleRegion(visibleRegion);
3082 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003083 layer->setVisibleNonTransparentRegion(
3084 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003085 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086
Mathias Agopian87baae12012-07-31 12:38:26 -07003087 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088}
3089
Chia-I Wuab0c3192017-08-01 11:29:00 -07003090void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003091 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003092 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3093 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003094 }
3095 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003096}
3097
Dan Stoza6b9454d2014-11-07 16:00:59 -08003098bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003100 ALOGV("handlePageFlip");
3101
Brian Andersond6927fb2016-07-23 23:37:30 -07003102 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103
Mathias Agopian4fec8732012-06-29 14:12:52 -07003104 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003106 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003107
3108 // Store the set of layers that need updates. This set must not change as
3109 // buffers are being latched, as this could result in a deadlock.
3110 // Example: Two producers share the same command stream and:
3111 // 1.) Layer 0 is latched
3112 // 2.) Layer 0 gets a new frame
3113 // 2.) Layer 1 gets a new frame
3114 // 3.) Layer 1 is latched.
3115 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3116 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003117 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003118 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003119 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003120 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3121 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003122 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003123 } else {
3124 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003125 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003126 } else {
3127 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003128 }
Robert Carr2047fae2016-11-28 14:09:09 -08003129 });
3130
Lloyd Piquef2c79392018-12-20 16:23:33 -08003131 if (!mLayersWithQueuedFrames.empty()) {
3132 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3133 // writes to Layer current state. See also b/119481871
3134 Mutex::Autolock lock(mStateLock);
3135
3136 for (auto& layer : mLayersWithQueuedFrames) {
3137 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3138 layer->useSurfaceDamage();
3139 invalidateLayerStack(layer, dirty);
3140 if (layer->isBufferLatched()) {
3141 newDataLatched = true;
3142 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003143 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003145
Alec Mouri86770e52018-09-24 22:40:58 +00003146 // Clear the renderengine fence here...
3147 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3148 // clear instead of sp::clear.
3149 getBE().flushFence = Fence::NO_FENCE;
3150
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003151 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003152
Vishnu Nairde19f852018-12-18 16:11:53 -08003153 if (visibleRegions) {
3154 // Update input window info if the layer receives its first buffer.
3155 updateInputWindows();
3156 }
3157
Dan Stoza6b9454d2014-11-07 16:00:59 -08003158 // If we will need to wake up at some time in the future to deal with a
3159 // queued frame that shouldn't be displayed during this vsync period, wake
3160 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003161 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003162 signalLayerUpdate();
3163 }
3164
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003165 // enter boot animation on first buffer latch
3166 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3167 ALOGI("Enter boot animation");
3168 mBootStage = BootStage::BOOTANIMATION;
3169 }
3170
Dan Stoza6b9454d2014-11-07 16:00:59 -08003171 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003172 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173}
3174
Mathias Agopianad456f92011-01-13 17:53:01 -08003175void SurfaceFlinger::invalidateHwcGeometry()
3176{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003177 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003178}
3179
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003180void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003181 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003182 // We only need to actually compose the display if:
3183 // 1) It is being handled by hardware composer, which may need this to
3184 // keep its virtual display state machine in sync, or
3185 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003186 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003187 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003188 return;
3189 }
3190
Dan Stoza9e56aa02015-11-02 13:00:03 -08003191 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003192 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003193
3194 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003195 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196}
3197
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003198bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003199 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003200
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003201 const Region bounds(display->bounds());
3202 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003203 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003204 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003205 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003206
Peiyong Lind3788632018-09-18 16:01:31 -07003207 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003208 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003209
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003210 // Framebuffer will live in this scope for GPU composition.
3211 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3212
Dan Stoza9e56aa02015-11-02 13:00:03 -08003213 if (hasClientComposition) {
3214 ALOGV("hasClientComposition");
3215
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003216 sp<GraphicBuffer> buf = display->dequeueBuffer();
3217
3218 if (buf == nullptr) {
3219 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3220 "client composition for this frame",
3221 display->getDisplayName().c_str());
3222 return false;
3223 }
3224
3225 // Bind the framebuffer in this scope.
3226 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3227 buf->getNativeBuffer());
3228
3229 if (fbo->getStatus() != NO_ERROR) {
3230 ALOGW("Binding buffer for display [%s] failed with status: %d",
3231 display->getDisplayName().c_str(), fbo->getStatus());
3232 return false;
3233 }
3234
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003235 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003236 if (display->hasWideColorGamut()) {
3237 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003238 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003239 getRenderEngine().setOutputDataSpace(outputDataspace);
3240 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003241 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003242
Lloyd Pique441d5042018-10-18 16:49:51 -07003243 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003244 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003245 getHwComposer()
3246 .hasDisplayCapability(displayId,
3247 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003248
Peiyong Lind3788632018-09-18 16:01:31 -07003249 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003250 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3251 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003252 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003253 }
3254
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003255 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003256
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003257 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003259 // when using overlays, we assume a fully transparent framebuffer
3260 // NOTE: we could reduce how much we need to clear, for instance
3261 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003262 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003263 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003264 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003265 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003266 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003267 // we're left with the letterbox region
3268 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003269 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003270
3271 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003272 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003273
Mathias Agopianb9494d52012-04-18 02:28:45 -07003274 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003275 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003276 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003277 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003278 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003279 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003280
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003281 const Rect& bounds = display->getBounds();
3282 const Rect& scissor = display->getScissor();
3283 if (scissor != bounds) {
3284 // scissor doesn't match the screen's dimensions, so we
3285 // need to clear everything outside of it and enable
3286 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003287
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003288 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003289 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003290 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003291 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003292
Mathias Agopian85d751c2012-08-29 16:59:24 -07003293 /*
3294 * and then, render the layers targeted at the framebuffer
3295 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003296
Dan Stoza9e56aa02015-11-02 13:00:03 -08003297 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003298 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003299 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003300 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003301 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003302 displayTransform.transform(layer->visibleRegion)));
3303 ALOGV("Layer: %s", layer->getName().string());
3304 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003305 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003306 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003307 case HWC2::Composition::Cursor:
3308 case HWC2::Composition::Device:
3309 case HWC2::Composition::Sideband:
3310 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003311 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003312 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003313 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003314 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003315 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003316 // never clear the very first layer since we're
3317 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003318 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003319 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003320 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003321 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003322 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003323 if (layer->hasColorTransform()) {
3324 mat4 tmpMatrix;
3325 if (applyColorMatrix) {
3326 tmpMatrix = mDrawingState.colorMatrix;
3327 }
3328 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003329 getRenderEngine().setColorTransform(tmpMatrix);
3330 } else {
3331 getRenderEngine().setColorTransform(colorMatrix);
3332 }
David Sodmanc1498e62018-09-12 14:36:26 -07003333 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003334 break;
3335 }
3336 default:
3337 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003338 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003339 } else {
3340 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003341 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003342 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003343 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003344
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003345 // Perform some cleanup steps if we used client composition.
3346 if (hasClientComposition) {
3347 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003348 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003349 display->finishBuffer();
3350 // Clear out error flags here so that we don't wait until next
3351 // composition to log.
3352 getRenderEngine().checkErrors();
3353 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003354 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355}
3356
Chia-I Wu28e3a252018-09-07 12:05:02 -07003357void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003358 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003359 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003360}
3361
Dan Stoza7d89d062015-04-30 13:29:25 -07003362status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003363 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003364 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003365 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003366 const sp<Layer>& parent,
3367 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003368{
Dan Stoza7d89d062015-04-30 13:29:25 -07003369 // add this layer to the current state list
3370 {
3371 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003372 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003373 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3374 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003375 return NO_MEMORY;
3376 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003377 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003378 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003379 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003380 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003381 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003382 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003383 parent->addChild(lbc);
3384 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003385
Yiwei Zhang243b3782018-05-15 17:40:04 -07003386 if (gbc != nullptr) {
3387 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3388 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3389 mMaxGraphicBufferProducerListSize,
3390 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3391 mGraphicBufferProducerList.size(),
3392 mMaxGraphicBufferProducerListSize, mNumLayers);
3393 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003394 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003395 }
3396
Mathias Agopian96f08192010-06-02 23:28:45 -07003397 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003398 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003399
Dan Stoza7d89d062015-04-30 13:29:25 -07003400 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003401}
3402
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003403uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003404 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003405}
3406
Mathias Agopian3f844832013-08-07 21:24:32 -07003407uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003408 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409}
3410
Mathias Agopian3f844832013-08-07 21:24:32 -07003411uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003412 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003413}
3414
3415uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003416 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003417 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003418 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003419 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003420 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003421 }
3422 return old;
3423}
3424
Marissa Wall713b63f2018-10-17 15:42:43 -07003425bool SurfaceFlinger::flushTransactionQueues() {
3426 Mutex::Autolock _l(mStateLock);
3427 auto it = mTransactionQueues.begin();
3428 while (it != mTransactionQueues.end()) {
3429 auto& [applyToken, transactionQueue] = *it;
3430
3431 while (!transactionQueue.empty()) {
3432 const auto& [states, displays, flags] = transactionQueue.front();
3433 if (composerStateContainsUnsignaledFences(states)) {
3434 break;
3435 }
chaviw273171b2018-12-26 11:46:30 -08003436 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003437 transactionQueue.pop();
3438 }
3439
3440 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3441 }
3442 return mTransactionQueues.empty();
3443}
3444
chaviwca27f252018-02-06 16:46:39 -08003445bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3446 for (const ComposerState& state : states) {
3447 // Here we need to check that the interface we're given is indeed
3448 // one of our own. A malicious client could give us a nullptr
3449 // IInterface, or one of its own or even one of our own but a
3450 // different type. All these situations would cause us to crash.
3451 if (state.client == nullptr) {
3452 return true;
3453 }
3454
3455 sp<IBinder> binder = IInterface::asBinder(state.client);
3456 if (binder == nullptr) {
3457 return true;
3458 }
3459
3460 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3461 return true;
3462 }
3463 }
3464 return false;
3465}
3466
Marissa Wall713b63f2018-10-17 15:42:43 -07003467bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3468 for (const ComposerState& state : states) {
3469 const layer_state_t& s = state.state;
3470 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3471 continue;
3472 }
3473 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3474 return true;
3475 }
3476 }
3477 return false;
3478}
3479
3480void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3481 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003482 const sp<IBinder>& applyToken,
3483 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003484 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003485 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486
chaviwca27f252018-02-06 16:46:39 -08003487 if (containsAnyInvalidClientState(states)) {
3488 return;
3489 }
3490
Marissa Wall713b63f2018-10-17 15:42:43 -07003491 // If its TransactionQueue already has a pending TransactionState or if it is pending
3492 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3493 composerStateContainsUnsignaledFences(states)) {
3494 mTransactionQueues[applyToken].emplace(states, displays, flags);
3495 setTransactionFlags(eTransactionNeeded);
3496 return;
3497 }
3498
chaviw273171b2018-12-26 11:46:30 -08003499 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003500}
3501
3502void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003503 const Vector<DisplayState>& displays, uint32_t flags,
3504 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003505 uint32_t transactionFlags = 0;
3506
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003507 if (flags & eAnimation) {
3508 // For window updates that are part of an animation we must wait for
3509 // previous animation "frames" to be handled.
3510 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003511 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003512 if (CC_UNLIKELY(err != NO_ERROR)) {
3513 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003514 // caller after a few seconds.
3515 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3516 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003517 mAnimTransactionPending = false;
3518 break;
3519 }
3520 }
3521 }
3522
chaviwca27f252018-02-06 16:46:39 -08003523 for (const DisplayState& display : displays) {
3524 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003525 }
3526
Marissa Walle2ffb422018-10-12 11:33:52 -07003527 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003528 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003529 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003530 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003531 // If the state doesn't require a traversal and there are callbacks, send them now
3532 if (!(clientStateFlags & eTraversalNeeded)) {
3533 mTransactionCompletedThread.sendCallbacks();
3534 }
3535 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003536
chaviw273171b2018-12-26 11:46:30 -08003537 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3538
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003539 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3540 // anyway. This can be used as a flush mechanism for previous async transactions.
3541 // Empty animation transaction can be used to simulate back-pressure, so also force a
3542 // transaction for empty animation transactions.
3543 if (transactionFlags == 0 &&
3544 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003545 transactionFlags = eTransactionNeeded;
3546 }
3547
Mathias Agopian386aa982011-11-07 21:58:03 -08003548 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003549 if (mInterceptor->isEnabled()) {
3550 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003551 }
Irvel468051e2016-06-13 16:44:44 -07003552
Mathias Agopian386aa982011-11-07 21:58:03 -08003553 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003554 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3555 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003556 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003557
3558 // if this is a synchronous transaction, wait for it to take effect
3559 // before returning.
3560 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003561 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003562 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003563 if (flags & eAnimation) {
3564 mAnimTransactionPending = true;
3565 }
3566 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003567 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3568 if (CC_UNLIKELY(err != NO_ERROR)) {
3569 // just in case something goes wrong in SF, return to the
3570 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003571 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3572 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003573 break;
3574 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003575 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 }
3577}
3578
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003579uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3580 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3581 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003582
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003584 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3585
3586 const uint32_t what = s.what;
3587 if (what & DisplayState::eSurfaceChanged) {
3588 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3589 state.surface = s.surface;
3590 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003591 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003592 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003593 if (what & DisplayState::eLayerStackChanged) {
3594 if (state.layerStack != s.layerStack) {
3595 state.layerStack = s.layerStack;
3596 flags |= eDisplayTransactionNeeded;
3597 }
3598 }
3599 if (what & DisplayState::eDisplayProjectionChanged) {
3600 if (state.orientation != s.orientation) {
3601 state.orientation = s.orientation;
3602 flags |= eDisplayTransactionNeeded;
3603 }
3604 if (state.frame != s.frame) {
3605 state.frame = s.frame;
3606 flags |= eDisplayTransactionNeeded;
3607 }
3608 if (state.viewport != s.viewport) {
3609 state.viewport = s.viewport;
3610 flags |= eDisplayTransactionNeeded;
3611 }
3612 }
3613 if (what & DisplayState::eDisplaySizeChanged) {
3614 if (state.width != s.width) {
3615 state.width = s.width;
3616 flags |= eDisplayTransactionNeeded;
3617 }
3618 if (state.height != s.height) {
3619 state.height = s.height;
3620 flags |= eDisplayTransactionNeeded;
3621 }
3622 }
3623
Mathias Agopiane57f2922012-08-09 16:29:12 -07003624 return flags;
3625}
3626
Robert Carrd4ae7f32018-06-07 16:10:57 -07003627bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3628 IPCThreadState* ipc = IPCThreadState::self();
3629 const int pid = ipc->getCallingPid();
3630 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003631 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003632 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003633 return false;
3634 }
3635 return true;
3636}
3637
chaviwca27f252018-02-06 16:46:39 -08003638uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3639 const layer_state_t& s = composerState.state;
3640 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3641
Mathias Agopian13127d82013-03-05 17:47:11 -08003642 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003643 if (layer == nullptr) {
3644 return 0;
3645 }
3646
chaviw8b3871a2017-11-01 17:41:01 -07003647 uint32_t flags = 0;
3648
Garfield Tan8a3083e2018-12-03 13:21:07 -08003649 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003650 bool geometryAppliesWithResize =
3651 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003652
3653 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3654 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003655 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003656 layer->pushPendingState();
3657 }
3658
chaviw8b3871a2017-11-01 17:41:01 -07003659 if (what & layer_state_t::ePositionChanged) {
3660 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3661 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 }
3664 if (what & layer_state_t::eLayerChanged) {
3665 // NOTE: index needs to be calculated before we update the state
3666 const auto& p = layer->getParent();
3667 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003668 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003669 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003670 mCurrentState.layersSortedByZ.removeAt(idx);
3671 mCurrentState.layersSortedByZ.add(layer);
3672 // we need traversal (state changed)
3673 // AND transaction (list changed)
3674 flags |= eTransactionNeeded|eTraversalNeeded;
3675 }
chaviw8b3871a2017-11-01 17:41:01 -07003676 } else {
3677 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003678 flags |= eTransactionNeeded|eTraversalNeeded;
3679 }
3680 }
chaviw8b3871a2017-11-01 17:41:01 -07003681 }
3682 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003683 // NOTE: index needs to be calculated before we update the state
3684 const auto& p = layer->getParent();
3685 if (p == nullptr) {
3686 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3687 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3688 mCurrentState.layersSortedByZ.removeAt(idx);
3689 mCurrentState.layersSortedByZ.add(layer);
3690 // we need traversal (state changed)
3691 // AND transaction (list changed)
3692 flags |= eTransactionNeeded|eTraversalNeeded;
3693 }
3694 } else {
3695 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3696 flags |= eTransactionNeeded|eTraversalNeeded;
3697 }
chaviw8b3871a2017-11-01 17:41:01 -07003698 }
3699 }
3700 if (what & layer_state_t::eSizeChanged) {
3701 if (layer->setSize(s.w, s.h)) {
3702 flags |= eTraversalNeeded;
3703 }
3704 }
3705 if (what & layer_state_t::eAlphaChanged) {
3706 if (layer->setAlpha(s.alpha))
3707 flags |= eTraversalNeeded;
3708 }
3709 if (what & layer_state_t::eColorChanged) {
3710 if (layer->setColor(s.color))
3711 flags |= eTraversalNeeded;
3712 }
Peiyong Lind3788632018-09-18 16:01:31 -07003713 if (what & layer_state_t::eColorTransformChanged) {
3714 if (layer->setColorTransform(s.colorTransform)) {
3715 flags |= eTraversalNeeded;
3716 }
3717 }
chaviw8b3871a2017-11-01 17:41:01 -07003718 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003719 // TODO: b/109894387
3720 //
3721 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3722 // rotation. To see the problem observe that if we have a square parent, and a child
3723 // of the same size, then we rotate the child 45 degrees around it's center, the child
3724 // must now be cropped to a non rectangular 8 sided region.
3725 //
3726 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3727 // private API, and the WindowManager only uses rotation in one case, which is on a top
3728 // level layer in which cropping is not an issue.
3729 //
3730 // However given that abuse of rotation matrices could lead to surfaces extending outside
3731 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3732 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3733 // transformations.
3734 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003735 flags |= eTraversalNeeded;
3736 }
3737 if (what & layer_state_t::eTransparentRegionChanged) {
3738 if (layer->setTransparentRegionHint(s.transparentRegion))
3739 flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eFlagsChanged) {
3742 if (layer->setFlags(s.flags, s.mask))
3743 flags |= eTraversalNeeded;
3744 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003745 if (what & layer_state_t::eCropChanged_legacy) {
3746 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003747 flags |= eTraversalNeeded;
3748 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003749 if (what & layer_state_t::eCornerRadiusChanged) {
3750 if (layer->setCornerRadius(s.cornerRadius))
3751 flags |= eTraversalNeeded;
3752 }
chaviw8b3871a2017-11-01 17:41:01 -07003753 if (what & layer_state_t::eLayerStackChanged) {
3754 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3755 // We only allow setting layer stacks for top level layers,
3756 // everything else inherits layer stack from its parent.
3757 if (layer->hasParent()) {
3758 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3759 layer->getName().string());
3760 } else if (idx < 0) {
3761 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3762 "that also does not appear in the top level layer list. Something"
3763 " has gone wrong.", layer->getName().string());
3764 } else if (layer->setLayerStack(s.layerStack)) {
3765 mCurrentState.layersSortedByZ.removeAt(idx);
3766 mCurrentState.layersSortedByZ.add(layer);
3767 // we need traversal (state changed)
3768 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003769 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003770 }
3771 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003772 if (what & layer_state_t::eDeferTransaction_legacy) {
3773 if (s.barrierHandle_legacy != nullptr) {
3774 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3775 } else if (s.barrierGbp_legacy != nullptr) {
3776 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003777 if (authenticateSurfaceTextureLocked(gbp)) {
3778 const auto& otherLayer =
3779 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003780 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003781 } else {
3782 ALOGE("Attempt to defer transaction to to an"
3783 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003784 }
3785 }
chaviw8b3871a2017-11-01 17:41:01 -07003786 // We don't trigger a traversal here because if no other state is
3787 // changed, we don't want this to cause any more work
3788 }
3789 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003790 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003791 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003792 if (!hadParent) {
3793 mCurrentState.layersSortedByZ.remove(layer);
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003796 }
chaviw8b3871a2017-11-01 17:41:01 -07003797 }
3798 if (what & layer_state_t::eReparentChildren) {
3799 if (layer->reparentChildren(s.reparentHandle)) {
3800 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003801 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003802 }
chaviw8b3871a2017-11-01 17:41:01 -07003803 if (what & layer_state_t::eDetachChildren) {
3804 layer->detachChildren();
3805 }
3806 if (what & layer_state_t::eOverrideScalingModeChanged) {
3807 layer->setOverrideScalingMode(s.overrideScalingMode);
3808 // We don't trigger a traversal here because if no other state is
3809 // changed, we don't want this to cause any more work
3810 }
Marissa Wall61c58622018-07-18 10:12:20 -07003811 if (what & layer_state_t::eTransformChanged) {
3812 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3813 }
3814 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3815 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3816 flags |= eTraversalNeeded;
3817 }
3818 if (what & layer_state_t::eCropChanged) {
3819 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3820 }
Marissa Wall861616d2018-10-22 12:52:23 -07003821 if (what & layer_state_t::eFrameChanged) {
3822 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3823 }
Marissa Wall61c58622018-07-18 10:12:20 -07003824 if (what & layer_state_t::eBufferChanged) {
3825 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3826 }
3827 if (what & layer_state_t::eAcquireFenceChanged) {
3828 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3829 }
3830 if (what & layer_state_t::eDataspaceChanged) {
3831 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3832 }
3833 if (what & layer_state_t::eHdrMetadataChanged) {
3834 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3835 }
3836 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3837 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3838 }
3839 if (what & layer_state_t::eApiChanged) {
3840 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3841 }
3842 if (what & layer_state_t::eSidebandStreamChanged) {
3843 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3844 }
Robert Carr720e5062018-07-30 17:45:14 -07003845 if (what & layer_state_t::eInputInfoChanged) {
3846 layer->setInputInfo(s.inputInfo);
3847 flags |= eTraversalNeeded;
3848 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003849 std::vector<sp<CallbackHandle>> callbackHandles;
3850 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3851 mTransactionCompletedThread.run();
3852 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3853 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3854 }
3855 }
3856 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3857 // Do not put anything that updates layer state or modifies flags after
3858 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003859 return flags;
3860}
3861
chaviw273171b2018-12-26 11:46:30 -08003862uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3863 uint32_t flags = 0;
3864 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3865 flags |= eTraversalNeeded;
3866 }
3867
3868 mInputWindowCommands.merge(inputWindowCommands);
3869 return flags;
3870}
3871
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003872status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003873 const String8& name,
3874 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003875 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003876 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003877 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003879 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003880 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003881 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003882 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003883 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003884
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003885 status_t result = NO_ERROR;
3886
3887 sp<Layer> layer;
3888
Cody Northropbc755282017-03-31 12:00:08 -06003889 String8 uniqueName = getUniqueLayerName(name);
3890
Mathias Agopian3165cc22012-08-08 19:42:09 -07003891 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003892 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003893 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3894 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003895
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003897 case ISurfaceComposerClient::eFXSurfaceBufferState:
3898 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3899 break;
chaviw13fdc492017-06-27 12:40:18 -07003900 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003901 // check if buffer size is set for color layer.
3902 if (w > 0 || h > 0) {
3903 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3904 int(w), int(h));
3905 return BAD_VALUE;
3906 }
3907
chaviw13fdc492017-06-27 12:40:18 -07003908 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003909 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003910 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003911 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003912 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003913 // check if buffer size is set for container layer.
3914 if (w > 0 || h > 0) {
3915 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3916 int(w), int(h));
3917 return BAD_VALUE;
3918 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003919 result = createContainerLayer(client,
3920 uniqueName, w, h, flags,
3921 handle, &layer);
3922 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003923 default:
3924 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 break;
3926 }
3927
Dan Stoza7d89d062015-04-30 13:29:25 -07003928 if (result != NO_ERROR) {
3929 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003930 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003931
Chia-I Wuab0c3192017-08-01 11:29:00 -07003932 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3933 // TODO b/64227542
3934 if (windowType == 441731) {
3935 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3936 layer->setPrimaryDisplayOnly();
3937 }
3938
Albert Chaulk479c60c2017-01-27 14:21:34 -05003939 layer->setInfo(windowType, ownerUid);
3940
Robert Carrb89ea9d2018-12-10 13:01:14 -08003941 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
3942 result = addClientLayer(client, *handle, *gbp, layer, *parent,
3943 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003944 if (result != NO_ERROR) {
3945 return result;
3946 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003947 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003948
3949 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003950 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951}
3952
Cody Northropbc755282017-03-31 12:00:08 -06003953String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3954{
3955 bool matchFound = true;
3956 uint32_t dupeCounter = 0;
3957
3958 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3959 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3960
Dan Stoza436ccf32018-06-21 12:10:12 -07003961 // Grab the state lock since we're accessing mCurrentState
3962 Mutex::Autolock lock(mStateLock);
3963
Cody Northropbc755282017-03-31 12:00:08 -06003964 // Loop over layers until we're sure there is no matching name
3965 while (matchFound) {
3966 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003967 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003968 if (layer->getName() == uniqueName) {
3969 matchFound = true;
3970 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3971 }
3972 });
3973 }
3974
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003975 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3976 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003977
3978 return uniqueName;
3979}
3980
Marissa Wallfd668622018-05-10 10:21:13 -07003981status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3982 uint32_t w, uint32_t h, uint32_t flags,
3983 PixelFormat& format, sp<IBinder>* handle,
3984 sp<IGraphicBufferProducer>* gbp,
3985 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003987 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 case PIXEL_FORMAT_TRANSPARENT:
3989 case PIXEL_FORMAT_TRANSLUCENT:
3990 format = PIXEL_FORMAT_RGBA_8888;
3991 break;
3992 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003993 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 break;
3995 }
3996
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003997 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003998 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003999 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004000 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004001 *handle = layer->getHandle();
4002 *gbp = layer->getProducer();
4003 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004005
Marissa Wallfd668622018-05-10 10:21:13 -07004006 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004007 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008}
4009
Marissa Wall61c58622018-07-18 10:12:20 -07004010status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4011 uint32_t w, uint32_t h, uint32_t flags,
4012 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004013 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004014 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004015 *handle = layer->getHandle();
4016 *outLayer = layer;
4017
4018 return NO_ERROR;
4019}
4020
chaviw13fdc492017-06-27 12:40:18 -07004021status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004022 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004023 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004025 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004026 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004027 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004028}
4029
Robert Carr6b3f6c52018-08-13 13:05:17 -07004030status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4031 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4032 sp<IBinder>* handle, sp<Layer>* outLayer)
4033{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004034 *outLayer =
4035 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004036 *handle = (*outLayer)->getHandle();
4037 return NO_ERROR;
4038}
4039
4040
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004041void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004042 mLayersPendingRemoval.add(layer);
4043 mLayersRemoved = true;
4044 setTransactionFlags(eTransactionNeeded);
4045}
4046
Robert Carr695d5282018-12-18 15:27:58 -08004047void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004048{
Robert Carr2e102c92018-10-23 12:11:15 -07004049 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004050 // If a layer has a parent, we allow it to out-live it's handle
4051 // with the idea that the parent holds a reference and will eventually
4052 // be cleaned up. However no one cleans up the top-level so we do so
4053 // here.
4054 if (layer->getParent() == nullptr) {
4055 mCurrentState.layersSortedByZ.remove(layer);
4056 }
4057 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004058 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004059}
4060
Mathias Agopianb60314a2012-04-10 22:09:54 -07004061// ---------------------------------------------------------------------------
4062
Andy McFadden13a082e2012-08-24 10:16:42 -07004063void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004064 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004065 if (!displayToken) return;
4066
Jesse Hall01e29052013-02-19 16:13:35 -08004067 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004068 Vector<ComposerState> state;
4069 Vector<DisplayState> displays;
4070 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004071 d.what = DisplayState::eDisplayProjectionChanged |
4072 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004073 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004074 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004075 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004076 d.frame.makeInvalid();
4077 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004078 d.width = 0;
4079 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004080 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004081 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004082
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004083 const auto display = getDisplayDevice(displayToken);
4084 if (!display) return;
4085
Dominik Laskowskie9774092018-12-11 10:04:24 -08004086 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004087
Dominik Laskowski075d3172018-05-24 15:50:06 -07004088 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004089 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004090 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004091
Brian Andersond0010582017-03-07 13:20:31 -08004092 // Use phase of 0 since phase is not known.
4093 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004094 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4095 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004096}
4097
4098void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004099 // Async since we may be called from the main thread.
4100 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004101}
4102
Dominik Laskowskie9774092018-12-11 10:04:24 -08004103void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 if (display->isVirtual()) {
4105 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004106 return;
4107 }
4108
Dominik Laskowski075d3172018-05-24 15:50:06 -07004109 const auto displayId = display->getId();
4110 LOG_ALWAYS_FATAL_IF(!displayId);
4111
Dominik Laskowski34157762018-10-31 13:07:19 -07004112 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004113
4114 int currentMode = display->getPowerMode();
4115 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004116 return;
4117 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004119 display->setPowerMode(mode);
4120
Lloyd Pique4dccc412018-01-22 17:21:36 -08004121 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004122 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004123 }
4124
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004125 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004126 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004128 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004129 if (mUseScheduler) {
4130 mScheduler->onScreenAcquired(mAppConnectionHandle);
4131 } else {
4132 mEventThread->onScreenAcquired();
4133 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004134 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004135 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004137 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004138 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004139 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004140
4141 struct sched_param param = {0};
4142 param.sched_priority = 1;
4143 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4144 ALOGW("Couldn't set SCHED_FIFO on display on");
4145 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004146 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004147 // Turn off the display
4148 struct sched_param param = {0};
4149 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4150 ALOGW("Couldn't set SCHED_OTHER on display off");
4151 }
4152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004153 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004154 if (mUseScheduler) {
4155 mScheduler->disableHardwareVsync(true);
4156 } else {
4157 disableHardwareVsync(true); // also cancels any in-progress resync
4158 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004159 if (mUseScheduler) {
4160 mScheduler->onScreenReleased(mAppConnectionHandle);
4161 } else {
4162 mEventThread->onScreenReleased();
4163 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004164 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004165
Dominik Laskowski075d3172018-05-24 15:50:06 -07004166 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004167 mVisibleRegionsDirty = true;
4168 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004169 } else if (mode == HWC_POWER_MODE_DOZE ||
4170 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004171 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004172 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004173 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004174 if (mUseScheduler) {
4175 mScheduler->onScreenAcquired(mAppConnectionHandle);
4176 } else {
4177 mEventThread->onScreenAcquired();
4178 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004179 resyncToHardwareVsync(true);
4180 }
4181 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4182 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004183 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004184 if (mUseScheduler) {
4185 mScheduler->disableHardwareVsync(true);
4186 } else {
4187 disableHardwareVsync(true); // also cancels any in-progress resync
4188 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004189 if (mUseScheduler) {
4190 mScheduler->onScreenReleased(mAppConnectionHandle);
4191 } else {
4192 mEventThread->onScreenReleased();
4193 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004194 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004195 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004196 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004197 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004198 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004199 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004200
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004201 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004202 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004203 }
4204
Dominik Laskowski34157762018-10-31 13:07:19 -07004205 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004206}
4207
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004209 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004210 const auto display = getDisplayDevice(displayToken);
4211 if (!display) {
4212 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4213 displayToken.get());
4214 } else if (display->isVirtual()) {
4215 ALOGW("Attempt to set power mode %d for virtual display", mode);
4216 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004217 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004218 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004219 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004220}
4221
4222// ---------------------------------------------------------------------------
4223
Lloyd Pique755e3192018-01-31 16:46:15 -08004224status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4225 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004226 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004227
Mathias Agopianbd115332013-04-18 16:41:04 -07004228 IPCThreadState* ipc = IPCThreadState::self();
4229 const int pid = ipc->getCallingPid();
4230 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004231
Mathias Agopianbd115332013-04-18 16:41:04 -07004232 if ((uid != AID_SHELL) &&
4233 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004234 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4235 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004236 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004237 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004238 // (this would indicate SF is stuck, but we want to be able to
4239 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004240 status_t err = mStateLock.timedLock(s2ns(1));
4241 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004242 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004243 StringAppendF(&result,
4244 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4245 "(no locks held)\n",
4246 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004247 }
4248
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249 bool dumpAll = true;
4250 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004251 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004252
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004253 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004254 if ((index < numArgs) &&
4255 (args[index] == String16("--list"))) {
4256 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004258 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004259 }
4260
4261 if ((index < numArgs) &&
4262 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004264 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004265 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004267
4268 if ((index < numArgs) &&
4269 (args[index] == String16("--latency-clear"))) {
4270 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004271 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004272 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004273 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004274
4275 if ((index < numArgs) &&
4276 (args[index] == String16("--dispsync"))) {
4277 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004278 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004279 dumpAll = false;
4280 }
Dan Stozab90cf072015-03-05 11:05:59 -08004281
4282 if ((index < numArgs) &&
4283 (args[index] == String16("--static-screen"))) {
4284 index++;
4285 dumpStaticScreenStats(result);
4286 dumpAll = false;
4287 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004288
4289 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004290 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004291 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004292 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004293 dumpAll = false;
4294 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004295
4296 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4297 index++;
4298 dumpWideColorInfo(result);
4299 dumpAll = false;
4300 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004301
4302 if ((index < numArgs) &&
4303 (args[index] == String16("--enable-layer-stats"))) {
4304 index++;
4305 mLayerStats.enable();
4306 dumpAll = false;
4307 }
4308
4309 if ((index < numArgs) &&
4310 (args[index] == String16("--disable-layer-stats"))) {
4311 index++;
4312 mLayerStats.disable();
4313 dumpAll = false;
4314 }
4315
4316 if ((index < numArgs) &&
4317 (args[index] == String16("--clear-layer-stats"))) {
4318 index++;
4319 mLayerStats.clear();
4320 dumpAll = false;
4321 }
4322
4323 if ((index < numArgs) &&
4324 (args[index] == String16("--dump-layer-stats"))) {
4325 index++;
4326 mLayerStats.dump(result);
4327 dumpAll = false;
4328 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329
4330 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004331 (args[index] == String16("--frame-composition"))) {
4332 index++;
4333 dumpFrameCompositionInfo(result);
4334 dumpAll = false;
4335 }
4336
4337 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004338 (args[index] == String16("--display-identification"))) {
4339 index++;
4340 dumpDisplayIdentificationData(result);
4341 dumpAll = false;
4342 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004343
4344 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4345 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004346 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004347 dumpAll = false;
4348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004349 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004350
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004352 if (asProto) {
4353 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4354 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4355 } else {
4356 dumpAllLocked(args, index, result);
4357 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004358 }
4359
Mathias Agopian9795c422009-08-26 16:36:26 -07004360 if (locked) {
4361 mStateLock.unlock();
4362 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 return NO_ERROR;
4366}
4367
Yiwei Zhang5434a782018-12-05 18:06:32 -08004368void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4369 std::string& result) const {
4370 mCurrentState.traverseInZOrder(
4371 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004372}
4373
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004374void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376 String8 name;
4377 if (index < args.size()) {
4378 name = String8(args[index]);
4379 index++;
4380 }
4381
Dominik Laskowski075d3172018-05-24 15:50:06 -07004382 if (const auto displayId = getInternalDisplayId();
4383 displayId && getHwComposer().isConnected(*displayId)) {
4384 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004385 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004386 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004387 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004388
4389 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004390 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004391 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004392 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004393 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004394 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004395 }
Robert Carr2047fae2016-11-28 14:09:09 -08004396 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397 }
4398}
4399
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004400void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004401 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004402 String8 name;
4403 if (index < args.size()) {
4404 name = String8(args[index]);
4405 index++;
4406 }
4407
Robert Carr2047fae2016-11-28 14:09:09 -08004408 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004409 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004410 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004411 }
Robert Carr2047fae2016-11-28 14:09:09 -08004412 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004413
Svetoslavd85084b2014-03-20 10:28:31 -07004414 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004415}
4416
Jamie Gennis6547ff42013-07-16 20:12:42 -07004417// This should only be called from the main thread. Otherwise it would need
4418// the lock and should use mCurrentState rather than mDrawingState.
4419void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004420 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004421 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004422 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004423
4424 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4425}
4426
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004428 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004429
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004430 if (isLayerTripleBufferingDisabled())
4431 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004432
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4434 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4435 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4436 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4437 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4438 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004439 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004440}
4441
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4443 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004444 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4445 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004446 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004447 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004449 }
David Sodman4a36e932017-11-07 14:29:47 -08004450 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004451 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004452 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4454 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004455}
4456
Dan Stozae77c7662016-05-13 11:37:28 -07004457void SurfaceFlinger::recordBufferingStats(const char* layerName,
4458 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004459 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4460 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004461 for (const auto& segment : history) {
4462 if (!segment.usedThirdBuffer) {
4463 stats.twoBufferTime += segment.totalTime;
4464 }
4465 if (segment.occupancyAverage < 1.0f) {
4466 stats.doubleBufferedTime += segment.totalTime;
4467 } else if (segment.occupancyAverage < 2.0f) {
4468 stats.tripleBufferedTime += segment.totalTime;
4469 }
4470 ++stats.numSegments;
4471 stats.totalTime += segment.totalTime;
4472 }
4473}
4474
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4476 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004477
4478 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4479 const size_t count = currentLayers.size();
4480 for (size_t i=0 ; i<count ; i++) {
4481 currentLayers[i]->dumpFrameEvents(result);
4482 }
4483}
4484
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004486 result.append("Buffering stats:\n");
4487 result.append(" [Layer name] <Active time> <Two buffer> "
4488 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004489 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004490 typedef std::tuple<std::string, float, float, float> BufferTuple;
4491 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004492 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004493 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004494 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004495 if (stats.numSegments == 0) {
4496 continue;
4497 }
4498 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4499 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4500 stats.totalTime;
4501 float doubleBufferRatio = static_cast<float>(
4502 stats.doubleBufferedTime) / stats.totalTime;
4503 float tripleBufferRatio = static_cast<float>(
4504 stats.tripleBufferedTime) / stats.totalTime;
4505 sorted.insert({activeTime, {name, twoBufferRatio,
4506 doubleBufferRatio, tripleBufferRatio}});
4507 }
4508 for (const auto& sortedPair : sorted) {
4509 float activeTime = sortedPair.first;
4510 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4512 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004513 }
4514 result.append("\n");
4515}
4516
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004518 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004519 const auto displayId = display->getId();
4520 if (!displayId) {
4521 continue;
4522 }
4523 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004524 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004525 continue;
4526 }
4527
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 StringAppendF(&result,
4529 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4530 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004531 uint8_t port;
4532 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004533 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004534 result.append("no identification data\n");
4535 continue;
4536 }
4537
4538 if (!isEdid(data)) {
4539 result.append("unknown identification data: ");
4540 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004542 }
4543 result.append("\n");
4544 continue;
4545 }
4546
4547 const auto edid = parseEdid(data);
4548 if (!edid) {
4549 result.append("invalid EDID: ");
4550 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004552 }
4553 result.append("\n");
4554 continue;
4555 }
4556
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004558 result.append(edid->displayName.data(), edid->displayName.length());
4559 result.append("\"\n");
4560 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561}
4562
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4564 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4565 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4566 StringAppendF(&result, "DisplayColorSetting: %s\n",
4567 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004568
4569 // TODO: print out if wide-color mode is active or not
4570
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004571 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004572 const auto displayId = display->getId();
4573 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004574 continue;
4575 }
4576
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004578 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004579 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004581 }
4582
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004583 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584 StringAppendF(&result, " Current color mode: %s (%d)\n",
4585 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004586 }
4587 result.append("\n");
4588}
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004591 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004592 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4593 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004594 continue;
4595 }
4596
Dominik Laskowski05275f12018-11-01 15:03:24 -07004597 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4599 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004600 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 compositionInfo.dump(result, nullptr);
4602 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004603 }
4604 }
David Sodman7e4ae112018-02-09 15:02:28 -08004605}
4606
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004607LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004608 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004609 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4610 const State& state = useDrawing ? mDrawingState : mCurrentState;
4611 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004612 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004613 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004614 });
4615
4616 return layersProto;
4617}
4618
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004619LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004620 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004621
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004622 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004623 resolution->set_w(display.getWidth());
4624 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004625
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004626 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4627 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4628 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004629
Dominik Laskowski075d3172018-05-24 15:50:06 -07004630 const auto displayId = display.getId();
4631 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004632 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004633 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004634 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004635 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004636 }
4637 });
4638
4639 return layersProto;
4640}
4641
Mathias Agopian74d211a2013-04-22 16:55:35 +02004642void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004644 bool colorize = false;
4645 if (index < args.size()
4646 && (args[index] == String16("--color"))) {
4647 colorize = true;
4648 index++;
4649 }
4650
4651 Colorizer colorizer(colorize);
4652
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 // figure out if we're stuck somewhere
4654 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004655 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4657
4658 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004659 * Dump library configuration.
4660 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661
4662 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004663 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004664 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004665 appendSfConfigString(result);
4666 appendUiConfigString(result);
4667 appendGuiConfigString(result);
4668 result.append("\n");
4669
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004670 result.append("\nDisplay identification data:\n");
4671 dumpDisplayIdentificationData(result);
4672
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004673 result.append("\nWide-Color information:\n");
4674 dumpWideColorInfo(result);
4675
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004677 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004679 result.append(SyncFeatures::getInstance().toString());
4680 result.append("\n");
4681
Andy McFadden41d67d72014-04-25 16:58:34 -07004682 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004683 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004684 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004685
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004686 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4687 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 if (const auto displayId = getInternalDisplayId();
4689 displayId && getHwComposer().isConnected(*displayId)) {
4690 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004691 StringAppendF(&result,
4692 "Display %s: app phase %" PRId64 " ns, "
4693 "sf phase %" PRId64 " ns, "
4694 "early app phase %" PRId64 " ns, "
4695 "early sf phase %" PRId64 " ns, "
4696 "early app gl phase %" PRId64 " ns, "
4697 "early sf gl phase %" PRId64 " ns, "
4698 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4699 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4700 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4701 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004702 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004703 result.append("\n");
4704
Dan Stozab90cf072015-03-05 11:05:59 -08004705 // Dump static screen stats
4706 result.append("\n");
4707 dumpStaticScreenStats(result);
4708 result.append("\n");
4709
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004711
Dan Stozae77c7662016-05-13 11:37:28 -07004712 dumpBufferingStats(result);
4713
Andy McFadden4803b742012-09-24 19:07:20 -07004714 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715 * Dump the visible layer list
4716 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4719 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4720 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004721 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004722
Chia-I Wu2f884132018-09-13 15:17:58 -07004723 {
4724 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4725 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004727 result.append("\n");
4728 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729
David Sodman7e4ae112018-02-09 15:02:28 -08004730 result.append("\nFrame-Composition information:\n");
4731 dumpFrameCompositionInfo(result);
4732 result.append("\n");
4733
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004735 * Dump Display state
4736 */
4737
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004738 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004739 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004740 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004741 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004742 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004743 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004744 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004745
4746 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004747 * Dump SurfaceFlinger global state
4748 */
4749
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004751 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004752 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004753
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004754 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004755
Dominik Laskowski075d3172018-05-24 15:50:06 -07004756 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004757 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4759 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004760 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result,
4762 " transaction-flags : %08x\n"
4763 " gpu_to_cpu_unsupported : %d\n",
4764 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004765
Dominik Laskowski075d3172018-05-24 15:50:06 -07004766 if (const auto displayId = getInternalDisplayId();
4767 displayId && getHwComposer().isConnected(*displayId)) {
4768 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004769 StringAppendF(&result,
4770 " refresh-rate : %f fps\n"
4771 " x-dpi : %f\n"
4772 " y-dpi : %f\n",
4773 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4774 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004775 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004776
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780 /*
4781 * VSYNC state
4782 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004783 if (mUseScheduler) {
4784 mScheduler->dump(mAppConnectionHandle, result);
4785 } else {
4786 mEventThread->dump(result);
4787 }
Dan Stozae22aec72016-08-01 13:20:59 -07004788 result.append("\n");
4789
4790 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004791 * Tracing state
4792 */
4793 mTracing.dump(result);
4794 result.append("\n");
4795
4796 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004797 * HWC layer minidump
4798 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004799 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004800 const auto displayId = display->getId();
4801 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004802 continue;
4803 }
4804
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004806 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004807 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004808 result.append("\n");
4809 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004810
4811 /*
4812 * Dump HWComposer state
4813 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004815 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004816 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004817 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004819 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004820
4821 /*
4822 * Dump gralloc state
4823 */
4824 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4825 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004826
4827 /*
4828 * Dump VrFlinger state if in use.
4829 */
4830 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4831 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004833 result.append("\n");
4834 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835}
4836
Dominik Laskowski075d3172018-05-24 15:50:06 -07004837const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004838 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004839 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004840 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004841 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004842 }
4843 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844
Dominik Laskowski34157762018-10-31 13:07:19 -07004845 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004846 static const Vector<sp<Layer>> empty;
4847 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004848}
4849
Keun young Park63f165f2012-08-31 10:53:36 -07004850bool SurfaceFlinger::startDdmConnection()
4851{
4852 void* libddmconnection_dso =
4853 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4854 if (!libddmconnection_dso) {
4855 return false;
4856 }
4857 void (*DdmConnection_start)(const char* name);
4858 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004859 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004860 if (!DdmConnection_start) {
4861 dlclose(libddmconnection_dso);
4862 return false;
4863 }
4864 (*DdmConnection_start)(getServiceName());
4865 return true;
4866}
4867
Chia-I Wu28f320b2018-05-03 11:02:56 -07004868void SurfaceFlinger::updateColorMatrixLocked() {
4869 mat4 colorMatrix;
4870 if (mGlobalSaturationFactor != 1.0f) {
4871 // Rec.709 luma coefficients
4872 float3 luminance{0.213f, 0.715f, 0.072f};
4873 luminance *= 1.0f - mGlobalSaturationFactor;
4874 mat4 saturationMatrix = mat4(
4875 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4876 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4877 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4878 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4879 );
4880 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4881 } else {
4882 colorMatrix = mClientColorMatrix * mDaltonizer();
4883 }
4884
4885 if (mCurrentState.colorMatrix != colorMatrix) {
4886 mCurrentState.colorMatrix = colorMatrix;
4887 mCurrentState.colorMatrixChanged = true;
4888 setTransactionFlags(eTransactionNeeded);
4889 }
4890}
4891
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004892status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893#pragma clang diagnostic push
4894#pragma clang diagnostic error "-Wswitch-enum"
4895 switch (static_cast<ISurfaceComposerTag>(code)) {
4896 // These methods should at minimum make sure that the client requested
4897 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004898 case BOOT_FINISHED:
4899 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 case CREATE_DISPLAY:
4901 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004902 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 case GET_ACTIVE_COLOR_MODE:
4904 case GET_ANIMATION_FRAME_STATS:
4905 case GET_HDR_CAPABILITIES:
4906 case SET_ACTIVE_CONFIG:
4907 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004908 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004909 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004910 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004911 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4912 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004913 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4914 IPCThreadState* ipc = IPCThreadState::self();
4915 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4916 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004917 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 }
Robert Carr1db73f62016-12-21 12:58:51 -08004919 return OK;
4920 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004922 IPCThreadState* ipc = IPCThreadState::self();
4923 const int pid = ipc->getCallingPid();
4924 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4926 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004927 return PERMISSION_DENIED;
4928 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 // Used by apps to hook Choreographer to SurfaceFlinger.
4932 case CREATE_DISPLAY_EVENT_CONNECTION:
4933 // The following calls are currently used by clients that do not
4934 // request necessary permissions. However, they do not expose any secret
4935 // information, so it is OK to pass them.
4936 case AUTHENTICATE_SURFACE:
4937 case GET_ACTIVE_CONFIG:
4938 case GET_BUILT_IN_DISPLAY:
4939 case GET_DISPLAY_COLOR_MODES:
4940 case GET_DISPLAY_CONFIGS:
4941 case GET_DISPLAY_STATS:
4942 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4943 // Calling setTransactionState is safe, because you need to have been
4944 // granted a reference to Client* and Handle* to do anything with it.
4945 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004946 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004947 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004948 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949 return OK;
4950 }
4951 case CAPTURE_LAYERS:
4952 case CAPTURE_SCREEN: {
4953 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004954 IPCThreadState* ipc = IPCThreadState::self();
4955 const int pid = ipc->getCallingPid();
4956 const int uid = ipc->getCallingUid();
4957 if ((uid != AID_GRAPHICS) &&
4958 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4959 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4960 return PERMISSION_DENIED;
4961 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004962 return OK;
4963 }
4964 // The following codes are deprecated and should never be allowed to access SF.
4965 case CONNECT_DISPLAY_UNUSED:
4966 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4967 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4968 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971
4972 // These codes are used for the IBinder protocol to either interrogate the recipient
4973 // side of the transaction for its canonical interface descriptor or to dump its state.
4974 // We let them pass by default.
4975 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4976 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4977 code == IBinder::SYSPROPS_TRANSACTION) {
4978 return OK;
4979 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004980 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004982 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004983 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4984 return OK;
4985 }
4986 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4987 return PERMISSION_DENIED;
4988#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004989}
4990
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4992 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004993 status_t credentialCheck = CheckTransactCodeCredentials(code);
4994 if (credentialCheck != OK) {
4995 return credentialCheck;
4996 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004997
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004998 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4999 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005000 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005001 IPCThreadState* ipc = IPCThreadState::self();
5002 const int uid = ipc->getCallingUid();
5003 if (CC_UNLIKELY(uid != AID_SYSTEM
5004 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005005 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005006 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005007 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 return PERMISSION_DENIED;
5009 }
5010 int n;
5011 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005012 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005013 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 return NO_ERROR;
5015 case 1002: // SHOW_UPDATES
5016 n = data.readInt32();
5017 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005018 invalidateHwcGeometry();
5019 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005021 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005022 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005023 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005025 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005026 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005027 setTransactionFlags(
5028 eTransactionNeeded|
5029 eDisplayTransactionNeeded|
5030 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005031 return NO_ERROR;
5032 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005033 case 1006:{ // send empty update
5034 signalRefresh();
5035 return NO_ERROR;
5036 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005037 case 1008: // toggle use of hw composer
5038 n = data.readInt32();
5039 mDebugDisableHWC = n ? 1 : 0;
5040 invalidateHwcGeometry();
5041 repaintEverything();
5042 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005043 case 1009: // toggle use of transform hint
5044 n = data.readInt32();
5045 mDebugDisableTransformHint = n ? 1 : 0;
5046 invalidateHwcGeometry();
5047 repaintEverything();
5048 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005050 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 reply->writeInt32(0);
5052 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005053 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005054 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005055 return NO_ERROR;
5056 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005057 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005058 if (!display) {
5059 return NAME_NOT_FOUND;
5060 }
5061
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005062 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005063 return NO_ERROR;
5064 }
5065 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005066 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005067 // daltonize
5068 n = data.readInt32();
5069 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005070 case 1:
5071 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5072 break;
5073 case 2:
5074 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5075 break;
5076 case 3:
5077 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5078 break;
5079 default:
5080 mDaltonizer.setType(ColorBlindnessType::None);
5081 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005082 }
5083 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005084 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005085 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005086 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005087 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005088
5089 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005092 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005093 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005094 // apply a color matrix
5095 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005096 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005097 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005098 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005099 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005100 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005101 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005102 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005103 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005105 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005106
5107 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5108 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005110 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5111 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5112 }
5113
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005115 return NO_ERROR;
5116 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005117 // This is an experimental interface
5118 // Needs to be shifted to proper binder interface when we productize
5119 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005120 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005121 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005122 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005123 return NO_ERROR;
5124 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005125 case 1017: {
5126 n = data.readInt32();
5127 mForceFullDamage = static_cast<bool>(n);
5128 return NO_ERROR;
5129 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005130 case 1018: { // Modify Choreographer's phase offset
5131 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005132 if (mUseScheduler) {
5133 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5134 } else {
5135 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5136 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005137 return NO_ERROR;
5138 }
5139 case 1019: { // Modify SurfaceFlinger's phase offset
5140 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005141 if (mUseScheduler) {
5142 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5143 } else {
5144 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5145 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005146 return NO_ERROR;
5147 }
Irvel468051e2016-06-13 16:44:44 -07005148 case 1020: { // Layer updates interceptor
5149 n = data.readInt32();
5150 if (n) {
5151 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005152 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005153 }
5154 else{
5155 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005156 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005157 }
5158 return NO_ERROR;
5159 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005160 case 1021: { // Disable HWC virtual displays
5161 n = data.readInt32();
5162 mUseHwcVirtualDisplays = !n;
5163 return NO_ERROR;
5164 }
Romain Guy0147a172017-06-01 13:53:56 -07005165 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005166 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005167 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005168
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005170 return NO_ERROR;
5171 }
Romain Guy54f154a2017-10-24 21:40:32 +01005172 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005173 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005174 invalidateHwcGeometry();
5175 repaintEverything();
5176 return NO_ERROR;
5177 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005178 // Deprecate, use 1030 to check whether the device is color managed.
5179 case 1024: {
5180 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005181 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005182 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005183 n = data.readInt32();
5184 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005185 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005186 mTracing.enable();
5187 doTracing("tracing.enable");
5188 reply->writeInt32(NO_ERROR);
5189 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005190 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005191 status_t err = mTracing.disable();
5192 reply->writeInt32(err);
5193 }
5194 return NO_ERROR;
5195 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005196 case 1026: { // Get layer tracing status
5197 reply->writeBool(mTracing.isEnabled());
5198 return NO_ERROR;
5199 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005200 // Is a DisplayColorSetting supported?
5201 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005202 const auto display = getDefaultDisplayDevice();
5203 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005204 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005205 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005206
5207 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5208 switch (setting) {
5209 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005210 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005211 break;
5212 case DisplayColorSetting::UNMANAGED:
5213 reply->writeBool(true);
5214 break;
5215 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005216 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005217 break;
5218 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005219 reply->writeBool(
5220 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005221 break;
5222 }
5223 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005224 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005225 // Is VrFlinger active?
5226 case 1028: {
5227 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005228 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005229 return NO_ERROR;
5230 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005231 // Is device color managed?
5232 case 1030: {
5233 reply->writeBool(useColorManagement);
5234 return NO_ERROR;
5235 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005236 // Override default composition data space
5237 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5238 // && adb shell stop zygote && adb shell start zygote
5239 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5240 // adb shell stop zygote && adb shell start zygote
5241 case 1031: {
5242 Mutex::Autolock _l(mStateLock);
5243 n = data.readInt32();
5244 if (n) {
5245 n = data.readInt32();
5246 if (n) {
5247 Dataspace dataspace = static_cast<Dataspace>(n);
5248 if (!validateCompositionDataspace(dataspace)) {
5249 return BAD_VALUE;
5250 }
5251 mDefaultCompositionDataspace = dataspace;
5252 }
5253 n = data.readInt32();
5254 if (n) {
5255 Dataspace dataspace = static_cast<Dataspace>(n);
5256 if (!validateCompositionDataspace(dataspace)) {
5257 return BAD_VALUE;
5258 }
5259 mWideColorGamutCompositionDataspace = dataspace;
5260 }
5261 } else {
5262 // restore composition data space.
5263 mDefaultCompositionDataspace = defaultCompositionDataspace;
5264 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5265 }
5266 return NO_ERROR;
5267 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005268 }
5269 }
5270 return err;
5271}
5272
Steven Thomas6d8110b2017-08-31 18:24:21 -07005273void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005274 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005275 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005276}
5277
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5279class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005280public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5282 ~WindowDisconnector() {
5283 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005284 }
5285
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005286private:
5287 ANativeWindow* mWindow;
5288 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005289};
5290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005291status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005292 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5293 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005294 uint32_t reqWidth, uint32_t reqHeight,
5295 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005296 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005297 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005298
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005299 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005300
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005301 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5302
Chia-I Wu20261cb2018-08-23 12:55:44 -07005303 sp<DisplayDevice> display;
5304 {
5305 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005306
Chia-I Wu20261cb2018-08-23 12:55:44 -07005307 display = getDisplayDeviceLocked(displayToken);
5308 if (!display) return BAD_VALUE;
5309
Chia-I Wucb023152018-08-28 12:57:23 -07005310 // set the requested width/height to the logical display viewport size
5311 // by default
5312 if (reqWidth == 0 || reqHeight == 0) {
5313 reqWidth = uint32_t(display->getViewport().width());
5314 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005315 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005316 }
5317
Peiyong Lin0e003c92018-09-17 11:09:51 -07005318 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5319 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005320
5321 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005322 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005323 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5324 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005325}
5326
5327status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005328 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5329 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005330 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005331 ATRACE_CALL();
5332
5333 class LayerRenderArea : public RenderArea {
5334 public:
Robert Carr578038f2018-03-09 12:25:24 -08005335 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005336 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5337 bool childrenOnly)
5338 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005339 mLayer(layer),
5340 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005341 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005342 mFlinger(flinger),
5343 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005344 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005345 Rect getBounds() const override {
5346 const Layer::State& layerState(mLayer->getDrawingState());
5347 return mLayer->getBufferSize(layerState);
5348 }
Marissa Wall61c58622018-07-18 10:12:20 -07005349 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005350 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005351 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005352 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005353 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005354 }
chaviwa76b2712017-09-20 12:02:26 -07005355 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005356 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005357 Rect getSourceCrop() const override {
5358 if (mCrop.isEmpty()) {
5359 return getBounds();
5360 } else {
5361 return mCrop;
5362 }
5363 }
Robert Carr578038f2018-03-09 12:25:24 -08005364 class ReparentForDrawing {
5365 public:
5366 const sp<Layer>& oldParent;
5367 const sp<Layer>& newParent;
5368
5369 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5370 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005371 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005372 }
Robert Carr15eae092018-03-23 13:43:53 -07005373 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005374 };
5375
5376 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005377 const Rect sourceCrop = getSourceCrop();
5378 // no need to check rotation because there is none
5379 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5380 sourceCrop.height() != getReqHeight();
5381
Robert Carr578038f2018-03-09 12:25:24 -08005382 if (!mChildrenOnly) {
5383 mTransform = mLayer->getTransform().inverse();
5384 drawLayers();
5385 } else {
5386 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005387 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005388 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5389 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005390
5391 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5392 drawLayers();
5393 }
5394 }
chaviwa76b2712017-09-20 12:02:26 -07005395
chaviwa76b2712017-09-20 12:02:26 -07005396 private:
chaviw7206d492017-11-10 16:16:12 -08005397 const sp<Layer> mLayer;
5398 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005399
5400 // In the "childrenOnly" case we reparent the children to a screenshot
5401 // layer which has no properties set and which does not draw.
5402 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005403 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005404 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005405
5406 SurfaceFlinger* mFlinger;
5407 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005408 };
5409
5410 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5411 auto parent = layerHandle->owner.promote();
5412
Robert Carr2e102c92018-10-23 12:11:15 -07005413 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005414 ALOGE("captureLayers called with a removed parent");
5415 return NAME_NOT_FOUND;
5416 }
5417
Robert Carr578038f2018-03-09 12:25:24 -08005418 const int uid = IPCThreadState::self()->getCallingUid();
5419 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005420 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005421 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5422 return PERMISSION_DENIED;
5423 }
5424
chaviw7206d492017-11-10 16:16:12 -08005425 Rect crop(sourceCrop);
5426 if (sourceCrop.width() <= 0) {
5427 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005428 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005429 }
5430
5431 if (sourceCrop.height() <= 0) {
5432 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005433 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005434 }
5435
5436 int32_t reqWidth = crop.width() * frameScale;
5437 int32_t reqHeight = crop.height() * frameScale;
5438
Chia-I Wu20261cb2018-08-23 12:55:44 -07005439 // really small crop or frameScale
5440 if (reqWidth <= 0) {
5441 reqWidth = 1;
5442 }
5443 if (reqHeight <= 0) {
5444 reqHeight = 1;
5445 }
5446
Peiyong Lin0e003c92018-09-17 11:09:51 -07005447 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005448
Robert Carr578038f2018-03-09 12:25:24 -08005449 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005450 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5451 if (!layer->isVisible()) {
5452 return;
Robert Carr578038f2018-03-09 12:25:24 -08005453 } else if (childrenOnly && layer == parent.get()) {
5454 return;
chaviwa76b2712017-09-20 12:02:26 -07005455 }
5456 visitor(layer);
5457 });
5458 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005459 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005460}
5461
5462status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5463 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005464 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005465 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005466 bool useIdentityTransform) {
5467 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005468
Peiyong Lin0e003c92018-09-17 11:09:51 -07005469 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005470 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5471 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005472 *outBuffer =
5473 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5474 static_cast<android_pixel_format>(reqPixelFormat), 1,
5475 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005476
5477 // This mutex protects syncFd and captureResult for communication of the return values from the
5478 // main thread back to this Binder thread
5479 std::mutex captureMutex;
5480 std::condition_variable captureCondition;
5481 std::unique_lock<std::mutex> captureLock(captureMutex);
5482 int syncFd = -1;
5483 std::optional<status_t> captureResult;
5484
Robert Carr03480e22018-01-04 16:02:06 -08005485 const int uid = IPCThreadState::self()->getCallingUid();
5486 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5487
Dominik Laskowski8c001672018-05-30 16:52:06 -07005488 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005489 // If there is a refresh pending, bug out early and tell the binder thread to try again
5490 // after the refresh.
5491 if (mRefreshPending) {
5492 ATRACE_NAME("Skipping screenshot for now");
5493 std::unique_lock<std::mutex> captureLock(captureMutex);
5494 captureResult = std::make_optional<status_t>(EAGAIN);
5495 captureCondition.notify_one();
5496 return;
5497 }
5498
5499 status_t result = NO_ERROR;
5500 int fd = -1;
5501 {
5502 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005503 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005504 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5505 useIdentityTransform, forSystem, &fd);
5506 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507 }
5508
5509 {
5510 std::unique_lock<std::mutex> captureLock(captureMutex);
5511 syncFd = fd;
5512 captureResult = std::make_optional<status_t>(result);
5513 captureCondition.notify_one();
5514 }
5515 });
5516
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005517 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005518 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005519 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005520 while (*captureResult == EAGAIN) {
5521 captureResult.reset();
5522 result = postMessageAsync(message);
5523 if (result != NO_ERROR) {
5524 return result;
5525 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005526 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005527 }
5528 result = *captureResult;
5529 }
5530
5531 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005532 sync_wait(syncFd, -1);
5533 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005534 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005535
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005536 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005537}
5538
chaviwa76b2712017-09-20 12:02:26 -07005539void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005540 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005541 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005542 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005543
Lloyd Pique144e1162017-12-20 16:44:52 -08005544 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005545
chaviwa76b2712017-09-20 12:02:26 -07005546 const auto reqWidth = renderArea.getReqWidth();
5547 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005548 const auto sourceCrop = renderArea.getSourceCrop();
5549 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005550
Peiyong Lin0e003c92018-09-17 11:09:51 -07005551 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005552 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005553
Mathias Agopian180f10d2013-04-10 22:55:41 -07005554 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005555 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005556
5557 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005558 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005559 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005560
chaviw50da5042018-04-09 13:49:37 -07005561 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005562 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005563 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005564
chaviwa76b2712017-09-20 12:02:26 -07005565 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005566 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005567 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005568 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005569 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005570}
5571
chaviwa76b2712017-09-20 12:02:26 -07005572status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5573 TraverseLayersFunction traverseLayers,
5574 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005575 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005576 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005577 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005578 ATRACE_CALL();
5579
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005580 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005581
5582 traverseLayers([&](Layer* layer) {
5583 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5584 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005585
Robert Carr03480e22018-01-04 16:02:06 -08005586 // We allow the system server to take screenshots of secure layers for
5587 // use in situations like the Screen-rotation animation and place
5588 // the impetus on WindowManager to not persist them.
5589 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005590 ALOGW("FB is protected: PERMISSION_DENIED");
5591 return PERMISSION_DENIED;
5592 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005593 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005594
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005595 // this binds the given EGLImage as a framebuffer for the
5596 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005597 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005598 if (bufferBond.getStatus() != NO_ERROR) {
5599 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005600 return INVALID_OPERATION;
5601 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005602
Dan Stozaabcda352017-06-01 14:37:39 -07005603 // this will in fact render into our dequeued buffer
5604 // via an FBO, which means we didn't have to create
5605 // an EGLSurface and therefore we're not
5606 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005607 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005608
Peiyong Linfb530cf2018-12-15 05:07:38 +00005609 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005610 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005611 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005612 }
Alec Mouri492bc572018-09-11 21:40:04 +00005613 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005614
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005615 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005616}
5617
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005618// ---------------------------------------------------------------------------
5619
Dan Stoza412903f2017-04-27 13:42:17 -07005620void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5621 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005622}
5623
Dan Stoza412903f2017-04-27 13:42:17 -07005624void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5625 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005626}
5627
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005628void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005629 const LayerVector::Visitor& visitor) {
5630 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005631 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005632 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005633 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005634 continue;
5635 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005636 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005637 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005638 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005639 return;
5640 }
chaviwa76b2712017-09-20 12:02:26 -07005641 if (!layer->isVisible()) {
5642 return;
5643 }
5644 visitor(layer);
5645 });
5646 }
5647}
5648
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005649}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005650
Lloyd Pique074e8122018-07-26 12:57:23 -07005651
Mathias Agopian3f844832013-08-07 21:24:32 -07005652#if defined(__gl_h_)
5653#error "don't include gl/gl.h in this file"
5654#endif
5655
5656#if defined(__gl2_h_)
5657#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005658#endif