blob: dc0266655996380e9ee88c48ec37a4c2fa5b507b [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
Dominik Laskowskif654d572018-12-20 11:03:06 -0800621 auto resyncCallback = makeResyncCallback();
622
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700624 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700625 mScheduler = getFactory().createScheduler([this](bool enabled) {
626 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
627 });
628
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700630 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800631 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 impl::EventThread::InterceptVSyncsCallback());
633 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700634 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800635 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 mInterceptor->saveVSyncEvent(timestamp);
637 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800638
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700640 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
641 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 } else {
643 mEventThreadSource =
644 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
645 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
646 mEventThread =
647 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 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(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700656 [this](nsecs_t timestamp) {
657 mInterceptor->saveVSyncEvent(timestamp);
658 },
659 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800660 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700661 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800663
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700665 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700666 renderEngineFeature |= (useColorManagement ?
667 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700668 renderEngineFeature |= (useContextPriority ?
669 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700670
671 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700673 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700674 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700675
676 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
677 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
679 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 const auto display = getDefaultDisplayDeviceLocked();
683 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800686
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 // This callback is called from the vr flinger dispatch thread. We
690 // need to call signalTransaction(), which requires holding
691 // mStateLock when we're not on the main thread. Acquiring
692 // mStateLock from the vr flinger dispatch thread might trigger a
693 // deadlock in surface flinger (see b/66916578), so post a message
694 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
697 mVrFlingerRequestsDisplay = requestDisplay;
698 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
702 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 .value_or(0),
705 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (!mVrFlinger) {
707 ALOGE("Failed to start vrflinger");
708 }
709 }
710
Lloyd Pique90c115d2018-09-18 21:39:42 -0700711 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700713
Mathias Agopian92a979a2012-08-02 18:32:23 -0700714 // initialize our drawing state
715 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700716
Andy McFadden13a082e2012-08-24 10:16:42 -0700717 // set initial conditions (e.g. unblank default device)
718 initializeDisplays();
719
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700720 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700721
Wei Wangf9b05ee2017-07-19 20:59:39 -0700722 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700723
724 const bool presentFenceReliable =
725 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
726 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727
728 if (mStartPropertySetThread->Start() != NO_ERROR) {
729 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800731
Ana Krulec7d1d6832018-12-27 11:10:09 -0800732 if (mUseScheduler) {
733 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
734 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
735 }
736
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700752}
753
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Start boot animation service by setting a property mailbox
756 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700757 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 if (mStartPropertySetThread->join() != NO_ERROR) {
760 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700765 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800773
Jamie Gennis582270d2011-08-17 18:19:00 -0700774bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800775 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800776 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800777 return authenticateSurfaceTextureLocked(bufferProducer);
778}
779
780bool SurfaceFlinger::authenticateSurfaceTextureLocked(
781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800782 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800783 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800784}
785
Brian Anderson6b376712017-04-04 10:51:39 -0700786status_t SurfaceFlinger::getSupportedFrameTimestamps(
787 std::vector<FrameEvent>* outSupported) const {
788 *outSupported = {
789 FrameEvent::REQUESTED_PRESENT,
790 FrameEvent::ACQUIRE,
791 FrameEvent::LATCH,
792 FrameEvent::FIRST_REFRESH_START,
793 FrameEvent::LAST_REFRESH_START,
794 FrameEvent::GPU_COMPOSITION_DONE,
795 FrameEvent::DEQUEUE_READY,
796 FrameEvent::RELEASE,
797 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700800 if (!getHwComposer().hasCapability(
801 HWC2::Capability::PresentFenceIsNotReliable)) {
802 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
803 }
804 return NO_ERROR;
805}
806
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
808 Vector<DisplayInfo>* configs) {
809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 const auto displayId = getPhysicalDisplayId(displayToken);
814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700822 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826 return density;
827 }
828 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Steven Thomas6d8110b2017-08-31 18:24:21 -0700837 ConditionalLock _l(mStateLock,
838 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 DisplayInfo info = DisplayInfo();
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 float xdpi = hwConfig->getDpiX();
843 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700845 info.w = hwConfig->getWidth();
846 info.h = hwConfig->getHeight();
847 // Default display viewport to display width and height
848 info.viewportW = info.w;
849 info.viewportH = info.h;
850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 // The density of the device is provided by a build property
853 float density = Density::getBuildDensity() / 160.0f;
854 if (density == 0) {
855 // the build doesn't provide a density -- this is wrong!
856 // use xdpi instead
857 ALOGE("ro.sf.lcd_density must be defined as a build property");
858 density = xdpi / 160.0f;
859 }
860 if (Density::getEmuDensity()) {
861 // if "qemu.sf.lcd_density" is specified, it overrides everything
862 xdpi = ydpi = density = Density::getEmuDensity();
863 density /= 160.0f;
864 }
865 info.density = density;
866
867 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868 const auto display = getDefaultDisplayDeviceLocked();
869 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
871 // This is for screenrecord
872 const Rect viewport = display->getViewport();
873 if (viewport.isValid()) {
874 info.viewportW = uint32_t(viewport.getWidth());
875 info.viewportH = uint32_t(viewport.getHeight());
876 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 } else {
878 // TODO: where should this value come from?
879 static const int TV_DENSITY = 213;
880 info.density = TV_DENSITY / 160.0f;
881 info.orientation = 0;
882 }
883
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Dominik Laskowski075d3172018-05-24 15:50:06 -0700907 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700908 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
Ana Krulece588e312018-09-18 12:32:24 -0700923 if (mUseScheduler) {
924 mScheduler->getDisplayStatInfo(stats);
925 } else {
926 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
928 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return NO_ERROR;
930}
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
933 const auto display = getDisplayDevice(displayToken);
934 if (!display) {
935 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800936 return BAD_VALUE;
937 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700940}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700941
Ana Krulec7d1d6832018-12-27 11:10:09 -0800942status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
943 ATRACE_NAME("setActiveConfigAsync");
944 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
945 return NO_ERROR;
946}
947
948status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
949 ATRACE_NAME("setActiveConfigSync");
950 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
951 return NO_ERROR;
952}
953
954void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
955 Vector<DisplayInfo> configs;
956 getDisplayConfigs(displayToken, &configs);
957 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
958 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
959 return;
960 }
961
962 const auto display = getDisplayDevice(displayToken);
963 if (!display) {
964 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
965 displayToken.get());
966 return;
967 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700968 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 return;
971 }
972 int currentDisplayPowerMode = display->getPowerMode();
973 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
974 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 return;
976 }
977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700979 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800980 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981 return;
982 }
983
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 const auto displayId = display->getId();
985 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 ATRACE_INT("ActiveConfigMode", mode);
991 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700992}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
995 Vector<ColorMode>* outColorModes) {
996 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return BAD_VALUE;
998 }
999
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 const auto displayId = getPhysicalDisplayId(displayToken);
1001 if (!displayId) {
1002 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001003 }
1004
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001006 {
1007 ConditionalLock _l(mStateLock,
1008 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001009 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001010 }
Michael Wright28f24d02016-07-12 13:30:53 -07001011 outColorModes->clear();
1012 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1013
1014 return NO_ERROR;
1015}
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1018 if (const auto display = getDisplayDevice(displayToken)) {
1019 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001020 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1025 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001026 if (display->isVirtual()) {
1027 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1028 return;
1029 }
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 ColorMode currentMode = display->getActiveColorMode();
1032 Dataspace currentDataSpace = display->getCompositionDataSpace();
1033 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001034
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 if (mode == currentMode && dataSpace == currentDataSpace &&
1036 renderIntent == currentRenderIntent) {
1037 return;
1038 }
1039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 display->setActiveColorMode(mode);
1041 display->setCompositionDataSpace(dataSpace);
1042 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001043
Dominik Laskowski075d3172018-05-24 15:50:06 -07001044 const auto displayId = display->getId();
1045 LOG_ALWAYS_FATAL_IF(!displayId);
1046 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1047
Dominik Laskowski34157762018-10-31 13:07:19 -07001048 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001050 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001051}
1052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001054 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 Vector<ColorMode> modes;
1056 getDisplayColorModes(displayToken, &modes);
1057 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1058 if (mode < ColorMode::NATIVE || !exists) {
1059 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1060 decodeColorMode(mode).c_str(), mode, displayToken.get());
1061 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001062 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 const auto display = getDisplayDevice(displayToken);
1064 if (!display) {
1065 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1066 decodeColorMode(mode).c_str(), mode, displayToken.get());
1067 } else if (display->isVirtual()) {
1068 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1069 decodeColorMode(mode).c_str(), mode);
1070 } else {
1071 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1072 RenderIntent::COLORIMETRIC);
1073 }
1074 }));
1075
Michael Wright28f24d02016-07-12 13:30:53 -07001076 return NO_ERROR;
1077}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078
Svetoslavd85084b2014-03-20 10:28:31 -07001079status_t SurfaceFlinger::clearAnimationFrameStats() {
1080 Mutex::Autolock _l(mStateLock);
1081 mAnimFrameTracker.clearStats();
1082 return NO_ERROR;
1083}
1084
1085status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1086 Mutex::Autolock _l(mStateLock);
1087 mAnimFrameTracker.getStats(outStats);
1088 return NO_ERROR;
1089}
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1092 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 Mutex::Autolock _l(mStateLock);
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const auto display = getDisplayDeviceLocked(displayToken);
1096 if (!display) {
1097 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 return BAD_VALUE;
1099 }
1100
Peiyong Linfb069302018-04-25 14:34:31 -07001101 // At this point the DisplayDeivce should already be set up,
1102 // meaning the luminance information is already queried from
1103 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001105 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1106 capabilities.getDesiredMaxLuminance(),
1107 capabilities.getDesiredMaxAverageLuminance(),
1108 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001109
1110 return NO_ERROR;
1111}
1112
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001113status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1114 ui::PixelFormat* outFormat,
1115 ui::Dataspace* outDataspace,
1116 uint8_t* outComponentMask) const {
1117 if (!outFormat || !outDataspace || !outComponentMask) {
1118 return BAD_VALUE;
1119 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001120 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001121 if (!display || !display->getId()) {
1122 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1123 return BAD_VALUE;
1124 }
1125 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1126 outDataspace, outComponentMask);
1127}
1128
Kevin DuBois74e53772018-11-19 10:52:38 -08001129status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1130 bool enable, uint8_t componentMask,
1131 uint64_t maxFrames) const {
1132 const auto display = getDisplayDevice(displayToken);
1133 if (!display || !display->getId()) {
1134 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1135 return BAD_VALUE;
1136 }
1137
1138 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1139 componentMask, maxFrames);
1140}
1141
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001142status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1143 uint64_t maxFrames, uint64_t timestamp,
1144 DisplayedFrameStats* outStats) const {
1145 const auto display = getDisplayDevice(displayToken);
1146 if (!display || !display->getId()) {
1147 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1148 return BAD_VALUE;
1149 }
1150
1151 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1152 outStats);
1153}
1154
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001155status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1156 if (!outSupported) {
1157 return BAD_VALUE;
1158 }
1159 *outSupported = getRenderEngine().supportsProtectedContent();
1160 return NO_ERROR;
1161}
1162
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001164 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 if (mInjectVSyncs == enable) {
1168 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170
Dominik Laskowskif654d572018-12-20 11:03:06 -08001171 auto resyncCallback = makeResyncCallback();
1172
Ana Krulec98b5b242018-08-10 15:03:23 -07001173 // TODO(akrulec): Part of the Injector should be refactored, so that it
1174 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 if (enable) {
1176 ALOGV("VSync Injections enabled");
1177 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001178 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001179 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001180 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001181 impl::EventThread::InterceptVSyncsCallback(),
1182 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001184 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185 } else {
1186 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001187 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 }
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001191 }));
1192
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001193 return NO_ERROR;
1194}
1195
1196status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 Mutex::Autolock _l(mStateLock);
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199 if (!mInjectVSyncs) {
1200 ALOGE("VSync Injections not enabled");
1201 return BAD_VALUE;
1202 }
1203 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1204 ALOGV("Injecting VSync inside SurfaceFlinger");
1205 mVSyncInjector->onInjectSyncEvent(when);
1206 }
1207 return NO_ERROR;
1208}
1209
Lloyd Pique755e3192018-01-31 16:46:15 -08001210status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1211 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001212 // Try to acquire a lock for 1s, fail gracefully
1213 const status_t err = mStateLock.timedLock(s2ns(1));
1214 const bool locked = (err == NO_ERROR);
1215 if (!locked) {
1216 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1217 return TIMED_OUT;
1218 }
1219
1220 outLayers->clear();
1221 mCurrentState.traverseInZOrder([&](Layer* layer) {
1222 outLayers->push_back(layer->getLayerDebugInfo());
1223 });
1224
1225 mStateLock.unlock();
1226 return NO_ERROR;
1227}
1228
Peiyong Linc6780972018-10-28 15:24:08 -07001229status_t SurfaceFlinger::getCompositionPreference(
1230 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1231 Dataspace* outWideColorGamutDataspace,
1232 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001233 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001234 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001235 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001236 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001237 return NO_ERROR;
1238}
1239
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001240// ----------------------------------------------------------------------------
1241
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001242sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1243 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001244 auto resyncCallback = makeResyncCallback();
1245
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 if (mUseScheduler) {
1247 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001248 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001249 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001252 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001255 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001256 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001257 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001258 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001259}
1260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262
1263void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001276 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001286 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001287 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288 if (res == NO_ERROR) {
1289 msg->wait();
1290 }
1291 return res;
1292}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001295 do {
1296 waitForEvent();
1297 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001298}
1299
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300void SurfaceFlinger::enableHardwareVsync() {
1301 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001303 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001304 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001306 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307}
1308
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310 Mutex::Autolock _l(mHWVsyncLock);
1311
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 if (makeAvailable) {
1313 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001314 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1315 if (mUseScheduler) {
1316 mScheduler->makeHWSyncAvailable(true);
1317 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001318 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001319 // Hardware vsync is not currently available, so abort the resync
1320 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001321 return;
1322 }
1323
Dominik Laskowski075d3172018-05-24 15:50:06 -07001324 const auto displayId = getInternalDisplayId();
1325 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001326 return;
1327 }
1328
Dominik Laskowski075d3172018-05-24 15:50:06 -07001329 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331
Ana Krulece588e312018-09-18 12:32:24 -07001332 if (mUseScheduler) {
1333 mScheduler->setVsyncPeriod(period);
1334 } else {
1335 mPrimaryDispSync->reset();
1336 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337
Ana Krulece588e312018-09-18 12:32:24 -07001338 if (!mPrimaryHWVsyncEnabled) {
1339 mPrimaryDispSync->beginResync();
1340 mEventControlThread->setVsyncEnabled(true);
1341 mPrimaryHWVsyncEnabled = true;
1342 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343 }
1344}
1345
Jesse Hall948fe0c2013-10-14 12:56:09 -07001346void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347 Mutex::Autolock _l(mHWVsyncLock);
1348 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001349 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001350 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351 mPrimaryHWVsyncEnabled = false;
1352 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001353 if (makeUnavailable) {
1354 mHWVsyncAvailable = false;
1355 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356}
1357
Dominik Laskowskif654d572018-12-20 11:03:06 -08001358void SurfaceFlinger::VsyncState::resync() {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001359 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001360
1361 // No explicit locking is needed here since EventThread holds a lock while calling this method
Dan Stoza57164302017-05-08 14:03:54 -07001362 const nsecs_t now = systemTime();
Dominik Laskowskif654d572018-12-20 11:03:06 -08001363 if (now - lastResyncTime > kIgnoreDelay) {
1364 flinger.resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001365 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001366 lastResyncTime = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001367}
1368
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001369void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1370 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001371 ATRACE_NAME("SF onVsync");
1372
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001375 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 return;
1377 }
1378
Dominik Laskowski075d3172018-05-24 15:50:06 -07001379 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 return;
1381 }
1382
Dominik Laskowski075d3172018-05-24 15:50:06 -07001383 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001384 // For now, we don't do anything with external display vsyncs.
1385 return;
1386 }
1387
Ana Krulece588e312018-09-18 12:32:24 -07001388 if (mUseScheduler) {
1389 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001390 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001391 bool needsHwVsync = false;
1392 { // Scope for the lock
1393 Mutex::Autolock _l(mHWVsyncLock);
1394 if (mPrimaryHWVsyncEnabled) {
1395 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1396 }
1397 }
1398
1399 if (needsHwVsync) {
1400 enableHardwareVsync();
1401 } else {
1402 disableHardwareVsync(false);
1403 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001404 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001405}
1406
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001408 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1409 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410}
1411
Ana Krulec7d1d6832018-12-27 11:10:09 -08001412void SurfaceFlinger::setRefreshRateTo(float newFps) {
1413 const auto displayId = getInternalDisplayId();
1414 if (!displayId || mBootStage != BootStage::FINISHED) {
1415 return;
1416 }
1417 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1418 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1419 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1420 // refresh cycle.
1421
1422 // Don't do any updating if the current fps is the same as the new one.
1423 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1424 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1425 if (currentVsyncPeriod == 0) {
1426 return;
1427 }
1428 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1429 // floating numbers.
1430 const float currentFps = 1e9 / currentVsyncPeriod;
1431 if (std::abs(currentFps - newFps) <= 1) {
1432 return;
1433 }
1434
1435 auto configs = getHwComposer().getConfigs(*displayId);
1436 for (int i = 0; i < configs.size(); i++) {
1437 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1438 if (vsyncPeriod == 0) {
1439 continue;
1440 }
1441 const float fps = 1e9 / vsyncPeriod;
1442 // TODO(b/113612090): There should be a better way at determining which config
1443 // has the right refresh rate.
1444 if (std::abs(fps - newFps) <= 1) {
1445 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1446 if (!display) return;
1447 // This is posted in async function to avoid deadlock when getDisplayDevice
1448 // requires mStateLock.
1449 setActiveConfigAsync(display, i);
1450 ATRACE_INT("FPS", newFps);
1451 }
1452 }
1453}
1454
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001455void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001456 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001457 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001458 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459
Lloyd Piqueba04e622017-12-14 17:11:26 -08001460 // Ignore events that do not have the right sequenceId.
1461 if (sequenceId != getBE().mComposerSequenceId) {
1462 return;
1463 }
1464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 // Only lock if we're not on the main thread. This function is normally
1466 // called on a hwbinder thread, but for the primary display it's called on
1467 // the main thread with the state lock already held, so don't attempt to
1468 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001469 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001470
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001471 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001472
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001473 if (std::this_thread::get_id() == mMainThreadId) {
1474 // Process all pending hot plug events immediately if we are on the main thread.
1475 processDisplayHotplugEventsLocked();
1476 }
1477
Lloyd Piqueba04e622017-12-14 17:11:26 -08001478 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001479}
1480
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001481void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001482 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001483 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001485 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001487}
1488
Dominik Laskowski075d3172018-05-24 15:50:06 -07001489void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001490 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001492 if (const auto displayId = getInternalDisplayId()) {
1493 getHwComposer().setVsyncEnabled(*displayId,
1494 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1495 }
Mathias Agopian86303202012-07-24 22:46:10 -07001496}
1497
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001498// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001499void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001500 if (mUseScheduler) {
1501 mScheduler->disableHardwareVsync(true);
1502 } else {
1503 disableHardwareVsync(true);
1504 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001505 // Clear the drawing state so that the logic inside of
1506 // handleTransactionLocked will fire. It will determine the delta between
1507 // mCurrentState and mDrawingState and re-apply all changes when we make the
1508 // transition.
1509 mDrawingState.displays.clear();
1510 mDisplays.clear();
1511}
1512
Steven Thomas050b2c82017-03-06 11:45:16 -08001513void SurfaceFlinger::updateVrFlinger() {
1514 if (!mVrFlinger)
1515 return;
1516 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001518 return;
1519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520
Lloyd Pique441d5042018-10-18 16:49:51 -07001521 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 ALOGE("Vr flinger is only supported for remote hardware composer"
1523 " service connections. Ignoring request to transition to vr"
1524 " flinger.");
1525 mVrFlingerRequestsDisplay = false;
1526 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001527 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001530
Steven Thomas0123ac62018-07-12 11:32:34 -07001531 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001532 LOG_ALWAYS_FATAL_IF(!display);
1533 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001534 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1535 // called below. Clear the reference now so we don't accidentally use it
1536 // later.
1537 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001538
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001542
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001544 // Delete the current instance before creating the new one
1545 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1546 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1547 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1548 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549
Lloyd Pique441d5042018-10-18 16:49:51 -07001550 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001551 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001552
1553 if (vrFlingerRequestsDisplay) {
1554 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001555 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
1557 mVisibleRegionsDirty = true;
1558 invalidateHwcGeometry();
1559
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001560 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001561 display = getDefaultDisplayDeviceLocked();
1562 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001563 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001566 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 const nsecs_t period = activeConfig->getVsyncPeriod();
1568 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001569
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570 // The present fences returned from vr_hwc are not an accurate
1571 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001572 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001573 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1574 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001575 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001576 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001577 !hasSyncFramework);
1578 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Use phase of 0 since phase is not known.
1581 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001582 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1583 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001584
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001585 resyncToHardwareVsync(false);
1586
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001587 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001589}
1590
Mathias Agopian4fec8732012-06-29 14:12:52 -07001591void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001592 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001593 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001594 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001595 if (mUseScheduler) {
1596 // This call is made each time SF wakes up and creates a new frame.
1597 mScheduler->incrementFrameCounter();
1598 }
Dan Stoza50182882016-07-08 12:02:20 -07001599 bool frameMissed = !mHadClientComposition &&
1600 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 (mPreviousPresentFence->getSignalTime() ==
1602 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001603 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001604 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001605 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001606 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001607 if (mPropagateBackpressure) {
1608 signalLayerUpdate();
1609 break;
1610 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 }
Dan Stoza50182882016-07-08 12:02:20 -07001612
Steven Thomas050b2c82017-03-06 11:45:16 -08001613 // Now that we're going to make it to the handleMessageTransaction()
1614 // call below it's safe to call updateVrFlinger(), which will
1615 // potentially trigger a display handoff.
1616 updateVrFlinger();
1617
Dan Stoza6b9454d2014-11-07 16:00:59 -08001618 bool refreshNeeded = handleMessageTransaction();
1619 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001620 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001621 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001622 // Signal a refresh if a transaction modified the window state,
1623 // a new buffer was latched, or if HWC has requested a full
1624 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625 signalRefresh();
1626 }
1627 break;
1628 }
1629 case MessageQueue::REFRESH: {
1630 handleMessageRefresh();
1631 break;
1632 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001633 }
1634}
1635
Dan Stoza6b9454d2014-11-07 16:00:59 -08001636bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001637 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001638
1639 // Apply any ready transactions in the queues if there are still transactions that have not been
1640 // applied, wake up during the next vsync period and check again
1641 bool transactionNeeded = false;
1642 if (!flushTransactionQueues()) {
1643 transactionNeeded = true;
1644 }
1645
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001647 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001648 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001649
1650 if (transactionNeeded) {
1651 setTransactionFlags(eTransactionNeeded);
1652 }
1653
1654 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655}
1656
Mathias Agopian4fec8732012-06-29 14:12:52 -07001657void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001658 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001659
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001660 mRefreshPending = false;
1661
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001662 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001663 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001664 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001665 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001666 for (const auto& [token, display] : mDisplays) {
1667 beginFrame(display);
1668 prepareFrame(display);
1669 doDebugFlashRegions(display, repaintEverything);
1670 doComposition(display, repaintEverything);
1671 }
1672
Adrian Roos1e1a1282017-11-01 19:05:31 +01001673 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001674 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675
1676 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001677 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001678
Dan Stozabfbffeb2016-07-21 14:49:33 -07001679 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001680 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001681 mHadClientComposition =
1682 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001683 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001684
Alec Mouri86770e52018-09-24 22:40:58 +00001685 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001686 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001687 if (mHadClientComposition) {
1688 base::unique_fd flushFence(getRenderEngine().flush());
1689 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1690 getBE().flushFence = new Fence(std::move(flushFence));
1691 } else {
1692 // Cleanup for hygiene.
1693 getBE().flushFence = Fence::NO_FENCE;
1694 }
1695 }
1696
Jorim Jaggi90535212018-05-23 23:44:06 +02001697 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001698
David Sodman7e4ae112018-02-09 15:02:28 -08001699 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001700 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001701 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001702 compositionInfo.hwc.hwcLayer = nullptr;
1703 }
David Sodmanba340492018-08-05 21:51:33 -07001704 }
David Sodman7e4ae112018-02-09 15:02:28 -08001705
1706 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001708
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709
1710bool SurfaceFlinger::handleMessageInvalidate() {
1711 ATRACE_CALL();
1712 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713}
1714
David Sodman79bba0e2018-08-05 18:07:49 -07001715void SurfaceFlinger::calculateWorkingSet() {
1716 ATRACE_CALL();
1717 ALOGV(__FUNCTION__);
1718
David Sodman79bba0e2018-08-05 18:07:49 -07001719 // build the h/w work list
1720 if (CC_UNLIKELY(mGeometryInvalid)) {
1721 mGeometryInvalid = false;
1722 for (const auto& [token, display] : mDisplays) {
1723 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001724 if (!displayId) {
1725 continue;
1726 }
David Sodman79bba0e2018-08-05 18:07:49 -07001727
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1729 for (size_t i = 0; i < currentLayers.size(); i++) {
1730 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001731
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 if (!layer->hasHwcLayer(*displayId)) {
1733 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1734 layer->forceClientComposition(*displayId);
1735 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001736 }
1737 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738
1739 layer->setGeometry(display, i);
1740 if (mDebugDisableHWC || mDebugRegion) {
1741 layer->forceClientComposition(*displayId);
1742 }
David Sodman79bba0e2018-08-05 18:07:49 -07001743 }
1744 }
1745 }
1746
1747 // Set the per-frame data
1748 for (const auto& [token, display] : mDisplays) {
1749 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001750 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001751 continue;
1752 }
1753
1754 if (mDrawingState.colorMatrixChanged) {
1755 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001756 status_t result =
1757 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001758 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1759 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001760 }
1761 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1762 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001764 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1765 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1766 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001767 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001768 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1769 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1770 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001772 }
1773
Peiyong Lind3788632018-09-18 16:01:31 -07001774 // TODO(b/111562338) remove when composer 2.3 is shipped.
1775 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001777 }
1778
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001779 if (layer->getRoundedCornerState().radius > 0.0f) {
1780 layer->forceClientComposition(*displayId);
1781 }
1782
Dominik Laskowski075d3172018-05-24 15:50:06 -07001783 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001784 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001786 continue;
1787 }
1788
Dominik Laskowski075d3172018-05-24 15:50:06 -07001789 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1790 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
1792
Peiyong Lin13effd12018-07-24 17:01:47 -07001793 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 ColorMode colorMode;
1795 Dataspace dataSpace;
1796 RenderIntent renderIntent;
1797 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1798 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1799 }
1800 }
1801
1802 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001803
1804 for (const auto& [token, display] : mDisplays) {
1805 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001806 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001807 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001808
1809 if (displayId) {
1810 if (!layer->setHwcLayer(*displayId)) {
1811 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1812 }
1813 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001814 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815
Dominik Laskowski05275f12018-11-01 15:03:24 -07001816 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001817 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1818 }
1819 }
David Sodman79bba0e2018-08-05 18:07:49 -07001820}
1821
David Sodmanfa9b2af2017-12-24 13:28:59 -08001822void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823{
1824 // is debugging enabled
1825 if (CC_LIKELY(!mDebugRegion))
1826 return;
1827
David Sodmanfa9b2af2017-12-24 13:28:59 -08001828 if (display->isPoweredOn()) {
1829 // transform the dirty region into this screen's coordinate space
1830 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1831 if (!dirtyRegion.isEmpty()) {
1832 // redraw the whole screen
1833 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834
David Sodmanfa9b2af2017-12-24 13:28:59 -08001835 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001837 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001838
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001839 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840 }
1841 }
1842
David Sodmanfa9b2af2017-12-24 13:28:59 -08001843 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844
1845 if (mDebugRegion > 1) {
1846 usleep(mDebugRegion * 1000);
1847 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001848
Dominik Laskowski05275f12018-11-01 15:03:24 -07001849 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850}
1851
Adrian Roos1e1a1282017-11-01 19:05:31 +01001852void SurfaceFlinger::doTracing(const char* where) {
1853 ATRACE_CALL();
1854 ATRACE_NAME(where);
1855 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001856 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001857 }
1858}
1859
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001860void SurfaceFlinger::logLayerStats() {
1861 ATRACE_CALL();
1862 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001863 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001864 if (display->isPrimary()) {
1865 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001866 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001867 }
1868 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001869
1870 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001871 }
1872}
1873
David Sodman2b406362017-12-15 13:33:47 -08001874void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 ATRACE_CALL();
1877 ALOGV("preComposition");
1878
David Sodman2b406362017-12-15 13:33:47 -08001879 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1880
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001882 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001883 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884 needExtraInvalidate = true;
1885 }
Robert Carr2047fae2016-11-28 14:09:09 -08001886 });
1887
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 if (needExtraInvalidate) {
1889 signalLayerUpdate();
1890 }
1891}
1892
Ana Krulece588e312018-09-18 12:32:24 -07001893void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1894 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001895 // Update queue of past composite+present times and determine the
1896 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001897 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001899 while (!getBE().mCompositePresentTimes.empty()) {
1900 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001901 // Cached values should have been updated before calling this method,
1902 // which helps avoid duplicate syscalls.
1903 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1904 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1905 break;
1906 }
1907 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001908 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 }
1910
1911 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001912 while (getBE().mCompositePresentTimes.size() > 16) {
1913 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914 }
1915
Ana Krulece588e312018-09-18 12:32:24 -07001916 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001917}
1918
Ana Krulece588e312018-09-18 12:32:24 -07001919void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1920 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // Integer division and modulo round toward 0 not -inf, so we need to
1922 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001923 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1924 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1925 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926
Brian Andersond0010582017-03-07 13:20:31 -08001927 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1928 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001929 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001930 }
1931
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932 // Snap the latency to a value that removes scheduling jitter from the
1933 // composition and present times, which often have >1ms of jitter.
1934 // Reducing jitter is important if an app attempts to extrapolate
1935 // something (such as user input) to an accurate diasplay time.
1936 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1937 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001938 nsecs_t bias = stats.vsyncPeriod / 2;
1939 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1940 nsecs_t snappedCompositeToPresentLatency =
1941 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942
David Sodman99974d22017-11-28 12:04:33 -08001943 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001944 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1945 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001946 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947}
1948
Ady Abraham8164d482019-01-11 14:47:59 -08001949// debug patch for b/119477596 - add stack guards to catch stack
1950// corruptions and disable clang optimizations.
1951// The code below is temporary and planned to be removed once stack
1952// corruptions are found.
1953#pragma clang optimize off
1954class StackGuard {
1955public:
1956 StackGuard(const char* name, const char* func, int line) {
1957 guarders.reserve(MIN_CAPACITY);
1958 guarders.push_back({this, name, func, line});
1959 validate();
1960 }
1961 ~StackGuard() {
1962 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1963 if (i->guard == this) {
1964 guarders.erase(i);
1965 break;
1966 }
1967 }
1968 }
1969
1970 static void validate() {
1971 for (const auto& guard : guarders) {
1972 if (guard.guard->cookie != COOKIE_VALUE) {
1973 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1974 CallStack stack(LOG_TAG);
1975 abort();
1976 }
1977 }
1978 }
1979
1980private:
1981 uint64_t cookie = COOKIE_VALUE;
1982 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1983 static constexpr size_t MIN_CAPACITY = 16;
1984
1985 struct GuarderElement {
1986 StackGuard* guard;
1987 const char* name;
1988 const char* func;
1989 int line;
1990 };
1991
1992 static std::vector<GuarderElement> guarders;
1993};
1994std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1995
1996#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1997
1998#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001999void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000{
Ady Abraham8164d482019-01-11 14:47:59 -08002001 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 ATRACE_CALL();
2003 ALOGV("postComposition");
2004
Brian Anderson3546a3f2016-07-14 11:51:14 -07002005 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002006 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002007 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002008 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002009 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002010 }
Ady Abraham8164d482019-01-11 14:47:59 -08002011 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002014 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002015 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016
David Sodman73beded2017-11-15 11:56:06 -08002017 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002019 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2020
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002021 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002024 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 } else {
2026 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2027 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028
Ady Abraham8164d482019-01-11 14:47:59 -08002029 ASSERT_ON_STACK_GUARD();
2030
David Sodman73beded2017-11-15 11:56:06 -08002031 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002032 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002033 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002034 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002035 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002036 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037
Ana Krulece588e312018-09-18 12:32:24 -07002038 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002039 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002040 if (mUseScheduler) {
2041 mScheduler->getDisplayStatInfo(&stats);
2042 } else {
2043 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2044 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2045 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002046
Ady Abraham8164d482019-01-11 14:47:59 -08002047 ASSERT_ON_STACK_GUARD();
2048
David Sodman2b406362017-12-15 13:33:47 -08002049 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 // when we started doing work for this frame, but that should be okay
2051 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002052 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002053 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002054 DEFINE_STACK_GUARD(compositorTiming);
2055
Brian Andersond0010582017-03-07 13:20:31 -08002056 {
David Sodman99974d22017-11-28 12:04:33 -08002057 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002058 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002059 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002060
2061 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002062 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063
Robert Carr2047fae2016-11-28 14:09:09 -08002064 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002065 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2066 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002068 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002069 recordBufferingStats(layer->getName().string(),
2070 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002071 }
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002073 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002074
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002075 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002076 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002077 if (mUseScheduler) {
2078 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002079 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002080 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002081 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2082 enableHardwareVsync();
2083 } else {
2084 disableHardwareVsync(false);
2085 }
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002087 }
2088 }
2089
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002090 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002091 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002092 if (mUseScheduler) {
2093 mScheduler->enableHardwareVsync();
2094 } else {
2095 enableHardwareVsync();
2096 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002097 }
2098 }
2099
Ady Abraham8164d482019-01-11 14:47:59 -08002100 ASSERT_ON_STACK_GUARD();
2101
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 if (mAnimCompositionPending) {
2103 mAnimCompositionPending = false;
2104
Brian Anderson4e606e32017-03-16 15:34:57 -07002105 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002106 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002107 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002108
2109 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002110 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002111 // The HWC doesn't support present fences, so use the refresh
2112 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002113 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002114 DEFINE_STACK_GUARD(presentTime);
2115
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002117 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002118 }
2119 mAnimFrameTracker.advanceFrame();
2120 }
Dan Stozab90cf072015-03-05 11:05:59 -08002121
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
2123
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002124 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002125 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002126 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002127 }
2128
Ady Abraham8164d482019-01-11 14:47:59 -08002129 ASSERT_ON_STACK_GUARD();
2130
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002131 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002132
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
2134
Dominik Laskowski075d3172018-05-24 15:50:06 -07002135 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002136 return;
2137 }
2138
2139 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002140 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002141 if (mHasPoweredOff) {
2142 mHasPoweredOff = false;
2143 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002144 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002146 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002147 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002148 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2149 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002150 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002151 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002152 }
David Sodman4a36e932017-11-07 14:29:47 -08002153 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002154
2155 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002156 }
David Sodman4a36e932017-11-07 14:29:47 -08002157 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002158 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002159
2160 {
2161 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002162 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002163 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002164 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002165 if (refillCount > 0) {
2166 const size_t offset = mTexturePool.size();
2167 mTexturePool.resize(mTexturePoolSize);
2168 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2169 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2170 }
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002172 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002173
Marissa Wallfda30bb2018-10-12 11:34:28 -07002174 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002175 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002176
2177 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002178}
Ady Abraham8164d482019-01-11 14:47:59 -08002179#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002180
2181void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 ATRACE_CALL();
2183 ALOGV("rebuildLayerStacks");
2184
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002185 // We need to clear these out now as these may be holding on to a
2186 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2187 // also holds a reference. When the set of visible layers is recomputed,
2188 // some layers may be destroyed if the only thing keeping them alive was
2189 // that list of visible layers associated with each display. The layer
2190 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2191 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2192 for (const auto& [token, display] : mDisplays) {
2193 getBE().mCompositionInfo[token].clear();
2194 }
2195
Mathias Agopiancd60f992012-08-16 16:28:27 -07002196 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002197 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002198 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002199 mVisibleRegionsDirty = false;
2200 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002201
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002202 for (const auto& pair : mDisplays) {
2203 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 Region opaqueRegion;
2205 Region dirtyRegion;
2206 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002207 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002208 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 const Rect bounds = display->getBounds();
2210 if (display->isPoweredOn()) {
2211 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002212
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002214 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002216 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002217 Region drawRegion(tr.transform(
2218 layer->visibleNonTransparentRegion));
2219 drawRegion.andSelf(bounds);
2220 if (!drawRegion.isEmpty()) {
2221 layersSortedByZ.add(layer);
2222 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002223 // Clear out the HWC layer if this layer was
2224 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002225 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002226 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002227 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002228 // WM changes display->layerStack upon sleep/awake.
2229 // Here we make sure we delete the HWC layers even if
2230 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002231 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002232 }
2233
2234 // If a layer is not going to get a release fence because
2235 // it is invisible, but it is also going to release its
2236 // old buffer, add it to the list of layers needing
2237 // fences.
2238 if (hwcLayerDestroyed) {
2239 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2240 mLayersWithQueuedFrames.cend(), layer);
2241 if (found != mLayersWithQueuedFrames.cend()) {
2242 layersNeedingFences.add(layer);
2243 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002244 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 });
2246 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 display->setVisibleLayersSortedByZ(layersSortedByZ);
2248 display->setLayersNeedingFences(layersNeedingFences);
2249 display->undefinedRegion.set(bounds);
2250 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2251 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002252 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002255
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002256// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002258// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002260// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261// The returned HDR data space is one of
2262// - Dataspace::UNKNOWN
2263// - Dataspace::BT2020_HLG
2264// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2266 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002267 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002268 *outHdrDataSpace = Dataspace::UNKNOWN;
2269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002270 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002271 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 case Dataspace::V0_SCRGB:
2273 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002274 case Dataspace::BT2020:
2275 case Dataspace::BT2020_ITU:
2276 case Dataspace::BT2020_LINEAR:
2277 case Dataspace::DISPLAY_BT2020:
2278 bestDataSpace = Dataspace::DISPLAY_BT2020;
2279 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002280 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002281 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 case Dataspace::BT2020_PQ:
2284 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002285 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002287 case Dataspace::BT2020_HLG:
2288 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002289 // When there's mixed PQ content and HLG content, we set the HDR
2290 // data space to be BT2020_PQ and convert HLG to PQ.
2291 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2292 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002293 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294 break;
2295 default:
2296 break;
2297 }
Romain Guy54f154a2017-10-24 21:40:32 +01002298 }
2299
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002301}
2302
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002304void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2305 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002306 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2307 *outMode = ColorMode::NATIVE;
2308 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002309 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002311 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002312
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002314 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315
Peiyong Lindfde5112018-06-05 10:58:41 -07002316 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002317 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002318 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002319 if (isHdr) {
2320 bestDataSpace = hdrDataSpace;
2321 }
2322
Chia-I Wu0d711262018-05-21 15:19:35 -07002323 RenderIntent intent;
2324 switch (mDisplayColorSetting) {
2325 case DisplayColorSetting::MANAGED:
2326 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002327 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002328 break;
2329 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002330 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002331 break;
2332 default: // vendor display color setting
2333 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2334 break;
2335 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002338}
2339
David Sodmanfa9b2af2017-12-24 13:28:59 -08002340void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002341{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002342 bool dirty = !display->getDirtyRegion(false).isEmpty();
2343 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2344 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002345
David Sodmanfa9b2af2017-12-24 13:28:59 -08002346 // If nothing has changed (!dirty), don't recompose.
2347 // If something changed, but we don't currently have any visible layers,
2348 // and didn't when we last did a composition, then skip it this time.
2349 // The second rule does two things:
2350 // - When all layers are removed from a display, we'll emit one black
2351 // frame, then nothing more until we get new layers.
2352 // - When a display is created with a private layer stack, we won't
2353 // emit any black frames until a layer is added to the layer stack.
2354 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002355
Dominik Laskowski075d3172018-05-24 15:50:06 -07002356 const char flagPrefix[] = {'-', '+'};
2357 static_cast<void>(flagPrefix);
2358 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2359 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2360 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002361
David Sodmanfa9b2af2017-12-24 13:28:59 -08002362 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002363
David Sodmanfa9b2af2017-12-24 13:28:59 -08002364 if (mustRecompose) {
2365 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002366 }
2367}
2368
David Sodmanfa9b2af2017-12-24 13:28:59 -08002369void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002370{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371 if (!display->isPoweredOn()) {
2372 return;
David Sodman2b406362017-12-15 13:33:47 -08002373 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002374
Dominik Laskowski05275f12018-11-01 15:03:24 -07002375 status_t result = display->prepareFrame(getHwComposer(),
2376 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002377 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2378 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002379}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002380
David Sodmanfa9b2af2017-12-24 13:28:59 -08002381void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002382 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 ALOGV("doComposition");
2384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 if (display->isPoweredOn()) {
2386 // transform the dirty region into this screen's coordinate space
2387 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002388
David Sodmanfa9b2af2017-12-24 13:28:59 -08002389 // repaint the framebuffer (if needed)
2390 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392 display->dirtyRegion.clear();
2393 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002394 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002396}
2397
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398void SurfaceFlinger::postFrame()
2399{
2400 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 const auto display = getDefaultDisplayDeviceLocked();
2402 if (display && getHwComposer().isConnected(*display->getId())) {
2403 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002404 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2405 logFrameStats();
2406 }
2407 }
2408}
2409
2410void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411{
Mathias Agopian841cde52012-03-01 15:44:37 -08002412 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002414
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002416
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002418 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 if (displayId) {
2420 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002421 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002422 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002423 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002424 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002425
Chia-I Wu7b549592017-11-15 09:14:57 -08002426 // The layer buffer from the previous frame (if any) is released
2427 // by HWC only when the release fence from this frame (if any) is
2428 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 if (displayId && layer->hasHwcLayer(*displayId)) {
2430 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2431 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002432 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002433
2434 // If the layer was client composited in the previous frame, we
2435 // need to merge with the previous client target acquire fence.
2436 // Since we do not track that, always merge with the current
2437 // client target acquire fence when it is available, even though
2438 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002439 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002440 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002442 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002443
David Sodman15094112018-10-11 09:39:37 -07002444 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 }
Chia-I Wu83806892017-11-16 10:50:20 -08002446
2447 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002449 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002452 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002454 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002455 }
2456 }
2457
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (displayId) {
2459 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002460 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462}
2463
Mathias Agopian87baae12012-07-31 12:38:26 -07002464void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465{
Mathias Agopian841cde52012-03-01 15:44:37 -08002466 ATRACE_CALL();
2467
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002468 // here we keep a copy of the drawing state (that is the state that's
2469 // going to be overwritten by handleTransactionLocked()) outside of
2470 // mStateLock so that the side-effects of the State assignment
2471 // don't happen with mStateLock held (which can cause deadlocks).
2472 State drawingState(mDrawingState);
2473
Mathias Agopianca4d3602011-05-19 15:38:14 -07002474 Mutex::Autolock _l(mStateLock);
2475 const nsecs_t now = systemTime();
2476 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477
Mathias Agopianca4d3602011-05-19 15:38:14 -07002478 // Here we're guaranteed that some transaction flags are set
2479 // so we can call handleTransactionLocked() unconditionally.
2480 // We call getTransactionFlags(), which will also clear the flags,
2481 // with mStateLock held to guarantee that mCurrentState won't change
2482 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002483
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002484 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002485 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002487
Mathias Agopianca4d3602011-05-19 15:38:14 -07002488 mLastTransactionTime = systemTime() - now;
2489 mDebugInTransaction = 0;
2490 invalidateHwcGeometry();
2491 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002492}
2493
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2495 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 const std::optional<DisplayIdentificationInfo> info =
2497 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002500 continue;
2501 }
2502
Lloyd Piqueba04e622017-12-14 17:11:26 -08002503 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002505 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 mPhysicalDisplayTokens[info->id] = new BBinder();
2507 DisplayDeviceState state;
2508 state.displayId = info->id;
2509 state.isSecure = true; // All physical displays are currently considered secure.
2510 state.displayName = info->name;
2511 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2512 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002513 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002515 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002516
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2518 if (index >= 0) {
2519 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2520 mInterceptor->saveDisplayDeletion(state.sequenceId);
2521 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002522 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524 }
2525
2526 processDisplayChangesLocked();
2527 }
2528
2529 mPendingHotplugEvents.clear();
2530}
2531
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2534 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2535 const sp<IGraphicBufferProducer>& producer) {
2536 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002537 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002539 creationArgs.isSecure = state.isSecure;
2540 creationArgs.displaySurface = dispSurface;
2541 creationArgs.hasWideColorGamut = false;
2542 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002543
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2545 creationArgs.isPrimary = isInternalDisplay;
2546
2547 if (useColorManagement && displayId) {
2548 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002550 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002551 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002552 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002553
Dominik Laskowski7e045462018-05-30 13:02:02 -07002554 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 }
tangrobin6753a022018-08-10 10:58:54 +08002558 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 if (displayId) {
2561 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002564 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002565
Lloyd Pique90c115d2018-09-18 21:39:42 -07002566 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002567 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002568 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002569
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570 // Make sure that composition can never be stalled by a virtual display
2571 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002572 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002573 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2575 }
2576
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 creationArgs.displayInstallOrientation =
2578 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002579
Lloyd Pique99d3da52018-01-22 17:48:03 -08002580 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582
Lloyd Pique90c115d2018-09-18 21:39:42 -07002583 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584
2585 if (maxFrameBufferAcquiredBuffers >= 3) {
2586 nativeWindowSurface->preallocateBuffers();
2587 }
2588
2589 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002590 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002591 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002593 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002595 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002596 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 if (!state.isVirtual()) {
2598 LOG_ALWAYS_FATAL_IF(!displayId);
2599 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002600 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 display->setLayerStack(state.layerStack);
2603 display->setProjection(state.orientation, state.viewport, state.frame);
2604 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607}
2608
Lloyd Pique347200f2017-12-14 17:00:15 -08002609void SurfaceFlinger::processDisplayChangesLocked() {
2610 // here we take advantage of Vector's copy-on-write semantics to
2611 // improve performance by skipping the transaction entirely when
2612 // know that the lists are identical
2613 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2614 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2615 if (!curr.isIdenticalTo(draw)) {
2616 mVisibleRegionsDirty = true;
2617 const size_t cc = curr.size();
2618 size_t dc = draw.size();
2619
2620 // find the displays that were removed
2621 // (ie: in drawing state but not in current state)
2622 // also handle displays that changed
2623 // (ie: displays that are in both lists)
2624 for (size_t i = 0; i < dc;) {
2625 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2626 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 // Save display IDs before disconnecting.
2628 const auto internalDisplayId = getInternalDisplayId();
2629 const auto externalDisplayId = getExternalDisplayId();
2630
Lloyd Pique347200f2017-12-14 17:00:15 -08002631 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002632 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2633 display->disconnect(getHwComposer());
2634 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002636 if (mUseScheduler) {
2637 mScheduler->hotplugReceived(mAppConnectionHandle,
2638 EventThread::DisplayType::Primary, false);
2639 } else {
2640 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2641 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002643 if (mUseScheduler) {
2644 mScheduler->hotplugReceived(mAppConnectionHandle,
2645 EventThread::DisplayType::External, false);
2646 } else {
2647 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2648 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002649 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002650 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 } else {
2652 // this display is in both lists. see if something changed.
2653 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2656 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2657 if (state_binder != draw_binder) {
2658 // changing the surface is like destroying and
2659 // recreating the DisplayDevice, so we just remove it
2660 // from the drawing state, so that it get re-added
2661 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2663 display->disconnect(getHwComposer());
2664 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002666 mDrawingState.displays.removeItemsAt(i);
2667 dc--;
2668 // at this point we must loop to the next item
2669 continue;
2670 }
2671
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002675 }
2676 if ((state.orientation != draw[i].orientation) ||
2677 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002679 }
2680 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 }
2683 }
2684 }
2685 ++i;
2686 }
2687
2688 // find displays that were added
2689 // (ie: in current state but not in drawing state)
2690 for (size_t i = 0; i < cc; i++) {
2691 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2692 const DisplayDeviceState& state(curr[i]);
2693
2694 sp<DisplaySurface> dispSurface;
2695 sp<IGraphicBufferProducer> producer;
2696 sp<IGraphicBufferProducer> bqProducer;
2697 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002698 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002699
Dominik Laskowski075d3172018-05-24 15:50:06 -07002700 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002701 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 // Virtual displays without a surface are dormant:
2703 // they have external state (layer stack, projection,
2704 // etc.) but no internal state (i.e. a DisplayDevice).
2705 if (state.surface != nullptr) {
2706 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002707 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 int width = 0;
2709 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2710 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2711 int height = 0;
2712 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2713 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2714 int intFormat = 0;
2715 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2716 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002717 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718
Dominik Laskowski075d3172018-05-24 15:50:06 -07002719 displayId =
2720 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 }
2722
2723 // TODO: Plumb requested format back up to consumer
2724
2725 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002726 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 bqProducer, bqConsumer,
2728 state.displayName);
2729
2730 dispSurface = vds;
2731 producer = vds;
2732 }
2733 } else {
2734 ALOGE_IF(state.surface != nullptr,
2735 "adding a supported display, but rendering "
2736 "surface is provided (%p), ignoring it",
2737 state.surface.get());
2738
Dominik Laskowski075d3172018-05-24 15:50:06 -07002739 displayId = state.displayId;
2740 LOG_ALWAYS_FATAL_IF(!displayId);
2741 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 producer = bqProducer;
2743 }
2744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002747 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002748 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002749 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002750 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 LOG_ALWAYS_FATAL_IF(!displayId);
2752
2753 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002754 if (mUseScheduler) {
2755 mScheduler->hotplugReceived(mAppConnectionHandle,
2756 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002757 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002758 } else {
2759 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2760 true);
2761 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002762 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002763 if (mUseScheduler) {
2764 mScheduler->hotplugReceived(mAppConnectionHandle,
2765 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002766 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002767 } else {
2768 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2769 true);
2770 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002771 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 }
2773 }
2774 }
2775 }
2776 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002777
2778 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002779}
2780
Mathias Agopian87baae12012-07-31 12:38:26 -07002781void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002782{
Dan Stoza7dde5992015-05-22 09:51:44 -07002783 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002784 mCurrentState.traverseInZOrder([](Layer* layer) {
2785 layer->notifyAvailableFrames();
2786 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 /*
2789 * Traversal of the children
2790 * (perform the transaction for each of them if needed)
2791 */
2792
Robert Carr720e5062018-07-30 17:45:14 -07002793 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002794 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002795 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002797 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798
2799 const uint32_t flags = layer->doTransaction(0);
2800 if (flags & Layer::eVisibleRegion)
2801 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002802
2803 if (flags & Layer::eInputInfoChanged) {
2804 inputChanged = true;
2805 }
Robert Carr2047fae2016-11-28 14:09:09 -08002806 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 }
2808
2809 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 */
2812
Mathias Agopiane57f2922012-08-09 16:29:12 -07002813 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002814 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002815 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002818 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002819 // The transform hint might have changed for some layers
2820 // (either because a display has changed, or because a layer
2821 // as changed).
2822 //
2823 // Walk through all the layers in currentLayers,
2824 // and update their transform hint.
2825 //
2826 // If a layer is visible only on a single display, then that
2827 // display is used to calculate the hint, otherwise we use the
2828 // default display.
2829 //
2830 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2831 // the hint is set before we acquire a buffer from the surface texture.
2832 //
2833 // NOTE: layer transactions have taken place already, so we use their
2834 // drawing state. However, SurfaceFlinger's own transaction has not
2835 // happened yet, so we must use the current state layer list
2836 // (soon to become the drawing state list).
2837 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002839 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002840 bool first = true;
2841 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002842 // NOTE: we rely on the fact that layers are sorted by
2843 // layerStack first (so we don't have to traverse the list
2844 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002845 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002846 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002847 currentlayerStack = layerStack;
2848 // figure out if this layerstack is mirrored
2849 // (more than one display) if so, pick the default display,
2850 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 hintDisplay = nullptr;
2852 for (const auto& [token, display] : mDisplays) {
2853 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2854 if (hintDisplay) {
2855 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002856 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002859 }
2860 }
2861 }
2862 }
Chet Haase91d25932013-04-11 15:24:55 -07002863
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002865 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2866 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002867
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002868 // could be null when this layer is using a layerStack
2869 // that is not visible on any display. Also can occur at
2870 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002872 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002873
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002875 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 if (hintDisplay) {
2877 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002878 }
Robert Carr2047fae2016-11-28 14:09:09 -08002879
2880 first = false;
2881 });
Mathias Agopian84300952012-11-21 16:02:13 -08002882 }
2883
2884
Mathias Agopian3559b072012-08-15 13:46:03 -07002885 /*
2886 * Perform our own transaction if needed
2887 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888
2889 if (mLayersAdded) {
2890 mLayersAdded = false;
2891 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 mVisibleRegionsDirty = true;
2893 }
2894
2895 // some layers might have been removed, so
2896 // we need to update the regions they're exposing.
2897 if (mLayersRemoved) {
2898 mLayersRemoved = false;
2899 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002900 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002902 // this layer is not visible anymore
2903 // TODO: we could traverse the tree from front to back and
2904 // compute the actual visible region
2905 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 Region visibleReg;
2907 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002908 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002909 }
Robert Carr2047fae2016-11-28 14:09:09 -08002910 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911 }
2912
2913 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002914
Vishnu Nairde19f852018-12-18 16:11:53 -08002915 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002916 updateInputWindows();
2917 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002918 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002919
Riley Andrews03414a12014-07-01 14:22:59 -07002920 updateCursorAsync();
2921}
2922
Robert Carr720e5062018-07-30 17:45:14 -07002923void SurfaceFlinger::updateInputWindows() {
2924 ATRACE_CALL();
2925
Vishnu Nairde19f852018-12-18 16:11:53 -08002926 if (mInputFlinger == nullptr) {
2927 return;
2928 }
2929
Robert Carr720e5062018-07-30 17:45:14 -07002930 Vector<InputWindowInfo> inputHandles;
2931
2932 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2933 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002934 // When calculating the screen bounds we ignore the transparent region since it may
2935 // result in an unwanted offset.
2936 inputHandles.add(layer->fillInputInfo(
2937 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002938 }
2939 });
2940 mInputFlinger->setInputWindows(inputHandles);
2941}
2942
chaviwfbe5d9c2018-12-26 12:23:37 -08002943void SurfaceFlinger::executeInputWindowCommands() {
2944 if (!mInputFlinger) {
2945 return;
2946 }
2947
2948 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2949 if (transferTouchFocusCommand.fromToken != nullptr &&
2950 transferTouchFocusCommand.toToken != nullptr &&
2951 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2952 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2953 transferTouchFocusCommand.toToken);
2954 }
2955 }
2956
2957 mInputWindowCommands.clear();
2958}
2959
Riley Andrews03414a12014-07-01 14:22:59 -07002960void SurfaceFlinger::updateCursorAsync()
2961{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002962 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002963 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002964 continue;
2965 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002967 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2968 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002969 }
2970 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002971}
2972
chaviw61626f22018-11-15 16:26:27 -08002973void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2974 if (layer->hasReadyFrame()) {
2975 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2976 if (layer->shouldPresentNow(expectedPresentTime)) {
2977 bool ignored = false;
2978 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2979 }
2980 }
2981 layer->releasePendingBuffer(systemTime());
2982}
2983
Mathias Agopian4fec8732012-06-29 14:12:52 -07002984void SurfaceFlinger::commitTransaction()
2985{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002986 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002987 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 for (const auto& l : mLayersPendingRemoval) {
2989 recordBufferingStats(l->getName().string(),
2990 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002991
2992 // We need to release the HWC layers when the Layer is removed
2993 // from the current state otherwise the HWC layer just continues
2994 // showing at its last configured state until we eventually
2995 // abandon the buffer queue.
2996 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002997 l->destroyHwcLayersForAllDisplays();
2998 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 }
3001 mLayersPendingRemoval.clear();
3002 }
3003
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003004 // If this transaction is part of a window animation then the next frame
3005 // we composite should be considered an animation as well.
3006 mAnimCompositionPending = mAnimTransactionPending;
3007
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003009 // clear the "changed" flags in current state
3010 mCurrentState.colorMatrixChanged = false;
3011
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 mDrawingState.traverseInZOrder([](Layer* layer) {
3013 layer->commitChildList();
3014 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003015 mTransactionPending = false;
3016 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003017 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018}
3019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3021 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003022 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025 Region aboveOpaqueLayers;
3026 Region aboveCoveredLayers;
3027 Region dirty;
3028
Mathias Agopian87baae12012-07-31 12:38:26 -07003029 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030
Robert Carr2047fae2016-11-28 14:09:09 -08003031 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003032 // start with the whole surface at its current location
3033 const Layer::State& s(layer->getDrawingState());
3034
Jesse Hall01e29052013-02-19 16:13:35 -08003035 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003037 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003038 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003039
Mathias Agopianab028732010-03-16 16:41:46 -07003040 /*
3041 * opaqueRegion: area of a surface that is fully opaque.
3042 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003044
3045 /*
3046 * visibleRegion: area of a surface that is visible on screen
3047 * and not fully transparent. This is essentially the layer's
3048 * footprint minus the opaque regions above it.
3049 * Areas covered by a translucent surface are considered visible.
3050 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003052
3053 /*
3054 * coveredRegion: area of a surface that is covered by all
3055 * visible regions above it (which includes the translucent areas).
3056 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003058
Jesse Halla8026d22012-09-25 13:25:04 -07003059 /*
3060 * transparentRegion: area of a surface that is hinted to be completely
3061 * transparent. This is only used to tell when the layer has no visible
3062 * non-transparent regions and can be removed from the layer list. It
3063 * does not affect the visibleRegion of this layer or any layers
3064 * beneath it. The hint may not be correct if apps don't respect the
3065 * SurfaceView restrictions (which, sadly, some don't).
3066 */
3067 Region transparentRegion;
3068
Mathias Agopianab028732010-03-16 16:41:46 -07003069
3070 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003071 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003072 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003076 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003077 if (!visibleRegion.isEmpty()) {
3078 // Remove the transparent area from the visible region
3079 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003080 if (tr.preserveRects()) {
3081 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003082 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003083 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003084 // transformation too complex, can't do the
3085 // transparent region optimization.
3086 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003087 }
Mathias Agopianab028732010-03-16 16:41:46 -07003088 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089
Mathias Agopianab028732010-03-16 16:41:46 -07003090 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003092 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003093 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003094 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003095 // the opaque region is the layer's footprint
3096 opaqueRegion = visibleRegion;
3097 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 }
3099 }
3100
Robert Carre5f4f692018-01-12 13:12:28 -08003101 if (visibleRegion.isEmpty()) {
3102 layer->clearVisibilityRegions();
3103 return;
3104 }
3105
Mathias Agopianab028732010-03-16 16:41:46 -07003106 // Clip the covered region to the visible region
3107 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3108
3109 // Update aboveCoveredLayers for next (lower) layer
3110 aboveCoveredLayers.orSelf(visibleRegion);
3111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 // subtract the opaque region covered by the layers above us
3113 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114
3115 // compute this layer's dirty region
3116 if (layer->contentDirty) {
3117 // we need to invalidate the whole region
3118 dirty = visibleRegion;
3119 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003120 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 layer->contentDirty = false;
3122 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003123 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003124 * the exposed region consists of two components:
3125 * 1) what's VISIBLE now and was COVERED before
3126 * 2) what's EXPOSED now less what was EXPOSED before
3127 *
3128 * note that (1) is conservative, we start with the whole
3129 * visible region but only keep what used to be covered by
3130 * something -- which mean it may have been exposed.
3131 *
3132 * (2) handles areas that were not covered by anything but got
3133 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003134 */
Mathias Agopianab028732010-03-16 16:41:46 -07003135 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003136 const Region oldVisibleRegion = layer->visibleRegion;
3137 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003138 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3139 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 }
3141 dirty.subtractSelf(aboveOpaqueLayers);
3142
3143 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003144 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145
Mathias Agopianab028732010-03-16 16:41:46 -07003146 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003148
Jesse Halla8026d22012-09-25 13:25:04 -07003149 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 layer->setVisibleRegion(visibleRegion);
3151 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003152 layer->setVisibleNonTransparentRegion(
3153 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003154 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155
Mathias Agopian87baae12012-07-31 12:38:26 -07003156 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Chia-I Wuab0c3192017-08-01 11:29:00 -07003159void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003160 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003161 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3162 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003163 }
3164 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003165}
3166
Dan Stoza6b9454d2014-11-07 16:00:59 -08003167bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003169 ALOGV("handlePageFlip");
3170
Brian Andersond6927fb2016-07-23 23:37:30 -07003171 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003174 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003175 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003176
3177 // Store the set of layers that need updates. This set must not change as
3178 // buffers are being latched, as this could result in a deadlock.
3179 // Example: Two producers share the same command stream and:
3180 // 1.) Layer 0 is latched
3181 // 2.) Layer 0 gets a new frame
3182 // 2.) Layer 1 gets a new frame
3183 // 3.) Layer 1 is latched.
3184 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3185 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003186 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003187 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003188 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003189 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3190 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003191 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003192 } else {
3193 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003194 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003195 } else {
3196 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003197 }
Robert Carr2047fae2016-11-28 14:09:09 -08003198 });
3199
Lloyd Piquef2c79392018-12-20 16:23:33 -08003200 if (!mLayersWithQueuedFrames.empty()) {
3201 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3202 // writes to Layer current state. See also b/119481871
3203 Mutex::Autolock lock(mStateLock);
3204
3205 for (auto& layer : mLayersWithQueuedFrames) {
3206 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3207 layer->useSurfaceDamage();
3208 invalidateLayerStack(layer, dirty);
3209 if (layer->isBufferLatched()) {
3210 newDataLatched = true;
3211 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003212 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003213 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003214
Alec Mouri86770e52018-09-24 22:40:58 +00003215 // Clear the renderengine fence here...
3216 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3217 // clear instead of sp::clear.
3218 getBE().flushFence = Fence::NO_FENCE;
3219
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003220 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221
Vishnu Nairde19f852018-12-18 16:11:53 -08003222 if (visibleRegions) {
3223 // Update input window info if the layer receives its first buffer.
3224 updateInputWindows();
3225 }
3226
Dan Stoza6b9454d2014-11-07 16:00:59 -08003227 // If we will need to wake up at some time in the future to deal with a
3228 // queued frame that shouldn't be displayed during this vsync period, wake
3229 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003230 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231 signalLayerUpdate();
3232 }
3233
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003234 // enter boot animation on first buffer latch
3235 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3236 ALOGI("Enter boot animation");
3237 mBootStage = BootStage::BOOTANIMATION;
3238 }
3239
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003241 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Mathias Agopianad456f92011-01-13 17:53:01 -08003244void SurfaceFlinger::invalidateHwcGeometry()
3245{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003246 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003247}
3248
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003249void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003250 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003251 // We only need to actually compose the display if:
3252 // 1) It is being handled by hardware composer, which may need this to
3253 // keep its virtual display state machine in sync, or
3254 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003255 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003256 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003257 return;
3258 }
3259
Dan Stoza9e56aa02015-11-02 13:00:03 -08003260 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003261 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003262
3263 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003264 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265}
3266
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003267bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003268 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003270 const Region bounds(display->bounds());
3271 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003272 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003273 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003274 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003275
Peiyong Lind3788632018-09-18 16:01:31 -07003276 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003277 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003278
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003279 // Framebuffer will live in this scope for GPU composition.
3280 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3281
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 if (hasClientComposition) {
3283 ALOGV("hasClientComposition");
3284
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003285 sp<GraphicBuffer> buf = display->dequeueBuffer();
3286
3287 if (buf == nullptr) {
3288 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3289 "client composition for this frame",
3290 display->getDisplayName().c_str());
3291 return false;
3292 }
3293
3294 // Bind the framebuffer in this scope.
3295 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3296 buf->getNativeBuffer());
3297
3298 if (fbo->getStatus() != NO_ERROR) {
3299 ALOGW("Binding buffer for display [%s] failed with status: %d",
3300 display->getDisplayName().c_str(), fbo->getStatus());
3301 return false;
3302 }
3303
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003304 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003305 if (display->hasWideColorGamut()) {
3306 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003307 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003308 getRenderEngine().setOutputDataSpace(outputDataspace);
3309 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003310 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003311
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003313 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003314 getHwComposer()
3315 .hasDisplayCapability(displayId,
3316 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003317
Peiyong Lind3788632018-09-18 16:01:31 -07003318 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003319 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3320 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003321 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003322 }
3323
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003324 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003325
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003326 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003327 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003328 // when using overlays, we assume a fully transparent framebuffer
3329 // NOTE: we could reduce how much we need to clear, for instance
3330 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003331 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003332 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003333 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003334 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003335 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003336 // we're left with the letterbox region
3337 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003338 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003339
3340 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003341 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003342
Mathias Agopianb9494d52012-04-18 02:28:45 -07003343 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003344 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003345 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003346 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003347 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003348 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003349
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003350 const Rect& bounds = display->getBounds();
3351 const Rect& scissor = display->getScissor();
3352 if (scissor != bounds) {
3353 // scissor doesn't match the screen's dimensions, so we
3354 // need to clear everything outside of it and enable
3355 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003356
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003357 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003358 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003359 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003361
Mathias Agopian85d751c2012-08-29 16:59:24 -07003362 /*
3363 * and then, render the layers targeted at the framebuffer
3364 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003365
Dan Stoza9e56aa02015-11-02 13:00:03 -08003366 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003367 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003368 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003369 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003370 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003371 displayTransform.transform(layer->visibleRegion)));
3372 ALOGV("Layer: %s", layer->getName().string());
3373 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003374 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003375 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003376 case HWC2::Composition::Cursor:
3377 case HWC2::Composition::Device:
3378 case HWC2::Composition::Sideband:
3379 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003380 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003382 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003383 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003384 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003385 // never clear the very first layer since we're
3386 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003387 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003388 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003389 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003390 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003391 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003392 if (layer->hasColorTransform()) {
3393 mat4 tmpMatrix;
3394 if (applyColorMatrix) {
3395 tmpMatrix = mDrawingState.colorMatrix;
3396 }
3397 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003398 getRenderEngine().setColorTransform(tmpMatrix);
3399 } else {
3400 getRenderEngine().setColorTransform(colorMatrix);
3401 }
David Sodmanc1498e62018-09-12 14:36:26 -07003402 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003403 break;
3404 }
3405 default:
3406 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003407 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 } else {
3409 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003410 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003412 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003413
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003414 // Perform some cleanup steps if we used client composition.
3415 if (hasClientComposition) {
3416 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003417 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003418 display->finishBuffer();
3419 // Clear out error flags here so that we don't wait until next
3420 // composition to log.
3421 getRenderEngine().checkErrors();
3422 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003423 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424}
3425
Chia-I Wu28e3a252018-09-07 12:05:02 -07003426void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003427 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003428 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003429}
3430
Dan Stoza7d89d062015-04-30 13:29:25 -07003431status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003432 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003433 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003434 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003435 const sp<Layer>& parent,
3436 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003437{
Dan Stoza7d89d062015-04-30 13:29:25 -07003438 // add this layer to the current state list
3439 {
3440 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003441 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003442 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3443 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003444 return NO_MEMORY;
3445 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003446 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003447 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003448 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003449 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003450 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003451 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003452 parent->addChild(lbc);
3453 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003454
Yiwei Zhang243b3782018-05-15 17:40:04 -07003455 if (gbc != nullptr) {
3456 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3457 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3458 mMaxGraphicBufferProducerListSize,
3459 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3460 mGraphicBufferProducerList.size(),
3461 mMaxGraphicBufferProducerListSize, mNumLayers);
3462 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003464 }
3465
Mathias Agopian96f08192010-06-02 23:28:45 -07003466 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003467 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003468
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003470}
3471
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003472uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003473 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003474}
3475
Mathias Agopian3f844832013-08-07 21:24:32 -07003476uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003477 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478}
3479
Mathias Agopian3f844832013-08-07 21:24:32 -07003480uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003481 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003482}
3483
3484uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003485 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003486 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003487 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003489 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490 }
3491 return old;
3492}
3493
Marissa Wall713b63f2018-10-17 15:42:43 -07003494bool SurfaceFlinger::flushTransactionQueues() {
3495 Mutex::Autolock _l(mStateLock);
3496 auto it = mTransactionQueues.begin();
3497 while (it != mTransactionQueues.end()) {
3498 auto& [applyToken, transactionQueue] = *it;
3499
3500 while (!transactionQueue.empty()) {
3501 const auto& [states, displays, flags] = transactionQueue.front();
3502 if (composerStateContainsUnsignaledFences(states)) {
3503 break;
3504 }
chaviw273171b2018-12-26 11:46:30 -08003505 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003506 transactionQueue.pop();
3507 }
3508
3509 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3510 }
3511 return mTransactionQueues.empty();
3512}
3513
chaviwca27f252018-02-06 16:46:39 -08003514bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3515 for (const ComposerState& state : states) {
3516 // Here we need to check that the interface we're given is indeed
3517 // one of our own. A malicious client could give us a nullptr
3518 // IInterface, or one of its own or even one of our own but a
3519 // different type. All these situations would cause us to crash.
3520 if (state.client == nullptr) {
3521 return true;
3522 }
3523
3524 sp<IBinder> binder = IInterface::asBinder(state.client);
3525 if (binder == nullptr) {
3526 return true;
3527 }
3528
3529 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3530 return true;
3531 }
3532 }
3533 return false;
3534}
3535
Marissa Wall713b63f2018-10-17 15:42:43 -07003536bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3537 for (const ComposerState& state : states) {
3538 const layer_state_t& s = state.state;
3539 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3540 continue;
3541 }
3542 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3543 return true;
3544 }
3545 }
3546 return false;
3547}
3548
3549void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3550 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003551 const sp<IBinder>& applyToken,
3552 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003553 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003554 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003555
chaviwca27f252018-02-06 16:46:39 -08003556 if (containsAnyInvalidClientState(states)) {
3557 return;
3558 }
3559
Marissa Wall713b63f2018-10-17 15:42:43 -07003560 // If its TransactionQueue already has a pending TransactionState or if it is pending
3561 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3562 composerStateContainsUnsignaledFences(states)) {
3563 mTransactionQueues[applyToken].emplace(states, displays, flags);
3564 setTransactionFlags(eTransactionNeeded);
3565 return;
3566 }
3567
chaviw273171b2018-12-26 11:46:30 -08003568 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003569}
3570
3571void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003572 const Vector<DisplayState>& displays, uint32_t flags,
3573 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003574 uint32_t transactionFlags = 0;
3575
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003576 if (flags & eAnimation) {
3577 // For window updates that are part of an animation we must wait for
3578 // previous animation "frames" to be handled.
3579 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003580 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003581 if (CC_UNLIKELY(err != NO_ERROR)) {
3582 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003583 // caller after a few seconds.
3584 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3585 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003586 mAnimTransactionPending = false;
3587 break;
3588 }
3589 }
3590 }
3591
chaviwca27f252018-02-06 16:46:39 -08003592 for (const DisplayState& display : displays) {
3593 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003594 }
3595
Marissa Walle2ffb422018-10-12 11:33:52 -07003596 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003597 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003598 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003599 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003600 // If the state doesn't require a traversal and there are callbacks, send them now
3601 if (!(clientStateFlags & eTraversalNeeded)) {
3602 mTransactionCompletedThread.sendCallbacks();
3603 }
3604 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003605
chaviw273171b2018-12-26 11:46:30 -08003606 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3607
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003608 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3609 // anyway. This can be used as a flush mechanism for previous async transactions.
3610 // Empty animation transaction can be used to simulate back-pressure, so also force a
3611 // transaction for empty animation transactions.
3612 if (transactionFlags == 0 &&
3613 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003614 transactionFlags = eTransactionNeeded;
3615 }
3616
Mathias Agopian386aa982011-11-07 21:58:03 -08003617 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003618 if (mInterceptor->isEnabled()) {
3619 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003620 }
Irvel468051e2016-06-13 16:44:44 -07003621
Mathias Agopian386aa982011-11-07 21:58:03 -08003622 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003623 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3624 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003625 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003626
3627 // if this is a synchronous transaction, wait for it to take effect
3628 // before returning.
3629 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003631 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003632 if (flags & eAnimation) {
3633 mAnimTransactionPending = true;
3634 }
3635 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003636 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3637 if (CC_UNLIKELY(err != NO_ERROR)) {
3638 // just in case something goes wrong in SF, return to the
3639 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003640 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3641 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003642 break;
3643 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645 }
3646}
3647
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003648uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3649 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3650 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003651
Mathias Agopiane57f2922012-08-09 16:29:12 -07003652 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003653 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3654
3655 const uint32_t what = s.what;
3656 if (what & DisplayState::eSurfaceChanged) {
3657 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3658 state.surface = s.surface;
3659 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003660 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003661 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003662 if (what & DisplayState::eLayerStackChanged) {
3663 if (state.layerStack != s.layerStack) {
3664 state.layerStack = s.layerStack;
3665 flags |= eDisplayTransactionNeeded;
3666 }
3667 }
3668 if (what & DisplayState::eDisplayProjectionChanged) {
3669 if (state.orientation != s.orientation) {
3670 state.orientation = s.orientation;
3671 flags |= eDisplayTransactionNeeded;
3672 }
3673 if (state.frame != s.frame) {
3674 state.frame = s.frame;
3675 flags |= eDisplayTransactionNeeded;
3676 }
3677 if (state.viewport != s.viewport) {
3678 state.viewport = s.viewport;
3679 flags |= eDisplayTransactionNeeded;
3680 }
3681 }
3682 if (what & DisplayState::eDisplaySizeChanged) {
3683 if (state.width != s.width) {
3684 state.width = s.width;
3685 flags |= eDisplayTransactionNeeded;
3686 }
3687 if (state.height != s.height) {
3688 state.height = s.height;
3689 flags |= eDisplayTransactionNeeded;
3690 }
3691 }
3692
Mathias Agopiane57f2922012-08-09 16:29:12 -07003693 return flags;
3694}
3695
Robert Carrd4ae7f32018-06-07 16:10:57 -07003696bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3697 IPCThreadState* ipc = IPCThreadState::self();
3698 const int pid = ipc->getCallingPid();
3699 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003700 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003701 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003702 return false;
3703 }
3704 return true;
3705}
3706
chaviwca27f252018-02-06 16:46:39 -08003707uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3708 const layer_state_t& s = composerState.state;
3709 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3710
Mathias Agopian13127d82013-03-05 17:47:11 -08003711 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003712 if (layer == nullptr) {
3713 return 0;
3714 }
3715
chaviw8b3871a2017-11-01 17:41:01 -07003716 uint32_t flags = 0;
3717
Garfield Tan8a3083e2018-12-03 13:21:07 -08003718 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003719 bool geometryAppliesWithResize =
3720 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003721
3722 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3723 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003724 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003725 layer->pushPendingState();
3726 }
3727
chaviw8b3871a2017-11-01 17:41:01 -07003728 if (what & layer_state_t::ePositionChanged) {
3729 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3730 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003731 }
chaviw8b3871a2017-11-01 17:41:01 -07003732 }
3733 if (what & layer_state_t::eLayerChanged) {
3734 // NOTE: index needs to be calculated before we update the state
3735 const auto& p = layer->getParent();
3736 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003737 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003738 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003739 mCurrentState.layersSortedByZ.removeAt(idx);
3740 mCurrentState.layersSortedByZ.add(layer);
3741 // we need traversal (state changed)
3742 // AND transaction (list changed)
3743 flags |= eTransactionNeeded|eTraversalNeeded;
3744 }
chaviw8b3871a2017-11-01 17:41:01 -07003745 } else {
3746 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003747 flags |= eTransactionNeeded|eTraversalNeeded;
3748 }
3749 }
chaviw8b3871a2017-11-01 17:41:01 -07003750 }
3751 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003752 // NOTE: index needs to be calculated before we update the state
3753 const auto& p = layer->getParent();
3754 if (p == nullptr) {
3755 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3756 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3757 mCurrentState.layersSortedByZ.removeAt(idx);
3758 mCurrentState.layersSortedByZ.add(layer);
3759 // we need traversal (state changed)
3760 // AND transaction (list changed)
3761 flags |= eTransactionNeeded|eTraversalNeeded;
3762 }
3763 } else {
3764 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3765 flags |= eTransactionNeeded|eTraversalNeeded;
3766 }
chaviw8b3871a2017-11-01 17:41:01 -07003767 }
3768 }
3769 if (what & layer_state_t::eSizeChanged) {
3770 if (layer->setSize(s.w, s.h)) {
3771 flags |= eTraversalNeeded;
3772 }
3773 }
3774 if (what & layer_state_t::eAlphaChanged) {
3775 if (layer->setAlpha(s.alpha))
3776 flags |= eTraversalNeeded;
3777 }
3778 if (what & layer_state_t::eColorChanged) {
3779 if (layer->setColor(s.color))
3780 flags |= eTraversalNeeded;
3781 }
Peiyong Lind3788632018-09-18 16:01:31 -07003782 if (what & layer_state_t::eColorTransformChanged) {
3783 if (layer->setColorTransform(s.colorTransform)) {
3784 flags |= eTraversalNeeded;
3785 }
3786 }
chaviw8b3871a2017-11-01 17:41:01 -07003787 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003788 // TODO: b/109894387
3789 //
3790 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3791 // rotation. To see the problem observe that if we have a square parent, and a child
3792 // of the same size, then we rotate the child 45 degrees around it's center, the child
3793 // must now be cropped to a non rectangular 8 sided region.
3794 //
3795 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3796 // private API, and the WindowManager only uses rotation in one case, which is on a top
3797 // level layer in which cropping is not an issue.
3798 //
3799 // However given that abuse of rotation matrices could lead to surfaces extending outside
3800 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3801 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3802 // transformations.
3803 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003804 flags |= eTraversalNeeded;
3805 }
3806 if (what & layer_state_t::eTransparentRegionChanged) {
3807 if (layer->setTransparentRegionHint(s.transparentRegion))
3808 flags |= eTraversalNeeded;
3809 }
3810 if (what & layer_state_t::eFlagsChanged) {
3811 if (layer->setFlags(s.flags, s.mask))
3812 flags |= eTraversalNeeded;
3813 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003814 if (what & layer_state_t::eCropChanged_legacy) {
3815 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003816 flags |= eTraversalNeeded;
3817 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003818 if (what & layer_state_t::eCornerRadiusChanged) {
3819 if (layer->setCornerRadius(s.cornerRadius))
3820 flags |= eTraversalNeeded;
3821 }
chaviw8b3871a2017-11-01 17:41:01 -07003822 if (what & layer_state_t::eLayerStackChanged) {
3823 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3824 // We only allow setting layer stacks for top level layers,
3825 // everything else inherits layer stack from its parent.
3826 if (layer->hasParent()) {
3827 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3828 layer->getName().string());
3829 } else if (idx < 0) {
3830 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3831 "that also does not appear in the top level layer list. Something"
3832 " has gone wrong.", layer->getName().string());
3833 } else if (layer->setLayerStack(s.layerStack)) {
3834 mCurrentState.layersSortedByZ.removeAt(idx);
3835 mCurrentState.layersSortedByZ.add(layer);
3836 // we need traversal (state changed)
3837 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003838 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003839 }
3840 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003841 if (what & layer_state_t::eDeferTransaction_legacy) {
3842 if (s.barrierHandle_legacy != nullptr) {
3843 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3844 } else if (s.barrierGbp_legacy != nullptr) {
3845 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003846 if (authenticateSurfaceTextureLocked(gbp)) {
3847 const auto& otherLayer =
3848 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003849 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003850 } else {
3851 ALOGE("Attempt to defer transaction to to an"
3852 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003853 }
3854 }
chaviw8b3871a2017-11-01 17:41:01 -07003855 // We don't trigger a traversal here because if no other state is
3856 // changed, we don't want this to cause any more work
3857 }
3858 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003859 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003860 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003861 if (!hadParent) {
3862 mCurrentState.layersSortedByZ.remove(layer);
3863 }
chaviw8b3871a2017-11-01 17:41:01 -07003864 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003865 }
chaviw8b3871a2017-11-01 17:41:01 -07003866 }
3867 if (what & layer_state_t::eReparentChildren) {
3868 if (layer->reparentChildren(s.reparentHandle)) {
3869 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003870 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003871 }
chaviw8b3871a2017-11-01 17:41:01 -07003872 if (what & layer_state_t::eDetachChildren) {
3873 layer->detachChildren();
3874 }
3875 if (what & layer_state_t::eOverrideScalingModeChanged) {
3876 layer->setOverrideScalingMode(s.overrideScalingMode);
3877 // We don't trigger a traversal here because if no other state is
3878 // changed, we don't want this to cause any more work
3879 }
Marissa Wall61c58622018-07-18 10:12:20 -07003880 if (what & layer_state_t::eTransformChanged) {
3881 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3882 }
3883 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3884 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3885 flags |= eTraversalNeeded;
3886 }
3887 if (what & layer_state_t::eCropChanged) {
3888 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3889 }
Marissa Wall861616d2018-10-22 12:52:23 -07003890 if (what & layer_state_t::eFrameChanged) {
3891 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3892 }
Marissa Wall61c58622018-07-18 10:12:20 -07003893 if (what & layer_state_t::eBufferChanged) {
3894 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3895 }
3896 if (what & layer_state_t::eAcquireFenceChanged) {
3897 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3898 }
3899 if (what & layer_state_t::eDataspaceChanged) {
3900 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3901 }
3902 if (what & layer_state_t::eHdrMetadataChanged) {
3903 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3904 }
3905 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3906 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3907 }
3908 if (what & layer_state_t::eApiChanged) {
3909 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3910 }
3911 if (what & layer_state_t::eSidebandStreamChanged) {
3912 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3913 }
Robert Carr720e5062018-07-30 17:45:14 -07003914 if (what & layer_state_t::eInputInfoChanged) {
3915 layer->setInputInfo(s.inputInfo);
3916 flags |= eTraversalNeeded;
3917 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003918 std::vector<sp<CallbackHandle>> callbackHandles;
3919 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3920 mTransactionCompletedThread.run();
3921 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3922 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3923 }
3924 }
3925 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3926 // Do not put anything that updates layer state or modifies flags after
3927 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003928 return flags;
3929}
3930
chaviw273171b2018-12-26 11:46:30 -08003931uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3932 uint32_t flags = 0;
3933 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3934 flags |= eTraversalNeeded;
3935 }
3936
3937 mInputWindowCommands.merge(inputWindowCommands);
3938 return flags;
3939}
3940
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003941status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003942 const String8& name,
3943 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003944 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003945 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003946 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003948 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003949 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003950 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003951 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003952 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003953
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 status_t result = NO_ERROR;
3955
3956 sp<Layer> layer;
3957
Cody Northropbc755282017-03-31 12:00:08 -06003958 String8 uniqueName = getUniqueLayerName(name);
3959
Mathias Agopian3165cc22012-08-08 19:42:09 -07003960 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003961 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003962 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3963 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003964
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003966 case ISurfaceComposerClient::eFXSurfaceBufferState:
3967 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3968 break;
chaviw13fdc492017-06-27 12:40:18 -07003969 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003970 // check if buffer size is set for color layer.
3971 if (w > 0 || h > 0) {
3972 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3973 int(w), int(h));
3974 return BAD_VALUE;
3975 }
3976
chaviw13fdc492017-06-27 12:40:18 -07003977 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003978 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003979 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003980 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003981 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003982 // check if buffer size is set for container layer.
3983 if (w > 0 || h > 0) {
3984 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3985 int(w), int(h));
3986 return BAD_VALUE;
3987 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003988 result = createContainerLayer(client,
3989 uniqueName, w, h, flags,
3990 handle, &layer);
3991 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003992 default:
3993 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 break;
3995 }
3996
Dan Stoza7d89d062015-04-30 13:29:25 -07003997 if (result != NO_ERROR) {
3998 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003999 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004000
Chia-I Wuab0c3192017-08-01 11:29:00 -07004001 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4002 // TODO b/64227542
4003 if (windowType == 441731) {
4004 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4005 layer->setPrimaryDisplayOnly();
4006 }
4007
Albert Chaulk479c60c2017-01-27 14:21:34 -05004008 layer->setInfo(windowType, ownerUid);
4009
Robert Carrb89ea9d2018-12-10 13:01:14 -08004010 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4011 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4012 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004013 if (result != NO_ERROR) {
4014 return result;
4015 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004016 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004017
4018 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004019 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020}
4021
Cody Northropbc755282017-03-31 12:00:08 -06004022String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4023{
4024 bool matchFound = true;
4025 uint32_t dupeCounter = 0;
4026
4027 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4028 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4029
Dan Stoza436ccf32018-06-21 12:10:12 -07004030 // Grab the state lock since we're accessing mCurrentState
4031 Mutex::Autolock lock(mStateLock);
4032
Cody Northropbc755282017-03-31 12:00:08 -06004033 // Loop over layers until we're sure there is no matching name
4034 while (matchFound) {
4035 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004036 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004037 if (layer->getName() == uniqueName) {
4038 matchFound = true;
4039 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4040 }
4041 });
4042 }
4043
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004044 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4045 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004046
4047 return uniqueName;
4048}
4049
Marissa Wallfd668622018-05-10 10:21:13 -07004050status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4051 uint32_t w, uint32_t h, uint32_t flags,
4052 PixelFormat& format, sp<IBinder>* handle,
4053 sp<IGraphicBufferProducer>* gbp,
4054 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004056 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 case PIXEL_FORMAT_TRANSPARENT:
4058 case PIXEL_FORMAT_TRANSLUCENT:
4059 format = PIXEL_FORMAT_RGBA_8888;
4060 break;
4061 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004062 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004063 break;
4064 }
4065
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004066 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004067 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004068 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004069 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004070 *handle = layer->getHandle();
4071 *gbp = layer->getProducer();
4072 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074
Marissa Wallfd668622018-05-10 10:21:13 -07004075 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077}
4078
Marissa Wall61c58622018-07-18 10:12:20 -07004079status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4080 uint32_t w, uint32_t h, uint32_t flags,
4081 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004082 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004083 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004084 *handle = layer->getHandle();
4085 *outLayer = layer;
4086
4087 return NO_ERROR;
4088}
4089
chaviw13fdc492017-06-27 12:40:18 -07004090status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004091 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004092 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004094 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004095 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004096 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004097}
4098
Robert Carr6b3f6c52018-08-13 13:05:17 -07004099status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4100 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4101 sp<IBinder>* handle, sp<Layer>* outLayer)
4102{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004103 *outLayer =
4104 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004105 *handle = (*outLayer)->getHandle();
4106 return NO_ERROR;
4107}
4108
4109
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004110void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004111 mLayersPendingRemoval.add(layer);
4112 mLayersRemoved = true;
4113 setTransactionFlags(eTransactionNeeded);
4114}
4115
Robert Carr695d5282018-12-18 15:27:58 -08004116void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004117{
Robert Carr2e102c92018-10-23 12:11:15 -07004118 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004119 // If a layer has a parent, we allow it to out-live it's handle
4120 // with the idea that the parent holds a reference and will eventually
4121 // be cleaned up. However no one cleans up the top-level so we do so
4122 // here.
4123 if (layer->getParent() == nullptr) {
4124 mCurrentState.layersSortedByZ.remove(layer);
4125 }
4126 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004127 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004128}
4129
Mathias Agopianb60314a2012-04-10 22:09:54 -07004130// ---------------------------------------------------------------------------
4131
Andy McFadden13a082e2012-08-24 10:16:42 -07004132void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004134 if (!displayToken) return;
4135
Jesse Hall01e29052013-02-19 16:13:35 -08004136 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004137 Vector<ComposerState> state;
4138 Vector<DisplayState> displays;
4139 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004140 d.what = DisplayState::eDisplayProjectionChanged |
4141 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004142 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004143 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004144 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004145 d.frame.makeInvalid();
4146 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004147 d.width = 0;
4148 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004149 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004150 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004151
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004152 const auto display = getDisplayDevice(displayToken);
4153 if (!display) return;
4154
Dominik Laskowskie9774092018-12-11 10:04:24 -08004155 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004156
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004158 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004159 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004160
Brian Andersond0010582017-03-07 13:20:31 -08004161 // Use phase of 0 since phase is not known.
4162 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004163 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4164 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004165}
4166
4167void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004168 // Async since we may be called from the main thread.
4169 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004170}
4171
Dominik Laskowskie9774092018-12-11 10:04:24 -08004172void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004173 if (display->isVirtual()) {
4174 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004175 return;
4176 }
4177
Dominik Laskowski075d3172018-05-24 15:50:06 -07004178 const auto displayId = display->getId();
4179 LOG_ALWAYS_FATAL_IF(!displayId);
4180
Dominik Laskowski34157762018-10-31 13:07:19 -07004181 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004182
4183 int currentMode = display->getPowerMode();
4184 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004185 return;
4186 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004187
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004188 display->setPowerMode(mode);
4189
Lloyd Pique4dccc412018-01-22 17:21:36 -08004190 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004191 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004192 }
4193
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004194 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004195 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004196 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004197 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004198 if (mUseScheduler) {
4199 mScheduler->onScreenAcquired(mAppConnectionHandle);
4200 } else {
4201 mEventThread->onScreenAcquired();
4202 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004203 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004204 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004206 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004207 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004208 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004209
4210 struct sched_param param = {0};
4211 param.sched_priority = 1;
4212 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4213 ALOGW("Couldn't set SCHED_FIFO on display on");
4214 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004215 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004216 // Turn off the display
4217 struct sched_param param = {0};
4218 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4219 ALOGW("Couldn't set SCHED_OTHER on display off");
4220 }
4221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004222 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004223 if (mUseScheduler) {
4224 mScheduler->disableHardwareVsync(true);
4225 } else {
4226 disableHardwareVsync(true); // also cancels any in-progress resync
4227 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004228 if (mUseScheduler) {
4229 mScheduler->onScreenReleased(mAppConnectionHandle);
4230 } else {
4231 mEventThread->onScreenReleased();
4232 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004233 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004234
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004236 mVisibleRegionsDirty = true;
4237 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004238 } else if (mode == HWC_POWER_MODE_DOZE ||
4239 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004240 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004241 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004242 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004243 if (mUseScheduler) {
4244 mScheduler->onScreenAcquired(mAppConnectionHandle);
4245 } else {
4246 mEventThread->onScreenAcquired();
4247 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004248 resyncToHardwareVsync(true);
4249 }
4250 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4251 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004253 if (mUseScheduler) {
4254 mScheduler->disableHardwareVsync(true);
4255 } else {
4256 disableHardwareVsync(true); // also cancels any in-progress resync
4257 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004258 if (mUseScheduler) {
4259 mScheduler->onScreenReleased(mAppConnectionHandle);
4260 } else {
4261 mEventThread->onScreenReleased();
4262 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004263 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004265 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004266 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004267 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004268 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004269
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004270 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004271 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004272 }
4273
Dominik Laskowski34157762018-10-31 13:07:19 -07004274 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004275}
4276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004278 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279 const auto display = getDisplayDevice(displayToken);
4280 if (!display) {
4281 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4282 displayToken.get());
4283 } else if (display->isVirtual()) {
4284 ALOGW("Attempt to set power mode %d for virtual display", mode);
4285 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004286 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004287 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004289}
4290
4291// ---------------------------------------------------------------------------
4292
Lloyd Pique755e3192018-01-31 16:46:15 -08004293status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4294 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004296
Mathias Agopianbd115332013-04-18 16:41:04 -07004297 IPCThreadState* ipc = IPCThreadState::self();
4298 const int pid = ipc->getCallingPid();
4299 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004300
Mathias Agopianbd115332013-04-18 16:41:04 -07004301 if ((uid != AID_SHELL) &&
4302 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004303 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4304 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004306 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004307 // (this would indicate SF is stuck, but we want to be able to
4308 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004309 status_t err = mStateLock.timedLock(s2ns(1));
4310 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004311 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312 StringAppendF(&result,
4313 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4314 "(no locks held)\n",
4315 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004316 }
4317
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 bool dumpAll = true;
4319 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004320 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004321
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004322 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004323 if ((index < numArgs) &&
4324 (args[index] == String16("--list"))) {
4325 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004326 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004327 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004328 }
4329
4330 if ((index < numArgs) &&
4331 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004333 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004334 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004336
4337 if ((index < numArgs) &&
4338 (args[index] == String16("--latency-clear"))) {
4339 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004340 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004341 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004342 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004343
4344 if ((index < numArgs) &&
4345 (args[index] == String16("--dispsync"))) {
4346 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004347 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004348 dumpAll = false;
4349 }
Dan Stozab90cf072015-03-05 11:05:59 -08004350
4351 if ((index < numArgs) &&
4352 (args[index] == String16("--static-screen"))) {
4353 index++;
4354 dumpStaticScreenStats(result);
4355 dumpAll = false;
4356 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004357
4358 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004359 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004360 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004361 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004362 dumpAll = false;
4363 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004364
4365 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4366 index++;
4367 dumpWideColorInfo(result);
4368 dumpAll = false;
4369 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004370
4371 if ((index < numArgs) &&
4372 (args[index] == String16("--enable-layer-stats"))) {
4373 index++;
4374 mLayerStats.enable();
4375 dumpAll = false;
4376 }
4377
4378 if ((index < numArgs) &&
4379 (args[index] == String16("--disable-layer-stats"))) {
4380 index++;
4381 mLayerStats.disable();
4382 dumpAll = false;
4383 }
4384
4385 if ((index < numArgs) &&
4386 (args[index] == String16("--clear-layer-stats"))) {
4387 index++;
4388 mLayerStats.clear();
4389 dumpAll = false;
4390 }
4391
4392 if ((index < numArgs) &&
4393 (args[index] == String16("--dump-layer-stats"))) {
4394 index++;
4395 mLayerStats.dump(result);
4396 dumpAll = false;
4397 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004398
4399 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004400 (args[index] == String16("--frame-composition"))) {
4401 index++;
4402 dumpFrameCompositionInfo(result);
4403 dumpAll = false;
4404 }
4405
4406 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004407 (args[index] == String16("--display-identification"))) {
4408 index++;
4409 dumpDisplayIdentificationData(result);
4410 dumpAll = false;
4411 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004412
4413 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4414 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004415 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004416 dumpAll = false;
4417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004418 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004419
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004421 if (asProto) {
4422 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4423 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4424 } else {
4425 dumpAllLocked(args, index, result);
4426 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004427 }
4428
Mathias Agopian9795c422009-08-26 16:36:26 -07004429 if (locked) {
4430 mStateLock.unlock();
4431 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 return NO_ERROR;
4435}
4436
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4438 std::string& result) const {
4439 mCurrentState.traverseInZOrder(
4440 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004441}
4442
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004444 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445 String8 name;
4446 if (index < args.size()) {
4447 name = String8(args[index]);
4448 index++;
4449 }
4450
Dominik Laskowski075d3172018-05-24 15:50:06 -07004451 if (const auto displayId = getInternalDisplayId();
4452 displayId && getHwComposer().isConnected(*displayId)) {
4453 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004456 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004457
4458 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004459 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004460 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004461 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004462 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004463 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004464 }
Robert Carr2047fae2016-11-28 14:09:09 -08004465 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004466 }
4467}
4468
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004469void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004470 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004471 String8 name;
4472 if (index < args.size()) {
4473 name = String8(args[index]);
4474 index++;
4475 }
4476
Robert Carr2047fae2016-11-28 14:09:09 -08004477 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004479 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004480 }
Robert Carr2047fae2016-11-28 14:09:09 -08004481 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004482
Svetoslavd85084b2014-03-20 10:28:31 -07004483 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004484}
4485
Jamie Gennis6547ff42013-07-16 20:12:42 -07004486// This should only be called from the main thread. Otherwise it would need
4487// the lock and should use mCurrentState rather than mDrawingState.
4488void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004489 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004491 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004492
4493 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4494}
4495
Yiwei Zhang5434a782018-12-05 18:06:32 -08004496void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004498
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004499 if (isLayerTripleBufferingDisabled())
4500 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004501
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4503 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4504 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4505 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4506 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4507 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004508 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004509}
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4512 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004513 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4514 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004515 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004516 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004518 }
David Sodman4a36e932017-11-07 14:29:47 -08004519 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004520 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004521 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004522 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4523 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004524}
4525
Dan Stozae77c7662016-05-13 11:37:28 -07004526void SurfaceFlinger::recordBufferingStats(const char* layerName,
4527 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004528 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4529 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004530 for (const auto& segment : history) {
4531 if (!segment.usedThirdBuffer) {
4532 stats.twoBufferTime += segment.totalTime;
4533 }
4534 if (segment.occupancyAverage < 1.0f) {
4535 stats.doubleBufferedTime += segment.totalTime;
4536 } else if (segment.occupancyAverage < 2.0f) {
4537 stats.tripleBufferedTime += segment.totalTime;
4538 }
4539 ++stats.numSegments;
4540 stats.totalTime += segment.totalTime;
4541 }
4542}
4543
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4545 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004546
4547 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4548 const size_t count = currentLayers.size();
4549 for (size_t i=0 ; i<count ; i++) {
4550 currentLayers[i]->dumpFrameEvents(result);
4551 }
4552}
4553
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004555 result.append("Buffering stats:\n");
4556 result.append(" [Layer name] <Active time> <Two buffer> "
4557 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004558 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004559 typedef std::tuple<std::string, float, float, float> BufferTuple;
4560 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004561 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004562 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004563 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004564 if (stats.numSegments == 0) {
4565 continue;
4566 }
4567 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4568 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4569 stats.totalTime;
4570 float doubleBufferRatio = static_cast<float>(
4571 stats.doubleBufferedTime) / stats.totalTime;
4572 float tripleBufferRatio = static_cast<float>(
4573 stats.tripleBufferedTime) / stats.totalTime;
4574 sorted.insert({activeTime, {name, twoBufferRatio,
4575 doubleBufferRatio, tripleBufferRatio}});
4576 }
4577 for (const auto& sortedPair : sorted) {
4578 float activeTime = sortedPair.first;
4579 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4581 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004582 }
4583 result.append("\n");
4584}
4585
Yiwei Zhang5434a782018-12-05 18:06:32 -08004586void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004587 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004588 const auto displayId = display->getId();
4589 if (!displayId) {
4590 continue;
4591 }
4592 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004593 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004594 continue;
4595 }
4596
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result,
4598 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4599 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004600 uint8_t port;
4601 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004602 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004603 result.append("no identification data\n");
4604 continue;
4605 }
4606
4607 if (!isEdid(data)) {
4608 result.append("unknown identification data: ");
4609 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004611 }
4612 result.append("\n");
4613 continue;
4614 }
4615
4616 const auto edid = parseEdid(data);
4617 if (!edid) {
4618 result.append("invalid EDID: ");
4619 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 }
4622 result.append("\n");
4623 continue;
4624 }
4625
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004627 result.append(edid->displayName.data(), edid->displayName.length());
4628 result.append("\"\n");
4629 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630}
4631
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4633 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4634 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4635 StringAppendF(&result, "DisplayColorSetting: %s\n",
4636 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004637
4638 // TODO: print out if wide-color mode is active or not
4639
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004640 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004641 const auto displayId = display->getId();
4642 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004643 continue;
4644 }
4645
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004647 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004648 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004650 }
4651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004652 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653 StringAppendF(&result, " Current color mode: %s (%d)\n",
4654 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004655 }
4656 result.append("\n");
4657}
4658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004660 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004661 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4662 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004663 continue;
4664 }
4665
Dominik Laskowski05275f12018-11-01 15:03:24 -07004666 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4668 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004669 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670 compositionInfo.dump(result, nullptr);
4671 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004672 }
4673 }
David Sodman7e4ae112018-02-09 15:02:28 -08004674}
4675
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004676LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004677 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004678 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4679 const State& state = useDrawing ? mDrawingState : mCurrentState;
4680 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004681 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004682 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004683 });
4684
4685 return layersProto;
4686}
4687
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004688LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004690
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004691 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004692 resolution->set_w(display.getWidth());
4693 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004694
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004695 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4696 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4697 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004698
Dominik Laskowski075d3172018-05-24 15:50:06 -07004699 const auto displayId = display.getId();
4700 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004701 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004702 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004703 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004704 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004705 }
4706 });
4707
4708 return layersProto;
4709}
4710
Mathias Agopian74d211a2013-04-22 16:55:35 +02004711void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004713 bool colorize = false;
4714 if (index < args.size()
4715 && (args[index] == String16("--color"))) {
4716 colorize = true;
4717 index++;
4718 }
4719
4720 Colorizer colorizer(colorize);
4721
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722 // figure out if we're stuck somewhere
4723 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004724 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004725 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4726
4727 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004728 * Dump library configuration.
4729 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004730
4731 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004732 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004734 appendSfConfigString(result);
4735 appendUiConfigString(result);
4736 appendGuiConfigString(result);
4737 result.append("\n");
4738
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004739 result.append("\nDisplay identification data:\n");
4740 dumpDisplayIdentificationData(result);
4741
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004742 result.append("\nWide-Color information:\n");
4743 dumpWideColorInfo(result);
4744
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004746 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004748 result.append(SyncFeatures::getInstance().toString());
4749 result.append("\n");
4750
Andy McFadden41d67d72014-04-25 16:58:34 -07004751 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004752 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004753 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004754
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004755 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4756 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004757 if (const auto displayId = getInternalDisplayId();
4758 displayId && getHwComposer().isConnected(*displayId)) {
4759 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004760 StringAppendF(&result,
4761 "Display %s: app phase %" PRId64 " ns, "
4762 "sf phase %" PRId64 " ns, "
4763 "early app phase %" PRId64 " ns, "
4764 "early sf phase %" PRId64 " ns, "
4765 "early app gl phase %" PRId64 " ns, "
4766 "early sf gl phase %" PRId64 " ns, "
4767 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4768 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4769 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4770 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004771 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004772 result.append("\n");
4773
Dan Stozab90cf072015-03-05 11:05:59 -08004774 // Dump static screen stats
4775 result.append("\n");
4776 dumpStaticScreenStats(result);
4777 result.append("\n");
4778
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004780
Dan Stozae77c7662016-05-13 11:37:28 -07004781 dumpBufferingStats(result);
4782
Andy McFadden4803b742012-09-24 19:07:20 -07004783 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004784 * Dump the visible layer list
4785 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004786 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4788 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4789 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004790 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004791
Chia-I Wu2f884132018-09-13 15:17:58 -07004792 {
4793 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4794 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004796 result.append("\n");
4797 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798
David Sodman7e4ae112018-02-09 15:02:28 -08004799 result.append("\nFrame-Composition information:\n");
4800 dumpFrameCompositionInfo(result);
4801 result.append("\n");
4802
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004804 * Dump Display state
4805 */
4806
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004807 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004808 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004810 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004811 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004812 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004813 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004814
4815 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816 * Dump SurfaceFlinger global state
4817 */
4818
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004819 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004820 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004821 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004823 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004824
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4828 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004829 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830 StringAppendF(&result,
4831 " transaction-flags : %08x\n"
4832 " gpu_to_cpu_unsupported : %d\n",
4833 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004834
Dominik Laskowski075d3172018-05-24 15:50:06 -07004835 if (const auto displayId = getInternalDisplayId();
4836 displayId && getHwComposer().isConnected(*displayId)) {
4837 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result,
4839 " refresh-rate : %f fps\n"
4840 " x-dpi : %f\n"
4841 " y-dpi : %f\n",
4842 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4843 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004845
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849 /*
4850 * VSYNC state
4851 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004852 if (mUseScheduler) {
4853 mScheduler->dump(mAppConnectionHandle, result);
4854 } else {
4855 mEventThread->dump(result);
4856 }
Dan Stozae22aec72016-08-01 13:20:59 -07004857 result.append("\n");
4858
4859 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004860 * Tracing state
4861 */
4862 mTracing.dump(result);
4863 result.append("\n");
4864
4865 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004866 * HWC layer minidump
4867 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004868 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004869 const auto displayId = display->getId();
4870 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004871 continue;
4872 }
4873
Yiwei Zhang5434a782018-12-05 18:06:32 -08004874 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004875 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004876 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004877 result.append("\n");
4878 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879
4880 /*
4881 * Dump HWComposer state
4882 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004883 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004884 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004885 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004886 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004888 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889
4890 /*
4891 * Dump gralloc state
4892 */
4893 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4894 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004895
4896 /*
4897 * Dump VrFlinger state if in use.
4898 */
4899 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4900 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004901 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004902 result.append("\n");
4903 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004904}
4905
Dominik Laskowski075d3172018-05-24 15:50:06 -07004906const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004907 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004908 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004909 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004910 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004911 }
4912 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004913
Dominik Laskowski34157762018-10-31 13:07:19 -07004914 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004915 static const Vector<sp<Layer>> empty;
4916 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004917}
4918
Keun young Park63f165f2012-08-31 10:53:36 -07004919bool SurfaceFlinger::startDdmConnection()
4920{
4921 void* libddmconnection_dso =
4922 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4923 if (!libddmconnection_dso) {
4924 return false;
4925 }
4926 void (*DdmConnection_start)(const char* name);
4927 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004928 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004929 if (!DdmConnection_start) {
4930 dlclose(libddmconnection_dso);
4931 return false;
4932 }
4933 (*DdmConnection_start)(getServiceName());
4934 return true;
4935}
4936
Chia-I Wu28f320b2018-05-03 11:02:56 -07004937void SurfaceFlinger::updateColorMatrixLocked() {
4938 mat4 colorMatrix;
4939 if (mGlobalSaturationFactor != 1.0f) {
4940 // Rec.709 luma coefficients
4941 float3 luminance{0.213f, 0.715f, 0.072f};
4942 luminance *= 1.0f - mGlobalSaturationFactor;
4943 mat4 saturationMatrix = mat4(
4944 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4945 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4946 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4947 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4948 );
4949 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4950 } else {
4951 colorMatrix = mClientColorMatrix * mDaltonizer();
4952 }
4953
4954 if (mCurrentState.colorMatrix != colorMatrix) {
4955 mCurrentState.colorMatrix = colorMatrix;
4956 mCurrentState.colorMatrixChanged = true;
4957 setTransactionFlags(eTransactionNeeded);
4958 }
4959}
4960
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004961status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004962#pragma clang diagnostic push
4963#pragma clang diagnostic error "-Wswitch-enum"
4964 switch (static_cast<ISurfaceComposerTag>(code)) {
4965 // These methods should at minimum make sure that the client requested
4966 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004967 case BOOT_FINISHED:
4968 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 case CREATE_DISPLAY:
4970 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004971 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972 case GET_ACTIVE_COLOR_MODE:
4973 case GET_ANIMATION_FRAME_STATS:
4974 case GET_HDR_CAPABILITIES:
4975 case SET_ACTIVE_CONFIG:
4976 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004977 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004978 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004979 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004980 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4981 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004982 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4983 IPCThreadState* ipc = IPCThreadState::self();
4984 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4985 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004986 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 }
Robert Carr1db73f62016-12-21 12:58:51 -08004988 return OK;
4989 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004990 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004991 IPCThreadState* ipc = IPCThreadState::self();
4992 const int pid = ipc->getCallingPid();
4993 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4995 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004996 return PERMISSION_DENIED;
4997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000 // Used by apps to hook Choreographer to SurfaceFlinger.
5001 case CREATE_DISPLAY_EVENT_CONNECTION:
5002 // The following calls are currently used by clients that do not
5003 // request necessary permissions. However, they do not expose any secret
5004 // information, so it is OK to pass them.
5005 case AUTHENTICATE_SURFACE:
5006 case GET_ACTIVE_CONFIG:
5007 case GET_BUILT_IN_DISPLAY:
5008 case GET_DISPLAY_COLOR_MODES:
5009 case GET_DISPLAY_CONFIGS:
5010 case GET_DISPLAY_STATS:
5011 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5012 // Calling setTransactionState is safe, because you need to have been
5013 // granted a reference to Client* and Handle* to do anything with it.
5014 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005015 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005016 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005017 case GET_COMPOSITION_PREFERENCE:
5018 case GET_PROTECTED_CONTENT_SUPPORT: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005019 return OK;
5020 }
5021 case CAPTURE_LAYERS:
5022 case CAPTURE_SCREEN: {
5023 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005024 IPCThreadState* ipc = IPCThreadState::self();
5025 const int pid = ipc->getCallingPid();
5026 const int uid = ipc->getCallingUid();
5027 if ((uid != AID_GRAPHICS) &&
5028 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5029 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5030 return PERMISSION_DENIED;
5031 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005032 return OK;
5033 }
5034 // The following codes are deprecated and should never be allowed to access SF.
5035 case CONNECT_DISPLAY_UNUSED:
5036 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5037 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5038 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005039 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005041
5042 // These codes are used for the IBinder protocol to either interrogate the recipient
5043 // side of the transaction for its canonical interface descriptor or to dump its state.
5044 // We let them pass by default.
5045 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5046 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5047 code == IBinder::SYSPROPS_TRANSACTION) {
5048 return OK;
5049 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005050 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005052 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005053 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5054 return OK;
5055 }
5056 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5057 return PERMISSION_DENIED;
5058#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005059}
5060
Ana Krulec13be8ad2018-08-21 02:43:56 +00005061status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5062 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005063 status_t credentialCheck = CheckTransactCodeCredentials(code);
5064 if (credentialCheck != OK) {
5065 return credentialCheck;
5066 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005067
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005068 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5069 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005070 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005071 IPCThreadState* ipc = IPCThreadState::self();
5072 const int uid = ipc->getCallingUid();
5073 if (CC_UNLIKELY(uid != AID_SYSTEM
5074 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005075 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005076 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005077 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005078 return PERMISSION_DENIED;
5079 }
5080 int n;
5081 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005082 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005083 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 return NO_ERROR;
5085 case 1002: // SHOW_UPDATES
5086 n = data.readInt32();
5087 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005088 invalidateHwcGeometry();
5089 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005092 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005093 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005095 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005096 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005097 setTransactionFlags(
5098 eTransactionNeeded|
5099 eDisplayTransactionNeeded|
5100 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005101 return NO_ERROR;
5102 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005103 case 1006:{ // send empty update
5104 signalRefresh();
5105 return NO_ERROR;
5106 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005107 case 1008: // toggle use of hw composer
5108 n = data.readInt32();
5109 mDebugDisableHWC = n ? 1 : 0;
5110 invalidateHwcGeometry();
5111 repaintEverything();
5112 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005113 case 1009: // toggle use of transform hint
5114 n = data.readInt32();
5115 mDebugDisableTransformHint = n ? 1 : 0;
5116 invalidateHwcGeometry();
5117 repaintEverything();
5118 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005119 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005120 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121 reply->writeInt32(0);
5122 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005123 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005124 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 return NO_ERROR;
5126 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005127 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005128 if (!display) {
5129 return NAME_NOT_FOUND;
5130 }
5131
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005132 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005133 return NO_ERROR;
5134 }
5135 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005136 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005137 // daltonize
5138 n = data.readInt32();
5139 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005140 case 1:
5141 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5142 break;
5143 case 2:
5144 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5145 break;
5146 case 3:
5147 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5148 break;
5149 default:
5150 mDaltonizer.setType(ColorBlindnessType::None);
5151 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005152 }
5153 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005154 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005155 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005156 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005157 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005158
5159 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005160 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005161 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005162 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005163 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005164 // apply a color matrix
5165 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005166 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005167 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005168 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005169 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005170 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005171 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005174 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005175 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005176
5177 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5178 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005179 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005180 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5181 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5182 }
5183
Chia-I Wu28f320b2018-05-03 11:02:56 -07005184 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005185 return NO_ERROR;
5186 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005187 // This is an experimental interface
5188 // Needs to be shifted to proper binder interface when we productize
5189 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005190 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005191 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005192 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005193 return NO_ERROR;
5194 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005195 case 1017: {
5196 n = data.readInt32();
5197 mForceFullDamage = static_cast<bool>(n);
5198 return NO_ERROR;
5199 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005200 case 1018: { // Modify Choreographer's phase offset
5201 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005202 if (mUseScheduler) {
5203 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5204 } else {
5205 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5206 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005207 return NO_ERROR;
5208 }
5209 case 1019: { // Modify SurfaceFlinger's phase offset
5210 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005211 if (mUseScheduler) {
5212 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5213 } else {
5214 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5215 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005216 return NO_ERROR;
5217 }
Irvel468051e2016-06-13 16:44:44 -07005218 case 1020: { // Layer updates interceptor
5219 n = data.readInt32();
5220 if (n) {
5221 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005222 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005223 }
5224 else{
5225 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005226 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005227 }
5228 return NO_ERROR;
5229 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005230 case 1021: { // Disable HWC virtual displays
5231 n = data.readInt32();
5232 mUseHwcVirtualDisplays = !n;
5233 return NO_ERROR;
5234 }
Romain Guy0147a172017-06-01 13:53:56 -07005235 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005236 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005237 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005238
Chia-I Wu28f320b2018-05-03 11:02:56 -07005239 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005240 return NO_ERROR;
5241 }
Romain Guy54f154a2017-10-24 21:40:32 +01005242 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005243 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005244 invalidateHwcGeometry();
5245 repaintEverything();
5246 return NO_ERROR;
5247 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005248 // Deprecate, use 1030 to check whether the device is color managed.
5249 case 1024: {
5250 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005251 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005252 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005253 n = data.readInt32();
5254 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005255 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005256 mTracing.enable();
5257 doTracing("tracing.enable");
5258 reply->writeInt32(NO_ERROR);
5259 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005260 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005261 status_t err = mTracing.disable();
5262 reply->writeInt32(err);
5263 }
5264 return NO_ERROR;
5265 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005266 case 1026: { // Get layer tracing status
5267 reply->writeBool(mTracing.isEnabled());
5268 return NO_ERROR;
5269 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005270 // Is a DisplayColorSetting supported?
5271 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005272 const auto display = getDefaultDisplayDevice();
5273 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005274 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005275 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005276
5277 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5278 switch (setting) {
5279 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005280 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005281 break;
5282 case DisplayColorSetting::UNMANAGED:
5283 reply->writeBool(true);
5284 break;
5285 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005286 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005287 break;
5288 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005289 reply->writeBool(
5290 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005291 break;
5292 }
5293 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005294 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005295 // Is VrFlinger active?
5296 case 1028: {
5297 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005298 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005299 return NO_ERROR;
5300 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005301 // Is device color managed?
5302 case 1030: {
5303 reply->writeBool(useColorManagement);
5304 return NO_ERROR;
5305 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005306 // Override default composition data space
5307 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5308 // && adb shell stop zygote && adb shell start zygote
5309 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5310 // adb shell stop zygote && adb shell start zygote
5311 case 1031: {
5312 Mutex::Autolock _l(mStateLock);
5313 n = data.readInt32();
5314 if (n) {
5315 n = data.readInt32();
5316 if (n) {
5317 Dataspace dataspace = static_cast<Dataspace>(n);
5318 if (!validateCompositionDataspace(dataspace)) {
5319 return BAD_VALUE;
5320 }
5321 mDefaultCompositionDataspace = dataspace;
5322 }
5323 n = data.readInt32();
5324 if (n) {
5325 Dataspace dataspace = static_cast<Dataspace>(n);
5326 if (!validateCompositionDataspace(dataspace)) {
5327 return BAD_VALUE;
5328 }
5329 mWideColorGamutCompositionDataspace = dataspace;
5330 }
5331 } else {
5332 // restore composition data space.
5333 mDefaultCompositionDataspace = defaultCompositionDataspace;
5334 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5335 }
5336 return NO_ERROR;
5337 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005338 }
5339 }
5340 return err;
5341}
5342
Steven Thomas6d8110b2017-08-31 18:24:21 -07005343void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005344 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005345 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005346}
5347
Ana Krulec7d1d6832018-12-27 11:10:09 -08005348void SurfaceFlinger::repaintEverythingForHWC() {
5349 mRepaintEverything = true;
5350 mEventQueue->invalidateForHWC();
5351}
5352
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005353// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5354class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005355public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005356 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5357 ~WindowDisconnector() {
5358 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005359 }
5360
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005361private:
5362 ANativeWindow* mWindow;
5363 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005364};
5365
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005366status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005367 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5368 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005369 uint32_t reqWidth, uint32_t reqHeight,
5370 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005371 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005374 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005375
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005376 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5377
Chia-I Wu20261cb2018-08-23 12:55:44 -07005378 sp<DisplayDevice> display;
5379 {
5380 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005381
Chia-I Wu20261cb2018-08-23 12:55:44 -07005382 display = getDisplayDeviceLocked(displayToken);
5383 if (!display) return BAD_VALUE;
5384
Chia-I Wucb023152018-08-28 12:57:23 -07005385 // set the requested width/height to the logical display viewport size
5386 // by default
5387 if (reqWidth == 0 || reqHeight == 0) {
5388 reqWidth = uint32_t(display->getViewport().width());
5389 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005390 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005391 }
5392
Peiyong Lin0e003c92018-09-17 11:09:51 -07005393 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5394 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005395
5396 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005397 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005398 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5399 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005400}
5401
5402status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005403 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5404 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005405 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005406 ATRACE_CALL();
5407
5408 class LayerRenderArea : public RenderArea {
5409 public:
Robert Carr578038f2018-03-09 12:25:24 -08005410 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005411 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5412 bool childrenOnly)
5413 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005414 mLayer(layer),
5415 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005416 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005417 mFlinger(flinger),
5418 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005419 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005420 Rect getBounds() const override {
5421 const Layer::State& layerState(mLayer->getDrawingState());
5422 return mLayer->getBufferSize(layerState);
5423 }
Marissa Wall61c58622018-07-18 10:12:20 -07005424 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005425 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005426 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005427 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005428 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005429 }
chaviwa76b2712017-09-20 12:02:26 -07005430 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005431 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005432 Rect getSourceCrop() const override {
5433 if (mCrop.isEmpty()) {
5434 return getBounds();
5435 } else {
5436 return mCrop;
5437 }
5438 }
Robert Carr578038f2018-03-09 12:25:24 -08005439 class ReparentForDrawing {
5440 public:
5441 const sp<Layer>& oldParent;
5442 const sp<Layer>& newParent;
5443
5444 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5445 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005446 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005447 }
Robert Carr15eae092018-03-23 13:43:53 -07005448 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005449 };
5450
5451 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005452 const Rect sourceCrop = getSourceCrop();
5453 // no need to check rotation because there is none
5454 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5455 sourceCrop.height() != getReqHeight();
5456
Robert Carr578038f2018-03-09 12:25:24 -08005457 if (!mChildrenOnly) {
5458 mTransform = mLayer->getTransform().inverse();
5459 drawLayers();
5460 } else {
5461 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005462 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005463 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5464 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005465
5466 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5467 drawLayers();
5468 }
5469 }
chaviwa76b2712017-09-20 12:02:26 -07005470
chaviwa76b2712017-09-20 12:02:26 -07005471 private:
chaviw7206d492017-11-10 16:16:12 -08005472 const sp<Layer> mLayer;
5473 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005474
5475 // In the "childrenOnly" case we reparent the children to a screenshot
5476 // layer which has no properties set and which does not draw.
5477 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005478 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005479 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005480
5481 SurfaceFlinger* mFlinger;
5482 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005483 };
5484
5485 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5486 auto parent = layerHandle->owner.promote();
5487
Robert Carr2e102c92018-10-23 12:11:15 -07005488 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005489 ALOGE("captureLayers called with a removed parent");
5490 return NAME_NOT_FOUND;
5491 }
5492
Robert Carr578038f2018-03-09 12:25:24 -08005493 const int uid = IPCThreadState::self()->getCallingUid();
5494 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005495 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005496 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5497 return PERMISSION_DENIED;
5498 }
5499
chaviw7206d492017-11-10 16:16:12 -08005500 Rect crop(sourceCrop);
5501 if (sourceCrop.width() <= 0) {
5502 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005503 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005504 }
5505
5506 if (sourceCrop.height() <= 0) {
5507 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005508 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005509 }
5510
5511 int32_t reqWidth = crop.width() * frameScale;
5512 int32_t reqHeight = crop.height() * frameScale;
5513
Chia-I Wu20261cb2018-08-23 12:55:44 -07005514 // really small crop or frameScale
5515 if (reqWidth <= 0) {
5516 reqWidth = 1;
5517 }
5518 if (reqHeight <= 0) {
5519 reqHeight = 1;
5520 }
5521
Peiyong Lin0e003c92018-09-17 11:09:51 -07005522 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005523
Robert Carr578038f2018-03-09 12:25:24 -08005524 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005525 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5526 if (!layer->isVisible()) {
5527 return;
Robert Carr578038f2018-03-09 12:25:24 -08005528 } else if (childrenOnly && layer == parent.get()) {
5529 return;
chaviwa76b2712017-09-20 12:02:26 -07005530 }
5531 visitor(layer);
5532 });
5533 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005534 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005535}
5536
5537status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5538 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005539 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005540 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005541 bool useIdentityTransform) {
5542 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005543
Peiyong Lin0e003c92018-09-17 11:09:51 -07005544 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005545 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5546 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005547 *outBuffer =
5548 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5549 static_cast<android_pixel_format>(reqPixelFormat), 1,
5550 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005551
5552 // This mutex protects syncFd and captureResult for communication of the return values from the
5553 // main thread back to this Binder thread
5554 std::mutex captureMutex;
5555 std::condition_variable captureCondition;
5556 std::unique_lock<std::mutex> captureLock(captureMutex);
5557 int syncFd = -1;
5558 std::optional<status_t> captureResult;
5559
Robert Carr03480e22018-01-04 16:02:06 -08005560 const int uid = IPCThreadState::self()->getCallingUid();
5561 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5562
Dominik Laskowski8c001672018-05-30 16:52:06 -07005563 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005564 // If there is a refresh pending, bug out early and tell the binder thread to try again
5565 // after the refresh.
5566 if (mRefreshPending) {
5567 ATRACE_NAME("Skipping screenshot for now");
5568 std::unique_lock<std::mutex> captureLock(captureMutex);
5569 captureResult = std::make_optional<status_t>(EAGAIN);
5570 captureCondition.notify_one();
5571 return;
5572 }
5573
5574 status_t result = NO_ERROR;
5575 int fd = -1;
5576 {
5577 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005578 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005579 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5580 useIdentityTransform, forSystem, &fd);
5581 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582 }
5583
5584 {
5585 std::unique_lock<std::mutex> captureLock(captureMutex);
5586 syncFd = fd;
5587 captureResult = std::make_optional<status_t>(result);
5588 captureCondition.notify_one();
5589 }
5590 });
5591
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005594 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005595 while (*captureResult == EAGAIN) {
5596 captureResult.reset();
5597 result = postMessageAsync(message);
5598 if (result != NO_ERROR) {
5599 return result;
5600 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005601 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005602 }
5603 result = *captureResult;
5604 }
5605
5606 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005607 sync_wait(syncFd, -1);
5608 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005610
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005611 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005612}
5613
chaviwa76b2712017-09-20 12:02:26 -07005614void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005615 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005616 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005617 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005618
Lloyd Pique144e1162017-12-20 16:44:52 -08005619 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005620
chaviwa76b2712017-09-20 12:02:26 -07005621 const auto reqWidth = renderArea.getReqWidth();
5622 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005623 const auto sourceCrop = renderArea.getSourceCrop();
5624 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005625
Peiyong Lin0e003c92018-09-17 11:09:51 -07005626 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005627 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005628
Mathias Agopian180f10d2013-04-10 22:55:41 -07005629 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005630 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005631
5632 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005633 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005634 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005635
chaviw50da5042018-04-09 13:49:37 -07005636 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005638 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005639
chaviwa76b2712017-09-20 12:02:26 -07005640 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005641 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005642 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005643 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005644 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005645}
5646
chaviwa76b2712017-09-20 12:02:26 -07005647status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5648 TraverseLayersFunction traverseLayers,
5649 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005650 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005651 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005652 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005653 ATRACE_CALL();
5654
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005655 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005656
5657 traverseLayers([&](Layer* layer) {
5658 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5659 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005660
Robert Carr03480e22018-01-04 16:02:06 -08005661 // We allow the system server to take screenshots of secure layers for
5662 // use in situations like the Screen-rotation animation and place
5663 // the impetus on WindowManager to not persist them.
5664 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005665 ALOGW("FB is protected: PERMISSION_DENIED");
5666 return PERMISSION_DENIED;
5667 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005668 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005669
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005670 // this binds the given EGLImage as a framebuffer for the
5671 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005672 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005673 if (bufferBond.getStatus() != NO_ERROR) {
5674 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005675 return INVALID_OPERATION;
5676 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005677
Dan Stozaabcda352017-06-01 14:37:39 -07005678 // this will in fact render into our dequeued buffer
5679 // via an FBO, which means we didn't have to create
5680 // an EGLSurface and therefore we're not
5681 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005682 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005683
Peiyong Linfb530cf2018-12-15 05:07:38 +00005684 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005685 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005686 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005687 }
Alec Mouri492bc572018-09-11 21:40:04 +00005688 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005689
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005690 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005691}
5692
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005693// ---------------------------------------------------------------------------
5694
Dan Stoza412903f2017-04-27 13:42:17 -07005695void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5696 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005697}
5698
Dan Stoza412903f2017-04-27 13:42:17 -07005699void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5700 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005701}
5702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005703void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005704 const LayerVector::Visitor& visitor) {
5705 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005706 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005707 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005708 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005709 continue;
5710 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005711 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005712 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005713 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005714 return;
5715 }
chaviwa76b2712017-09-20 12:02:26 -07005716 if (!layer->isVisible()) {
5717 return;
5718 }
5719 visitor(layer);
5720 });
5721 }
5722}
5723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005724}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005725
Lloyd Pique074e8122018-07-26 12:57:23 -07005726
Mathias Agopian3f844832013-08-07 21:24:32 -07005727#if defined(__gl_h_)
5728#error "don't include gl/gl.h in this file"
5729#endif
5730
5731#if defined(__gl2_h_)
5732#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005733#endif