blob: 26406250c307b3d1797392a12ea0b022983e0db9 [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
Marissa Wallebc2c052019-01-16 19:16:55 -08001163status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1164 int32_t* outBufferId) {
1165 if (!outBufferId) {
1166 return BAD_VALUE;
1167 }
1168 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1169 return NO_ERROR;
1170}
1171
1172status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1173 mBufferStateLayerCache.release(token, bufferId);
1174 return NO_ERROR;
1175}
1176
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001178 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001179 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 if (mInjectVSyncs == enable) {
1182 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001184
Dominik Laskowskif654d572018-12-20 11:03:06 -08001185 auto resyncCallback = makeResyncCallback();
1186
Ana Krulec98b5b242018-08-10 15:03:23 -07001187 // TODO(akrulec): Part of the Injector should be refactored, so that it
1188 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 if (enable) {
1190 ALOGV("VSync Injections enabled");
1191 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001192 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001193 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001194 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001195 impl::EventThread::InterceptVSyncsCallback(),
1196 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001198 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199 } else {
1200 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001201 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001202 }
1203
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001205 }));
1206
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001207 return NO_ERROR;
1208}
1209
1210status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001211 Mutex::Autolock _l(mStateLock);
1212
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001213 if (!mInjectVSyncs) {
1214 ALOGE("VSync Injections not enabled");
1215 return BAD_VALUE;
1216 }
1217 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1218 ALOGV("Injecting VSync inside SurfaceFlinger");
1219 mVSyncInjector->onInjectSyncEvent(when);
1220 }
1221 return NO_ERROR;
1222}
1223
Lloyd Pique755e3192018-01-31 16:46:15 -08001224status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1225 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001226 // Try to acquire a lock for 1s, fail gracefully
1227 const status_t err = mStateLock.timedLock(s2ns(1));
1228 const bool locked = (err == NO_ERROR);
1229 if (!locked) {
1230 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1231 return TIMED_OUT;
1232 }
1233
1234 outLayers->clear();
1235 mCurrentState.traverseInZOrder([&](Layer* layer) {
1236 outLayers->push_back(layer->getLayerDebugInfo());
1237 });
1238
1239 mStateLock.unlock();
1240 return NO_ERROR;
1241}
1242
Peiyong Linc6780972018-10-28 15:24:08 -07001243status_t SurfaceFlinger::getCompositionPreference(
1244 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1245 Dataspace* outWideColorGamutDataspace,
1246 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001247 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001248 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001249 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001250 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001251 return NO_ERROR;
1252}
1253
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001254// ----------------------------------------------------------------------------
1255
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001256sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1257 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001258 auto resyncCallback = makeResyncCallback();
1259
Ana Krulec98b5b242018-08-10 15:03:23 -07001260 if (mUseScheduler) {
1261 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001262 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001263 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001264 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001265 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001266 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001267 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001268 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001269 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001271 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001272 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001273}
1274
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001275// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001276
1277void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001278 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279}
1280
1281void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001286 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287}
1288
1289void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001290 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001291 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001292}
1293
1294status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001295 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001296 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001297}
1298
1299status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001300 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001301 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001302 if (res == NO_ERROR) {
1303 msg->wait();
1304 }
1305 return res;
1306}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001307
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001308void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001309 do {
1310 waitForEvent();
1311 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001312}
1313
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001314void SurfaceFlinger::enableHardwareVsync() {
1315 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001316 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001317 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001318 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001320 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321}
1322
Jesse Hall948fe0c2013-10-14 12:56:09 -07001323void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324 Mutex::Autolock _l(mHWVsyncLock);
1325
Jesse Hall948fe0c2013-10-14 12:56:09 -07001326 if (makeAvailable) {
1327 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001328 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1329 if (mUseScheduler) {
1330 mScheduler->makeHWSyncAvailable(true);
1331 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001333 // Hardware vsync is not currently available, so abort the resync
1334 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001335 return;
1336 }
1337
Dominik Laskowski075d3172018-05-24 15:50:06 -07001338 const auto displayId = getInternalDisplayId();
1339 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001340 return;
1341 }
1342
Dominik Laskowski075d3172018-05-24 15:50:06 -07001343 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345
Ana Krulece588e312018-09-18 12:32:24 -07001346 if (mUseScheduler) {
1347 mScheduler->setVsyncPeriod(period);
1348 } else {
1349 mPrimaryDispSync->reset();
1350 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351
Ana Krulece588e312018-09-18 12:32:24 -07001352 if (!mPrimaryHWVsyncEnabled) {
1353 mPrimaryDispSync->beginResync();
1354 mEventControlThread->setVsyncEnabled(true);
1355 mPrimaryHWVsyncEnabled = true;
1356 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357 }
1358}
1359
Jesse Hall948fe0c2013-10-14 12:56:09 -07001360void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001361 Mutex::Autolock _l(mHWVsyncLock);
1362 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001363 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001364 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001365 mPrimaryHWVsyncEnabled = false;
1366 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001367 if (makeUnavailable) {
1368 mHWVsyncAvailable = false;
1369 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001370}
1371
Dominik Laskowskif654d572018-12-20 11:03:06 -08001372void SurfaceFlinger::VsyncState::resync() {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001373 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001374
1375 // No explicit locking is needed here since EventThread holds a lock while calling this method
Dan Stoza57164302017-05-08 14:03:54 -07001376 const nsecs_t now = systemTime();
Dominik Laskowskif654d572018-12-20 11:03:06 -08001377 if (now - lastResyncTime > kIgnoreDelay) {
1378 flinger.resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001379 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001380 lastResyncTime = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1384 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001385 ATRACE_NAME("SF onVsync");
1386
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
1391 }
1392
Dominik Laskowski075d3172018-05-24 15:50:06 -07001393 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001394 return;
1395 }
1396
Dominik Laskowski075d3172018-05-24 15:50:06 -07001397 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 // For now, we don't do anything with external display vsyncs.
1399 return;
1400 }
1401
Ana Krulece588e312018-09-18 12:32:24 -07001402 if (mUseScheduler) {
1403 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001404 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001405 bool needsHwVsync = false;
1406 { // Scope for the lock
1407 Mutex::Autolock _l(mHWVsyncLock);
1408 if (mPrimaryHWVsyncEnabled) {
1409 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1410 }
1411 }
1412
1413 if (needsHwVsync) {
1414 enableHardwareVsync();
1415 } else {
1416 disableHardwareVsync(false);
1417 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001418 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001419}
1420
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001421void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001422 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1423 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001424}
1425
Ana Krulec7d1d6832018-12-27 11:10:09 -08001426void SurfaceFlinger::setRefreshRateTo(float newFps) {
1427 const auto displayId = getInternalDisplayId();
1428 if (!displayId || mBootStage != BootStage::FINISHED) {
1429 return;
1430 }
1431 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1432 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1433 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1434 // refresh cycle.
1435
1436 // Don't do any updating if the current fps is the same as the new one.
1437 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1438 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1439 if (currentVsyncPeriod == 0) {
1440 return;
1441 }
1442 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1443 // floating numbers.
1444 const float currentFps = 1e9 / currentVsyncPeriod;
1445 if (std::abs(currentFps - newFps) <= 1) {
1446 return;
1447 }
1448
1449 auto configs = getHwComposer().getConfigs(*displayId);
1450 for (int i = 0; i < configs.size(); i++) {
1451 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1452 if (vsyncPeriod == 0) {
1453 continue;
1454 }
1455 const float fps = 1e9 / vsyncPeriod;
1456 // TODO(b/113612090): There should be a better way at determining which config
1457 // has the right refresh rate.
1458 if (std::abs(fps - newFps) <= 1) {
1459 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1460 if (!display) return;
1461 // This is posted in async function to avoid deadlock when getDisplayDevice
1462 // requires mStateLock.
1463 setActiveConfigAsync(display, i);
1464 ATRACE_INT("FPS", newFps);
1465 }
1466 }
1467}
1468
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001469void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001470 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001471 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001472 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001473
Lloyd Piqueba04e622017-12-14 17:11:26 -08001474 // Ignore events that do not have the right sequenceId.
1475 if (sequenceId != getBE().mComposerSequenceId) {
1476 return;
1477 }
1478
Steven Thomasb02664d2017-07-26 18:48:28 -07001479 // Only lock if we're not on the main thread. This function is normally
1480 // called on a hwbinder thread, but for the primary display it's called on
1481 // the main thread with the state lock already held, so don't attempt to
1482 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001483 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001484
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001485 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001486
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001487 if (std::this_thread::get_id() == mMainThreadId) {
1488 // Process all pending hot plug events immediately if we are on the main thread.
1489 processDisplayHotplugEventsLocked();
1490 }
1491
Lloyd Piqueba04e622017-12-14 17:11:26 -08001492 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001493}
1494
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001495void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001496 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001497 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001499 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001500 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001501}
1502
Dominik Laskowski075d3172018-05-24 15:50:06 -07001503void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001504 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001505 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001506 if (const auto displayId = getInternalDisplayId()) {
1507 getHwComposer().setVsyncEnabled(*displayId,
1508 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1509 }
Mathias Agopian86303202012-07-24 22:46:10 -07001510}
1511
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001512// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001513void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001514 if (mUseScheduler) {
1515 mScheduler->disableHardwareVsync(true);
1516 } else {
1517 disableHardwareVsync(true);
1518 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519 // Clear the drawing state so that the logic inside of
1520 // handleTransactionLocked will fire. It will determine the delta between
1521 // mCurrentState and mDrawingState and re-apply all changes when we make the
1522 // transition.
1523 mDrawingState.displays.clear();
1524 mDisplays.clear();
1525}
1526
Steven Thomas050b2c82017-03-06 11:45:16 -08001527void SurfaceFlinger::updateVrFlinger() {
1528 if (!mVrFlinger)
1529 return;
1530 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001531 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001532 return;
1533 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001534
Lloyd Pique441d5042018-10-18 16:49:51 -07001535 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001536 ALOGE("Vr flinger is only supported for remote hardware composer"
1537 " service connections. Ignoring request to transition to vr"
1538 " flinger.");
1539 mVrFlingerRequestsDisplay = false;
1540 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001541 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001542
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001543 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Steven Thomas0123ac62018-07-12 11:32:34 -07001545 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001546 LOG_ALWAYS_FATAL_IF(!display);
1547 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001548 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1549 // called below. Clear the reference now so we don't accidentally use it
1550 // later.
1551 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001552
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001554 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001556
Steven Thomasb02664d2017-07-26 18:48:28 -07001557 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001558 // Delete the current instance before creating the new one
1559 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1560 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1561 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1562 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563
Lloyd Pique441d5042018-10-18 16:49:51 -07001564 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001565 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001566
1567 if (vrFlingerRequestsDisplay) {
1568 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570
1571 mVisibleRegionsDirty = true;
1572 invalidateHwcGeometry();
1573
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001574 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001575 display = getDefaultDisplayDeviceLocked();
1576 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001577 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001578
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001580 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 const nsecs_t period = activeConfig->getVsyncPeriod();
1582 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001583
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001584 // The present fences returned from vr_hwc are not an accurate
1585 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001586 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001587 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1588 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001589 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001590 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001591 !hasSyncFramework);
1592 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001593
Steven Thomasb02664d2017-07-26 18:48:28 -07001594 // Use phase of 0 since phase is not known.
1595 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001596 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1597 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001598
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001599 resyncToHardwareVsync(false);
1600
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001601 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001602 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001603}
1604
Mathias Agopian4fec8732012-06-29 14:12:52 -07001605void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001606 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001607 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001608 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001609 if (mUseScheduler) {
1610 // This call is made each time SF wakes up and creates a new frame.
1611 mScheduler->incrementFrameCounter();
1612 }
Dan Stoza50182882016-07-08 12:02:20 -07001613 bool frameMissed = !mHadClientComposition &&
1614 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 (mPreviousPresentFence->getSignalTime() ==
1616 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001617 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001618 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001619 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001620 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001621 if (mPropagateBackpressure) {
1622 signalLayerUpdate();
1623 break;
1624 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001625 }
Dan Stoza50182882016-07-08 12:02:20 -07001626
Steven Thomas050b2c82017-03-06 11:45:16 -08001627 // Now that we're going to make it to the handleMessageTransaction()
1628 // call below it's safe to call updateVrFlinger(), which will
1629 // potentially trigger a display handoff.
1630 updateVrFlinger();
1631
Dan Stoza6b9454d2014-11-07 16:00:59 -08001632 bool refreshNeeded = handleMessageTransaction();
1633 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001634 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001635 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001636 // Signal a refresh if a transaction modified the window state,
1637 // a new buffer was latched, or if HWC has requested a full
1638 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001639 signalRefresh();
1640 }
1641 break;
1642 }
1643 case MessageQueue::REFRESH: {
1644 handleMessageRefresh();
1645 break;
1646 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001647 }
1648}
1649
Dan Stoza6b9454d2014-11-07 16:00:59 -08001650bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001651 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001652
1653 // Apply any ready transactions in the queues if there are still transactions that have not been
1654 // applied, wake up during the next vsync period and check again
1655 bool transactionNeeded = false;
1656 if (!flushTransactionQueues()) {
1657 transactionNeeded = true;
1658 }
1659
Mathias Agopian4fec8732012-06-29 14:12:52 -07001660 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001661 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001662 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001663
1664 if (transactionNeeded) {
1665 setTransactionFlags(eTransactionNeeded);
1666 }
1667
1668 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001669}
1670
Mathias Agopian4fec8732012-06-29 14:12:52 -07001671void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001672 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001673
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001674 mRefreshPending = false;
1675
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001676 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001677 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001678 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001679 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001680 for (const auto& [token, display] : mDisplays) {
1681 beginFrame(display);
1682 prepareFrame(display);
1683 doDebugFlashRegions(display, repaintEverything);
1684 doComposition(display, repaintEverything);
1685 }
1686
Adrian Roos1e1a1282017-11-01 19:05:31 +01001687 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001688 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001689
1690 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001691 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001692
Dan Stozabfbffeb2016-07-21 14:49:33 -07001693 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001694 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001695 mHadClientComposition =
1696 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001697 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698
Alec Mouri86770e52018-09-24 22:40:58 +00001699 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001700 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001701 if (mHadClientComposition) {
1702 base::unique_fd flushFence(getRenderEngine().flush());
1703 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1704 getBE().flushFence = new Fence(std::move(flushFence));
1705 } else {
1706 // Cleanup for hygiene.
1707 getBE().flushFence = Fence::NO_FENCE;
1708 }
1709 }
1710
Jorim Jaggi90535212018-05-23 23:44:06 +02001711 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001712
David Sodman7e4ae112018-02-09 15:02:28 -08001713 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001714 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001715 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001716 compositionInfo.hwc.hwcLayer = nullptr;
1717 }
David Sodmanba340492018-08-05 21:51:33 -07001718 }
David Sodman7e4ae112018-02-09 15:02:28 -08001719
1720 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001722
David Sodmanfa9b2af2017-12-24 13:28:59 -08001723
1724bool SurfaceFlinger::handleMessageInvalidate() {
1725 ATRACE_CALL();
1726 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001727}
1728
David Sodman79bba0e2018-08-05 18:07:49 -07001729void SurfaceFlinger::calculateWorkingSet() {
1730 ATRACE_CALL();
1731 ALOGV(__FUNCTION__);
1732
David Sodman79bba0e2018-08-05 18:07:49 -07001733 // build the h/w work list
1734 if (CC_UNLIKELY(mGeometryInvalid)) {
1735 mGeometryInvalid = false;
1736 for (const auto& [token, display] : mDisplays) {
1737 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738 if (!displayId) {
1739 continue;
1740 }
David Sodman79bba0e2018-08-05 18:07:49 -07001741
Dominik Laskowski075d3172018-05-24 15:50:06 -07001742 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1743 for (size_t i = 0; i < currentLayers.size(); i++) {
1744 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001745
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746 if (!layer->hasHwcLayer(*displayId)) {
1747 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1748 layer->forceClientComposition(*displayId);
1749 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001750 }
1751 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752
1753 layer->setGeometry(display, i);
1754 if (mDebugDisableHWC || mDebugRegion) {
1755 layer->forceClientComposition(*displayId);
1756 }
David Sodman79bba0e2018-08-05 18:07:49 -07001757 }
1758 }
1759 }
1760
1761 // Set the per-frame data
1762 for (const auto& [token, display] : mDisplays) {
1763 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001764 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001765 continue;
1766 }
1767
1768 if (mDrawingState.colorMatrixChanged) {
1769 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001770 status_t result =
1771 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001772 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1773 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001774 }
1775 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1776 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001777 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001778 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1779 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1780 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001781 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001782 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1783 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1784 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001786 }
1787
Peiyong Lind3788632018-09-18 16:01:31 -07001788 // TODO(b/111562338) remove when composer 2.3 is shipped.
1789 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001790 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001791 }
1792
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001793 if (layer->getRoundedCornerState().radius > 0.0f) {
1794 layer->forceClientComposition(*displayId);
1795 }
1796
Dominik Laskowski075d3172018-05-24 15:50:06 -07001797 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001798 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001799 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001800 continue;
1801 }
1802
Dominik Laskowski075d3172018-05-24 15:50:06 -07001803 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1804 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001805 }
1806
Peiyong Lin13effd12018-07-24 17:01:47 -07001807 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001808 ColorMode colorMode;
1809 Dataspace dataSpace;
1810 RenderIntent renderIntent;
1811 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1812 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1813 }
1814 }
1815
1816 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001817
1818 for (const auto& [token, display] : mDisplays) {
1819 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001820 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001821 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001822
1823 if (displayId) {
1824 if (!layer->setHwcLayer(*displayId)) {
1825 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1826 }
1827 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001828 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001829
Dominik Laskowski05275f12018-11-01 15:03:24 -07001830 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001831 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1832 }
1833 }
David Sodman79bba0e2018-08-05 18:07:49 -07001834}
1835
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001837{
1838 // is debugging enabled
1839 if (CC_LIKELY(!mDebugRegion))
1840 return;
1841
David Sodmanfa9b2af2017-12-24 13:28:59 -08001842 if (display->isPoweredOn()) {
1843 // transform the dirty region into this screen's coordinate space
1844 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1845 if (!dirtyRegion.isEmpty()) {
1846 // redraw the whole screen
1847 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001848
David Sodmanfa9b2af2017-12-24 13:28:59 -08001849 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001850 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001851 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001852
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001853 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854 }
1855 }
1856
David Sodmanfa9b2af2017-12-24 13:28:59 -08001857 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858
1859 if (mDebugRegion > 1) {
1860 usleep(mDebugRegion * 1000);
1861 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001862
Dominik Laskowski05275f12018-11-01 15:03:24 -07001863 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864}
1865
Adrian Roos1e1a1282017-11-01 19:05:31 +01001866void SurfaceFlinger::doTracing(const char* where) {
1867 ATRACE_CALL();
1868 ATRACE_NAME(where);
1869 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001870 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001871 }
1872}
1873
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001874void SurfaceFlinger::logLayerStats() {
1875 ATRACE_CALL();
1876 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001877 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001878 if (display->isPrimary()) {
1879 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001880 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001881 }
1882 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001883
1884 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001885 }
1886}
1887
David Sodman2b406362017-12-15 13:33:47 -08001888void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 ATRACE_CALL();
1891 ALOGV("preComposition");
1892
David Sodman2b406362017-12-15 13:33:47 -08001893 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1894
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001896 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001897 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 needExtraInvalidate = true;
1899 }
Robert Carr2047fae2016-11-28 14:09:09 -08001900 });
1901
Mathias Agopiancd60f992012-08-16 16:28:27 -07001902 if (needExtraInvalidate) {
1903 signalLayerUpdate();
1904 }
1905}
1906
Ana Krulece588e312018-09-18 12:32:24 -07001907void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1908 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 // Update queue of past composite+present times and determine the
1910 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001911 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001913 while (!getBE().mCompositePresentTimes.empty()) {
1914 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915 // Cached values should have been updated before calling this method,
1916 // which helps avoid duplicate syscalls.
1917 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1918 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1919 break;
1920 }
1921 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001922 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001923 }
1924
1925 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001926 while (getBE().mCompositePresentTimes.size() > 16) {
1927 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 }
1929
Ana Krulece588e312018-09-18 12:32:24 -07001930 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001931}
1932
Ana Krulece588e312018-09-18 12:32:24 -07001933void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1934 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935 // Integer division and modulo round toward 0 not -inf, so we need to
1936 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001937 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1938 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1939 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001940
Brian Andersond0010582017-03-07 13:20:31 -08001941 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1942 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001943 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001944 }
1945
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946 // Snap the latency to a value that removes scheduling jitter from the
1947 // composition and present times, which often have >1ms of jitter.
1948 // Reducing jitter is important if an app attempts to extrapolate
1949 // something (such as user input) to an accurate diasplay time.
1950 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1951 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001952 nsecs_t bias = stats.vsyncPeriod / 2;
1953 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1954 nsecs_t snappedCompositeToPresentLatency =
1955 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001956
David Sodman99974d22017-11-28 12:04:33 -08001957 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001958 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1959 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001960 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001961}
1962
Ady Abraham8164d482019-01-11 14:47:59 -08001963// debug patch for b/119477596 - add stack guards to catch stack
1964// corruptions and disable clang optimizations.
1965// The code below is temporary and planned to be removed once stack
1966// corruptions are found.
1967#pragma clang optimize off
1968class StackGuard {
1969public:
1970 StackGuard(const char* name, const char* func, int line) {
1971 guarders.reserve(MIN_CAPACITY);
1972 guarders.push_back({this, name, func, line});
1973 validate();
1974 }
1975 ~StackGuard() {
1976 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1977 if (i->guard == this) {
1978 guarders.erase(i);
1979 break;
1980 }
1981 }
1982 }
1983
1984 static void validate() {
1985 for (const auto& guard : guarders) {
1986 if (guard.guard->cookie != COOKIE_VALUE) {
1987 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1988 CallStack stack(LOG_TAG);
1989 abort();
1990 }
1991 }
1992 }
1993
1994private:
1995 uint64_t cookie = COOKIE_VALUE;
1996 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1997 static constexpr size_t MIN_CAPACITY = 16;
1998
1999 struct GuarderElement {
2000 StackGuard* guard;
2001 const char* name;
2002 const char* func;
2003 int line;
2004 };
2005
2006 static std::vector<GuarderElement> guarders;
2007};
2008std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2009
2010#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2011
2012#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002013void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014{
Ady Abraham8164d482019-01-11 14:47:59 -08002015 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 ATRACE_CALL();
2017 ALOGV("postComposition");
2018
Brian Anderson3546a3f2016-07-14 11:51:14 -07002019 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002020 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002021 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002022 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002023 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002024 }
Ady Abraham8164d482019-01-11 14:47:59 -08002025 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002026
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002027 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002029 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030
David Sodman73beded2017-11-15 11:56:06 -08002031 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002033 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2034
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002035 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002036 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002037 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002038 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039 } else {
2040 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2041 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002042
Ady Abraham8164d482019-01-11 14:47:59 -08002043 ASSERT_ON_STACK_GUARD();
2044
David Sodman73beded2017-11-15 11:56:06 -08002045 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002046 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002047 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002048 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002049 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002050 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051
Ana Krulece588e312018-09-18 12:32:24 -07002052 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002054 if (mUseScheduler) {
2055 mScheduler->getDisplayStatInfo(&stats);
2056 } else {
2057 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2058 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2059 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002060
Ady Abraham8164d482019-01-11 14:47:59 -08002061 ASSERT_ON_STACK_GUARD();
2062
David Sodman2b406362017-12-15 13:33:47 -08002063 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064 // when we started doing work for this frame, but that should be okay
2065 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002066 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002067 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002068 DEFINE_STACK_GUARD(compositorTiming);
2069
Brian Andersond0010582017-03-07 13:20:31 -08002070 {
David Sodman99974d22017-11-28 12:04:33 -08002071 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002072 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002073 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002074
2075 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002076 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077
Robert Carr2047fae2016-11-28 14:09:09 -08002078 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002079 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2080 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002081 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002082 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002083 recordBufferingStats(layer->getName().string(),
2084 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002085 }
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002087 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002089 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002091 if (mUseScheduler) {
2092 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002093 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002094 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002095 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2096 enableHardwareVsync();
2097 } else {
2098 disableHardwareVsync(false);
2099 }
Ady Abraham8164d482019-01-11 14:47:59 -08002100 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002101 }
2102 }
2103
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002104 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002105 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002106 if (mUseScheduler) {
2107 mScheduler->enableHardwareVsync();
2108 } else {
2109 enableHardwareVsync();
2110 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002111 }
2112 }
2113
Ady Abraham8164d482019-01-11 14:47:59 -08002114 ASSERT_ON_STACK_GUARD();
2115
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116 if (mAnimCompositionPending) {
2117 mAnimCompositionPending = false;
2118
Brian Anderson4e606e32017-03-16 15:34:57 -07002119 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002121 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002122
2123 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002124 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002125 // The HWC doesn't support present fences, so use the refresh
2126 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002127 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002128 DEFINE_STACK_GUARD(presentTime);
2129
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002130 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002131 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002132 }
2133 mAnimFrameTracker.advanceFrame();
2134 }
Dan Stozab90cf072015-03-05 11:05:59 -08002135
Ady Abraham8164d482019-01-11 14:47:59 -08002136 ASSERT_ON_STACK_GUARD();
2137
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002138 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002139 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002140 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002141 }
2142
Ady Abraham8164d482019-01-11 14:47:59 -08002143 ASSERT_ON_STACK_GUARD();
2144
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002145 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002146
Ady Abraham8164d482019-01-11 14:47:59 -08002147 ASSERT_ON_STACK_GUARD();
2148
Dominik Laskowski075d3172018-05-24 15:50:06 -07002149 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002150 return;
2151 }
2152
2153 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002155 if (mHasPoweredOff) {
2156 mHasPoweredOff = false;
2157 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002158 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002159 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002160 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002161 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002162 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2163 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002164 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002165 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002166 }
David Sodman4a36e932017-11-07 14:29:47 -08002167 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002168
2169 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002170 }
David Sodman4a36e932017-11-07 14:29:47 -08002171 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002172 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002173
2174 {
2175 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002176 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002177 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002179 if (refillCount > 0) {
2180 const size_t offset = mTexturePool.size();
2181 mTexturePool.resize(mTexturePoolSize);
2182 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2183 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2184 }
Ady Abraham8164d482019-01-11 14:47:59 -08002185 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002186 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002187
Marissa Wallfda30bb2018-10-12 11:34:28 -07002188 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002189 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002190
2191 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002192}
Ady Abraham8164d482019-01-11 14:47:59 -08002193#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194
2195void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 ATRACE_CALL();
2197 ALOGV("rebuildLayerStacks");
2198
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002199 // We need to clear these out now as these may be holding on to a
2200 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2201 // also holds a reference. When the set of visible layers is recomputed,
2202 // some layers may be destroyed if the only thing keeping them alive was
2203 // that list of visible layers associated with each display. The layer
2204 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2205 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2206 for (const auto& [token, display] : mDisplays) {
2207 getBE().mCompositionInfo[token].clear();
2208 }
2209
Mathias Agopiancd60f992012-08-16 16:28:27 -07002210 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002212 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 mVisibleRegionsDirty = false;
2214 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002215
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002216 for (const auto& pair : mDisplays) {
2217 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002218 Region opaqueRegion;
2219 Region dirtyRegion;
2220 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002221 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002222 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002223 const Rect bounds = display->getBounds();
2224 if (display->isPoweredOn()) {
2225 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002226
Jeff Sharkey76488112017-02-27 14:15:18 -07002227 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002228 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002229 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002230 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002231 Region drawRegion(tr.transform(
2232 layer->visibleNonTransparentRegion));
2233 drawRegion.andSelf(bounds);
2234 if (!drawRegion.isEmpty()) {
2235 layersSortedByZ.add(layer);
2236 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002237 // Clear out the HWC layer if this layer was
2238 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002239 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002241 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002242 // WM changes display->layerStack upon sleep/awake.
2243 // Here we make sure we delete the HWC layers even if
2244 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002246 }
2247
2248 // If a layer is not going to get a release fence because
2249 // it is invisible, but it is also going to release its
2250 // old buffer, add it to the list of layers needing
2251 // fences.
2252 if (hwcLayerDestroyed) {
2253 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2254 mLayersWithQueuedFrames.cend(), layer);
2255 if (found != mLayersWithQueuedFrames.cend()) {
2256 layersNeedingFences.add(layer);
2257 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002258 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 });
2260 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002261 display->setVisibleLayersSortedByZ(layersSortedByZ);
2262 display->setLayersNeedingFences(layersNeedingFences);
2263 display->undefinedRegion.set(bounds);
2264 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2265 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002266 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002267 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002268}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002269
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002272// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002274// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002275// The returned HDR data space is one of
2276// - Dataspace::UNKNOWN
2277// - Dataspace::BT2020_HLG
2278// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2280 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002281 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 *outHdrDataSpace = Dataspace::UNKNOWN;
2283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002285 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286 case Dataspace::V0_SCRGB:
2287 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002288 case Dataspace::BT2020:
2289 case Dataspace::BT2020_ITU:
2290 case Dataspace::BT2020_LINEAR:
2291 case Dataspace::DISPLAY_BT2020:
2292 bestDataSpace = Dataspace::DISPLAY_BT2020;
2293 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002295 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 case Dataspace::BT2020_PQ:
2298 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002299 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002301 case Dataspace::BT2020_HLG:
2302 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 // When there's mixed PQ content and HLG content, we set the HDR
2304 // data space to be BT2020_PQ and convert HLG to PQ.
2305 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2306 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002307 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308 break;
2309 default:
2310 break;
2311 }
Romain Guy54f154a2017-10-24 21:40:32 +01002312 }
2313
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002315}
2316
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2319 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2321 *outMode = ColorMode::NATIVE;
2322 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002324 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002325 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002326
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002328 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329
Peiyong Lindfde5112018-06-05 10:58:41 -07002330 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002331 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002332 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002333 if (isHdr) {
2334 bestDataSpace = hdrDataSpace;
2335 }
2336
Chia-I Wu0d711262018-05-21 15:19:35 -07002337 RenderIntent intent;
2338 switch (mDisplayColorSetting) {
2339 case DisplayColorSetting::MANAGED:
2340 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002341 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002342 break;
2343 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002344 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002345 break;
2346 default: // vendor display color setting
2347 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2348 break;
2349 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002350
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002351 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002352}
2353
David Sodmanfa9b2af2017-12-24 13:28:59 -08002354void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002355{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002356 bool dirty = !display->getDirtyRegion(false).isEmpty();
2357 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2358 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002359
David Sodmanfa9b2af2017-12-24 13:28:59 -08002360 // If nothing has changed (!dirty), don't recompose.
2361 // If something changed, but we don't currently have any visible layers,
2362 // and didn't when we last did a composition, then skip it this time.
2363 // The second rule does two things:
2364 // - When all layers are removed from a display, we'll emit one black
2365 // frame, then nothing more until we get new layers.
2366 // - When a display is created with a private layer stack, we won't
2367 // emit any black frames until a layer is added to the layer stack.
2368 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002369
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 const char flagPrefix[] = {'-', '+'};
2371 static_cast<void>(flagPrefix);
2372 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2373 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2374 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002375
David Sodmanfa9b2af2017-12-24 13:28:59 -08002376 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002377
David Sodmanfa9b2af2017-12-24 13:28:59 -08002378 if (mustRecompose) {
2379 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002380 }
2381}
2382
David Sodmanfa9b2af2017-12-24 13:28:59 -08002383void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002384{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 if (!display->isPoweredOn()) {
2386 return;
David Sodman2b406362017-12-15 13:33:47 -08002387 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388
Dominik Laskowski05275f12018-11-01 15:03:24 -07002389 status_t result = display->prepareFrame(getHwComposer(),
2390 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2392 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002393}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002394
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002396 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002397 ALOGV("doComposition");
2398
David Sodmanfa9b2af2017-12-24 13:28:59 -08002399 if (display->isPoweredOn()) {
2400 // transform the dirty region into this screen's coordinate space
2401 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002402
David Sodmanfa9b2af2017-12-24 13:28:59 -08002403 // repaint the framebuffer (if needed)
2404 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002405
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406 display->dirtyRegion.clear();
2407 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002408 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002410}
2411
David Sodmanfa9b2af2017-12-24 13:28:59 -08002412void SurfaceFlinger::postFrame()
2413{
2414 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 const auto display = getDefaultDisplayDeviceLocked();
2416 if (display && getHwComposer().isConnected(*display->getId())) {
2417 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2419 logFrameStats();
2420 }
2421 }
2422}
2423
2424void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425{
Mathias Agopian841cde52012-03-01 15:44:37 -08002426 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002428
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002430
David Sodmanfa9b2af2017-12-24 13:28:59 -08002431 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002432 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 if (displayId) {
2434 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002435 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002436 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002437 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002438 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002439
Chia-I Wu7b549592017-11-15 09:14:57 -08002440 // The layer buffer from the previous frame (if any) is released
2441 // by HWC only when the release fence from this frame (if any) is
2442 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002443 if (displayId && layer->hasHwcLayer(*displayId)) {
2444 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2445 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002446 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002447
2448 // If the layer was client composited in the previous frame, we
2449 // need to merge with the previous client target acquire fence.
2450 // Since we do not track that, always merge with the current
2451 // client target acquire fence when it is available, even though
2452 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002453 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002454 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002456 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002457
David Sodman15094112018-10-11 09:39:37 -07002458 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 }
Chia-I Wu83806892017-11-16 10:50:20 -08002460
2461 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002462 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002463 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002465 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002466 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002468 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002469 }
2470 }
2471
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 if (displayId) {
2473 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002474 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476}
2477
Mathias Agopian87baae12012-07-31 12:38:26 -07002478void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479{
Mathias Agopian841cde52012-03-01 15:44:37 -08002480 ATRACE_CALL();
2481
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002482 // here we keep a copy of the drawing state (that is the state that's
2483 // going to be overwritten by handleTransactionLocked()) outside of
2484 // mStateLock so that the side-effects of the State assignment
2485 // don't happen with mStateLock held (which can cause deadlocks).
2486 State drawingState(mDrawingState);
2487
Mathias Agopianca4d3602011-05-19 15:38:14 -07002488 Mutex::Autolock _l(mStateLock);
2489 const nsecs_t now = systemTime();
2490 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491
Mathias Agopianca4d3602011-05-19 15:38:14 -07002492 // Here we're guaranteed that some transaction flags are set
2493 // so we can call handleTransactionLocked() unconditionally.
2494 // We call getTransactionFlags(), which will also clear the flags,
2495 // with mStateLock held to guarantee that mCurrentState won't change
2496 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002497
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002498 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002500 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002501
Mathias Agopianca4d3602011-05-19 15:38:14 -07002502 mLastTransactionTime = systemTime() - now;
2503 mDebugInTransaction = 0;
2504 invalidateHwcGeometry();
2505 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002506}
2507
Lloyd Piqueba04e622017-12-14 17:11:26 -08002508void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2509 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 const std::optional<DisplayIdentificationInfo> info =
2511 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002512
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 continue;
2515 }
2516
Lloyd Piqueba04e622017-12-14 17:11:26 -08002517 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002519 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 mPhysicalDisplayTokens[info->id] = new BBinder();
2521 DisplayDeviceState state;
2522 state.displayId = info->id;
2523 state.isSecure = true; // All physical displays are currently considered secure.
2524 state.displayName = info->name;
2525 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2526 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002527 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002529 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2532 if (index >= 0) {
2533 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2534 mInterceptor->saveDisplayDeletion(state.sequenceId);
2535 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002536 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002538 }
2539
2540 processDisplayChangesLocked();
2541 }
2542
2543 mPendingHotplugEvents.clear();
2544}
2545
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2548 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2549 const sp<IGraphicBufferProducer>& producer) {
2550 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002551 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002553 creationArgs.isSecure = state.isSecure;
2554 creationArgs.displaySurface = dispSurface;
2555 creationArgs.hasWideColorGamut = false;
2556 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002557
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2559 creationArgs.isPrimary = isInternalDisplay;
2560
2561 if (useColorManagement && displayId) {
2562 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002564 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002565 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002566 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002567
Dominik Laskowski7e045462018-05-30 13:02:02 -07002568 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002570 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571 }
tangrobin6753a022018-08-10 10:58:54 +08002572 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 if (displayId) {
2575 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002576 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002578 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002579
Lloyd Pique90c115d2018-09-18 21:39:42 -07002580 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002581 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002582 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002583
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 // Make sure that composition can never be stalled by a virtual display
2585 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002586 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002587 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2589 }
2590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 creationArgs.displayInstallOrientation =
2592 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002593
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596
Lloyd Pique90c115d2018-09-18 21:39:42 -07002597 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
2599 if (maxFrameBufferAcquiredBuffers >= 3) {
2600 nativeWindowSurface->preallocateBuffers();
2601 }
2602
2603 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002604 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002605 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002607 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002610 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 if (!state.isVirtual()) {
2612 LOG_ALWAYS_FATAL_IF(!displayId);
2613 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002614 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002616 display->setLayerStack(state.layerStack);
2617 display->setProjection(state.orientation, state.viewport, state.frame);
2618 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621}
2622
Lloyd Pique347200f2017-12-14 17:00:15 -08002623void SurfaceFlinger::processDisplayChangesLocked() {
2624 // here we take advantage of Vector's copy-on-write semantics to
2625 // improve performance by skipping the transaction entirely when
2626 // know that the lists are identical
2627 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2628 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2629 if (!curr.isIdenticalTo(draw)) {
2630 mVisibleRegionsDirty = true;
2631 const size_t cc = curr.size();
2632 size_t dc = draw.size();
2633
2634 // find the displays that were removed
2635 // (ie: in drawing state but not in current state)
2636 // also handle displays that changed
2637 // (ie: displays that are in both lists)
2638 for (size_t i = 0; i < dc;) {
2639 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2640 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002641 // Save display IDs before disconnecting.
2642 const auto internalDisplayId = getInternalDisplayId();
2643 const auto externalDisplayId = getExternalDisplayId();
2644
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002646 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2647 display->disconnect(getHwComposer());
2648 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002650 if (mUseScheduler) {
2651 mScheduler->hotplugReceived(mAppConnectionHandle,
2652 EventThread::DisplayType::Primary, false);
2653 } else {
2654 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2655 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002657 if (mUseScheduler) {
2658 mScheduler->hotplugReceived(mAppConnectionHandle,
2659 EventThread::DisplayType::External, false);
2660 } else {
2661 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2662 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002663 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 } else {
2666 // this display is in both lists. see if something changed.
2667 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2670 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2671 if (state_binder != draw_binder) {
2672 // changing the surface is like destroying and
2673 // recreating the DisplayDevice, so we just remove it
2674 // from the drawing state, so that it get re-added
2675 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2677 display->disconnect(getHwComposer());
2678 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 mDrawingState.displays.removeItemsAt(i);
2681 dc--;
2682 // at this point we must loop to the next item
2683 continue;
2684 }
2685
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002688 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 }
2690 if ((state.orientation != draw[i].orientation) ||
2691 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693 }
2694 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 }
2697 }
2698 }
2699 ++i;
2700 }
2701
2702 // find displays that were added
2703 // (ie: in current state but not in drawing state)
2704 for (size_t i = 0; i < cc; i++) {
2705 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2706 const DisplayDeviceState& state(curr[i]);
2707
2708 sp<DisplaySurface> dispSurface;
2709 sp<IGraphicBufferProducer> producer;
2710 sp<IGraphicBufferProducer> bqProducer;
2711 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002712 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713
Dominik Laskowski075d3172018-05-24 15:50:06 -07002714 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002715 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 // Virtual displays without a surface are dormant:
2717 // they have external state (layer stack, projection,
2718 // etc.) but no internal state (i.e. a DisplayDevice).
2719 if (state.surface != nullptr) {
2720 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002721 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 int width = 0;
2723 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2724 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2725 int height = 0;
2726 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2727 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2728 int intFormat = 0;
2729 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2730 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002731 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 displayId =
2734 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736
2737 // TODO: Plumb requested format back up to consumer
2738
2739 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002740 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 bqProducer, bqConsumer,
2742 state.displayName);
2743
2744 dispSurface = vds;
2745 producer = vds;
2746 }
2747 } else {
2748 ALOGE_IF(state.surface != nullptr,
2749 "adding a supported display, but rendering "
2750 "surface is provided (%p), ignoring it",
2751 state.surface.get());
2752
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 displayId = state.displayId;
2754 LOG_ALWAYS_FATAL_IF(!displayId);
2755 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 producer = bqProducer;
2757 }
2758
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002762 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002763 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002764 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002765 LOG_ALWAYS_FATAL_IF(!displayId);
2766
2767 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002768 if (mUseScheduler) {
2769 mScheduler->hotplugReceived(mAppConnectionHandle,
2770 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002771 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002772 } else {
2773 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2774 true);
2775 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002777 if (mUseScheduler) {
2778 mScheduler->hotplugReceived(mAppConnectionHandle,
2779 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002780 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002781 } else {
2782 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2783 true);
2784 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002785 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 }
2787 }
2788 }
2789 }
2790 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002791
2792 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002793}
2794
Mathias Agopian87baae12012-07-31 12:38:26 -07002795void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002796{
Dan Stoza7dde5992015-05-22 09:51:44 -07002797 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002798 mCurrentState.traverseInZOrder([](Layer* layer) {
2799 layer->notifyAvailableFrames();
2800 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 /*
2803 * Traversal of the children
2804 * (perform the transaction for each of them if needed)
2805 */
2806
Robert Carr720e5062018-07-30 17:45:14 -07002807 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002808 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002809 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002811 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812
2813 const uint32_t flags = layer->doTransaction(0);
2814 if (flags & Layer::eVisibleRegion)
2815 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002816
2817 if (flags & Layer::eInputInfoChanged) {
2818 inputChanged = true;
2819 }
Robert Carr2047fae2016-11-28 14:09:09 -08002820 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 }
2822
2823 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 */
2826
Mathias Agopiane57f2922012-08-09 16:29:12 -07002827 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002828 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002829 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002832 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002833 // The transform hint might have changed for some layers
2834 // (either because a display has changed, or because a layer
2835 // as changed).
2836 //
2837 // Walk through all the layers in currentLayers,
2838 // and update their transform hint.
2839 //
2840 // If a layer is visible only on a single display, then that
2841 // display is used to calculate the hint, otherwise we use the
2842 // default display.
2843 //
2844 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2845 // the hint is set before we acquire a buffer from the surface texture.
2846 //
2847 // NOTE: layer transactions have taken place already, so we use their
2848 // drawing state. However, SurfaceFlinger's own transaction has not
2849 // happened yet, so we must use the current state layer list
2850 // (soon to become the drawing state list).
2851 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002853 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002854 bool first = true;
2855 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002856 // NOTE: we rely on the fact that layers are sorted by
2857 // layerStack first (so we don't have to traverse the list
2858 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002860 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002861 currentlayerStack = layerStack;
2862 // figure out if this layerstack is mirrored
2863 // (more than one display) if so, pick the default display,
2864 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002865 hintDisplay = nullptr;
2866 for (const auto& [token, display] : mDisplays) {
2867 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2868 if (hintDisplay) {
2869 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002870 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002872 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002873 }
2874 }
2875 }
2876 }
Chet Haase91d25932013-04-11 15:24:55 -07002877
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002878 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002879 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2880 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002881
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002882 // could be null when this layer is using a layerStack
2883 // that is not visible on any display. Also can occur at
2884 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002886 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002887
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002889 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002890 if (hintDisplay) {
2891 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002892 }
Robert Carr2047fae2016-11-28 14:09:09 -08002893
2894 first = false;
2895 });
Mathias Agopian84300952012-11-21 16:02:13 -08002896 }
2897
2898
Mathias Agopian3559b072012-08-15 13:46:03 -07002899 /*
2900 * Perform our own transaction if needed
2901 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002902
2903 if (mLayersAdded) {
2904 mLayersAdded = false;
2905 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002906 mVisibleRegionsDirty = true;
2907 }
2908
2909 // some layers might have been removed, so
2910 // we need to update the regions they're exposing.
2911 if (mLayersRemoved) {
2912 mLayersRemoved = false;
2913 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002914 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002915 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002916 // this layer is not visible anymore
2917 // TODO: we could traverse the tree from front to back and
2918 // compute the actual visible region
2919 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 Region visibleReg;
2921 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002922 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002923 }
Robert Carr2047fae2016-11-28 14:09:09 -08002924 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925 }
2926
2927 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002928
Vishnu Nairde19f852018-12-18 16:11:53 -08002929 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002930 updateInputWindows();
2931 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002932 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002933
Riley Andrews03414a12014-07-01 14:22:59 -07002934 updateCursorAsync();
2935}
2936
Robert Carr720e5062018-07-30 17:45:14 -07002937void SurfaceFlinger::updateInputWindows() {
2938 ATRACE_CALL();
2939
Vishnu Nairde19f852018-12-18 16:11:53 -08002940 if (mInputFlinger == nullptr) {
2941 return;
2942 }
2943
Robert Carr720e5062018-07-30 17:45:14 -07002944 Vector<InputWindowInfo> inputHandles;
2945
2946 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2947 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002948 // When calculating the screen bounds we ignore the transparent region since it may
2949 // result in an unwanted offset.
2950 inputHandles.add(layer->fillInputInfo(
2951 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002952 }
2953 });
2954 mInputFlinger->setInputWindows(inputHandles);
2955}
2956
chaviwfbe5d9c2018-12-26 12:23:37 -08002957void SurfaceFlinger::executeInputWindowCommands() {
2958 if (!mInputFlinger) {
2959 return;
2960 }
2961
2962 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2963 if (transferTouchFocusCommand.fromToken != nullptr &&
2964 transferTouchFocusCommand.toToken != nullptr &&
2965 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2966 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2967 transferTouchFocusCommand.toToken);
2968 }
2969 }
2970
2971 mInputWindowCommands.clear();
2972}
2973
Riley Andrews03414a12014-07-01 14:22:59 -07002974void SurfaceFlinger::updateCursorAsync()
2975{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002976 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002977 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002978 continue;
2979 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002981 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2982 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002983 }
2984 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002985}
2986
chaviw61626f22018-11-15 16:26:27 -08002987void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2988 if (layer->hasReadyFrame()) {
2989 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2990 if (layer->shouldPresentNow(expectedPresentTime)) {
2991 bool ignored = false;
2992 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2993 }
2994 }
2995 layer->releasePendingBuffer(systemTime());
2996}
2997
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998void SurfaceFlinger::commitTransaction()
2999{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003000 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003001 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003002 for (const auto& l : mLayersPendingRemoval) {
3003 recordBufferingStats(l->getName().string(),
3004 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003005
3006 // We need to release the HWC layers when the Layer is removed
3007 // from the current state otherwise the HWC layer just continues
3008 // showing at its last configured state until we eventually
3009 // abandon the buffer queue.
3010 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003011 l->destroyHwcLayersForAllDisplays();
3012 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003013 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 }
3015 mLayersPendingRemoval.clear();
3016 }
3017
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003018 // If this transaction is part of a window animation then the next frame
3019 // we composite should be considered an animation as well.
3020 mAnimCompositionPending = mAnimTransactionPending;
3021
Mathias Agopian4fec8732012-06-29 14:12:52 -07003022 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003023 // clear the "changed" flags in current state
3024 mCurrentState.colorMatrixChanged = false;
3025
Robert Carr1f0a16a2016-10-24 16:27:39 -07003026 mDrawingState.traverseInZOrder([](Layer* layer) {
3027 layer->commitChildList();
3028 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003029 mTransactionPending = false;
3030 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003031 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032}
3033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3035 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003036 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003037 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003038
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 Region aboveOpaqueLayers;
3040 Region aboveCoveredLayers;
3041 Region dirty;
3042
Mathias Agopian87baae12012-07-31 12:38:26 -07003043 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044
Robert Carr2047fae2016-11-28 14:09:09 -08003045 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003046 // start with the whole surface at its current location
3047 const Layer::State& s(layer->getDrawingState());
3048
Jesse Hall01e29052013-02-19 16:13:35 -08003049 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003051 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003052 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003053
Mathias Agopianab028732010-03-16 16:41:46 -07003054 /*
3055 * opaqueRegion: area of a surface that is fully opaque.
3056 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003058
3059 /*
3060 * visibleRegion: area of a surface that is visible on screen
3061 * and not fully transparent. This is essentially the layer's
3062 * footprint minus the opaque regions above it.
3063 * Areas covered by a translucent surface are considered visible.
3064 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003066
3067 /*
3068 * coveredRegion: area of a surface that is covered by all
3069 * visible regions above it (which includes the translucent areas).
3070 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003072
Jesse Halla8026d22012-09-25 13:25:04 -07003073 /*
3074 * transparentRegion: area of a surface that is hinted to be completely
3075 * transparent. This is only used to tell when the layer has no visible
3076 * non-transparent regions and can be removed from the layer list. It
3077 * does not affect the visibleRegion of this layer or any layers
3078 * beneath it. The hint may not be correct if apps don't respect the
3079 * SurfaceView restrictions (which, sadly, some don't).
3080 */
3081 Region transparentRegion;
3082
Mathias Agopianab028732010-03-16 16:41:46 -07003083
3084 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003085 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003086 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003090 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003091 if (!visibleRegion.isEmpty()) {
3092 // Remove the transparent area from the visible region
3093 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003094 if (tr.preserveRects()) {
3095 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003096 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003097 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003098 // transformation too complex, can't do the
3099 // transparent region optimization.
3100 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003101 }
Mathias Agopianab028732010-03-16 16:41:46 -07003102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103
Mathias Agopianab028732010-03-16 16:41:46 -07003104 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003105 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003106 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003107 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003108 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003109 // the opaque region is the layer's footprint
3110 opaqueRegion = visibleRegion;
3111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 }
3113 }
3114
Robert Carre5f4f692018-01-12 13:12:28 -08003115 if (visibleRegion.isEmpty()) {
3116 layer->clearVisibilityRegions();
3117 return;
3118 }
3119
Mathias Agopianab028732010-03-16 16:41:46 -07003120 // Clip the covered region to the visible region
3121 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3122
3123 // Update aboveCoveredLayers for next (lower) layer
3124 aboveCoveredLayers.orSelf(visibleRegion);
3125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126 // subtract the opaque region covered by the layers above us
3127 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128
3129 // compute this layer's dirty region
3130 if (layer->contentDirty) {
3131 // we need to invalidate the whole region
3132 dirty = visibleRegion;
3133 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003134 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135 layer->contentDirty = false;
3136 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003137 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003138 * the exposed region consists of two components:
3139 * 1) what's VISIBLE now and was COVERED before
3140 * 2) what's EXPOSED now less what was EXPOSED before
3141 *
3142 * note that (1) is conservative, we start with the whole
3143 * visible region but only keep what used to be covered by
3144 * something -- which mean it may have been exposed.
3145 *
3146 * (2) handles areas that were not covered by anything but got
3147 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003148 */
Mathias Agopianab028732010-03-16 16:41:46 -07003149 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003150 const Region oldVisibleRegion = layer->visibleRegion;
3151 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003152 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3153 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 }
3155 dirty.subtractSelf(aboveOpaqueLayers);
3156
3157 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003158 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159
Mathias Agopianab028732010-03-16 16:41:46 -07003160 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003162
Jesse Halla8026d22012-09-25 13:25:04 -07003163 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 layer->setVisibleRegion(visibleRegion);
3165 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003166 layer->setVisibleNonTransparentRegion(
3167 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003168 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169
Mathias Agopian87baae12012-07-31 12:38:26 -07003170 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171}
3172
Chia-I Wuab0c3192017-08-01 11:29:00 -07003173void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003174 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003175 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3176 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003177 }
3178 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003179}
3180
Dan Stoza6b9454d2014-11-07 16:00:59 -08003181bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003183 ALOGV("handlePageFlip");
3184
Brian Andersond6927fb2016-07-23 23:37:30 -07003185 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186
Mathias Agopian4fec8732012-06-29 14:12:52 -07003187 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003188 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003189 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003190
3191 // Store the set of layers that need updates. This set must not change as
3192 // buffers are being latched, as this could result in a deadlock.
3193 // Example: Two producers share the same command stream and:
3194 // 1.) Layer 0 is latched
3195 // 2.) Layer 0 gets a new frame
3196 // 2.) Layer 1 gets a new frame
3197 // 3.) Layer 1 is latched.
3198 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3199 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003200 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003201 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003202 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003203 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3204 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003205 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003206 } else {
3207 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003208 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003209 } else {
3210 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003211 }
Robert Carr2047fae2016-11-28 14:09:09 -08003212 });
3213
Lloyd Piquef2c79392018-12-20 16:23:33 -08003214 if (!mLayersWithQueuedFrames.empty()) {
3215 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3216 // writes to Layer current state. See also b/119481871
3217 Mutex::Autolock lock(mStateLock);
3218
3219 for (auto& layer : mLayersWithQueuedFrames) {
3220 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3221 layer->useSurfaceDamage();
3222 invalidateLayerStack(layer, dirty);
3223 if (layer->isBufferLatched()) {
3224 newDataLatched = true;
3225 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003226 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003227 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003228
Alec Mouri86770e52018-09-24 22:40:58 +00003229 // Clear the renderengine fence here...
3230 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3231 // clear instead of sp::clear.
3232 getBE().flushFence = Fence::NO_FENCE;
3233
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003234 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003235
Vishnu Nairde19f852018-12-18 16:11:53 -08003236 if (visibleRegions) {
3237 // Update input window info if the layer receives its first buffer.
3238 updateInputWindows();
3239 }
3240
Dan Stoza6b9454d2014-11-07 16:00:59 -08003241 // If we will need to wake up at some time in the future to deal with a
3242 // queued frame that shouldn't be displayed during this vsync period, wake
3243 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003244 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003245 signalLayerUpdate();
3246 }
3247
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003248 // enter boot animation on first buffer latch
3249 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3250 ALOGI("Enter boot animation");
3251 mBootStage = BootStage::BOOTANIMATION;
3252 }
3253
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003255 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256}
3257
Mathias Agopianad456f92011-01-13 17:53:01 -08003258void SurfaceFlinger::invalidateHwcGeometry()
3259{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003260 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003261}
3262
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003263void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003264 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003265 // We only need to actually compose the display if:
3266 // 1) It is being handled by hardware composer, which may need this to
3267 // keep its virtual display state machine in sync, or
3268 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003269 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003270 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003271 return;
3272 }
3273
Dan Stoza9e56aa02015-11-02 13:00:03 -08003274 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003275 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003276
3277 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003278 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279}
3280
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003281bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003284 const Region bounds(display->bounds());
3285 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003286 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003287 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003288 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003289
Peiyong Lind3788632018-09-18 16:01:31 -07003290 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003291 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003292
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003293 // Framebuffer will live in this scope for GPU composition.
3294 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3295
Dan Stoza9e56aa02015-11-02 13:00:03 -08003296 if (hasClientComposition) {
3297 ALOGV("hasClientComposition");
3298
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003299 sp<GraphicBuffer> buf = display->dequeueBuffer();
3300
3301 if (buf == nullptr) {
3302 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3303 "client composition for this frame",
3304 display->getDisplayName().c_str());
3305 return false;
3306 }
3307
3308 // Bind the framebuffer in this scope.
3309 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3310 buf->getNativeBuffer());
3311
3312 if (fbo->getStatus() != NO_ERROR) {
3313 ALOGW("Binding buffer for display [%s] failed with status: %d",
3314 display->getDisplayName().c_str(), fbo->getStatus());
3315 return false;
3316 }
3317
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003318 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003319 if (display->hasWideColorGamut()) {
3320 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003321 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003322 getRenderEngine().setOutputDataSpace(outputDataspace);
3323 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003324 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003325
Lloyd Pique441d5042018-10-18 16:49:51 -07003326 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003327 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003328 getHwComposer()
3329 .hasDisplayCapability(displayId,
3330 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003331
Peiyong Lind3788632018-09-18 16:01:31 -07003332 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003333 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3334 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003335 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003336 }
3337
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003338 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003339
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003340 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003341 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003342 // when using overlays, we assume a fully transparent framebuffer
3343 // NOTE: we could reduce how much we need to clear, for instance
3344 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003345 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003346 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003347 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003348 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003349 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003350 // we're left with the letterbox region
3351 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003352 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003353
3354 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003355 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003356
Mathias Agopianb9494d52012-04-18 02:28:45 -07003357 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003358 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003359 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003360 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003361 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003362 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003363
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003364 const Rect& bounds = display->getBounds();
3365 const Rect& scissor = display->getScissor();
3366 if (scissor != bounds) {
3367 // scissor doesn't match the screen's dimensions, so we
3368 // need to clear everything outside of it and enable
3369 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003370
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003371 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003372 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003373 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003374 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003375
Mathias Agopian85d751c2012-08-29 16:59:24 -07003376 /*
3377 * and then, render the layers targeted at the framebuffer
3378 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003379
Dan Stoza9e56aa02015-11-02 13:00:03 -08003380 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003381 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003382 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003383 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003384 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003385 displayTransform.transform(layer->visibleRegion)));
3386 ALOGV("Layer: %s", layer->getName().string());
3387 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003388 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003389 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003390 case HWC2::Composition::Cursor:
3391 case HWC2::Composition::Device:
3392 case HWC2::Composition::Sideband:
3393 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003394 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003395 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003396 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003397 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003398 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003399 // never clear the very first layer since we're
3400 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003401 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003402 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003403 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003404 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003405 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003406 if (layer->hasColorTransform()) {
3407 mat4 tmpMatrix;
3408 if (applyColorMatrix) {
3409 tmpMatrix = mDrawingState.colorMatrix;
3410 }
3411 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003412 getRenderEngine().setColorTransform(tmpMatrix);
3413 } else {
3414 getRenderEngine().setColorTransform(colorMatrix);
3415 }
David Sodmanc1498e62018-09-12 14:36:26 -07003416 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003417 break;
3418 }
3419 default:
3420 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003421 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 } else {
3423 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003424 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003425 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003426 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003427
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003428 // Perform some cleanup steps if we used client composition.
3429 if (hasClientComposition) {
3430 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003431 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003432 display->finishBuffer();
3433 // Clear out error flags here so that we don't wait until next
3434 // composition to log.
3435 getRenderEngine().checkErrors();
3436 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003437 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438}
3439
Chia-I Wu28e3a252018-09-07 12:05:02 -07003440void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003441 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003442 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003443}
3444
Dan Stoza7d89d062015-04-30 13:29:25 -07003445status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003446 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003447 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003448 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003449 const sp<Layer>& parent,
3450 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003451{
Dan Stoza7d89d062015-04-30 13:29:25 -07003452 // add this layer to the current state list
3453 {
3454 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003456 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3457 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003458 return NO_MEMORY;
3459 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003460 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003461 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003462 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003463 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003464 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003465 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 parent->addChild(lbc);
3467 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003468
Yiwei Zhang243b3782018-05-15 17:40:04 -07003469 if (gbc != nullptr) {
3470 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3471 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3472 mMaxGraphicBufferProducerListSize,
3473 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3474 mGraphicBufferProducerList.size(),
3475 mMaxGraphicBufferProducerListSize, mNumLayers);
3476 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003477 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003478 }
3479
Mathias Agopian96f08192010-06-02 23:28:45 -07003480 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003481 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003482
Dan Stoza7d89d062015-04-30 13:29:25 -07003483 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003484}
3485
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003486uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003487 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003488}
3489
Mathias Agopian3f844832013-08-07 21:24:32 -07003490uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003491 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492}
3493
Mathias Agopian3f844832013-08-07 21:24:32 -07003494uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003495 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003496}
3497
3498uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003499 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003500 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003501 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003502 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003503 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504 }
3505 return old;
3506}
3507
Marissa Wall713b63f2018-10-17 15:42:43 -07003508bool SurfaceFlinger::flushTransactionQueues() {
3509 Mutex::Autolock _l(mStateLock);
3510 auto it = mTransactionQueues.begin();
3511 while (it != mTransactionQueues.end()) {
3512 auto& [applyToken, transactionQueue] = *it;
3513
3514 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003515 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3516 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003517 break;
3518 }
chaviw273171b2018-12-26 11:46:30 -08003519 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003520 transactionQueue.pop();
3521 }
3522
3523 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3524 }
3525 return mTransactionQueues.empty();
3526}
3527
chaviwca27f252018-02-06 16:46:39 -08003528bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3529 for (const ComposerState& state : states) {
3530 // Here we need to check that the interface we're given is indeed
3531 // one of our own. A malicious client could give us a nullptr
3532 // IInterface, or one of its own or even one of our own but a
3533 // different type. All these situations would cause us to crash.
3534 if (state.client == nullptr) {
3535 return true;
3536 }
3537
3538 sp<IBinder> binder = IInterface::asBinder(state.client);
3539 if (binder == nullptr) {
3540 return true;
3541 }
3542
3543 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3544 return true;
3545 }
3546 }
3547 return false;
3548}
3549
Marissa Wall17b4e452018-12-26 16:32:34 -08003550bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3551 const Vector<ComposerState>& states) {
3552 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3553 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3554 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3555 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3556 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3557 return false;
3558 }
3559
Marissa Wall713b63f2018-10-17 15:42:43 -07003560 for (const ComposerState& state : states) {
3561 const layer_state_t& s = state.state;
3562 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3563 continue;
3564 }
3565 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003566 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003567 }
3568 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003569 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003570}
3571
3572void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3573 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003574 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003575 const InputWindowCommands& inputWindowCommands,
3576 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003577 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003578 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003579
chaviwca27f252018-02-06 16:46:39 -08003580 if (containsAnyInvalidClientState(states)) {
3581 return;
3582 }
3583
Marissa Wall713b63f2018-10-17 15:42:43 -07003584 // If its TransactionQueue already has a pending TransactionState or if it is pending
3585 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003586 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3587 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003588 setTransactionFlags(eTransactionNeeded);
3589 return;
3590 }
3591
chaviw273171b2018-12-26 11:46:30 -08003592 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003593}
3594
3595void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003596 const Vector<DisplayState>& displays, uint32_t flags,
3597 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003598 uint32_t transactionFlags = 0;
3599
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003600 if (flags & eAnimation) {
3601 // For window updates that are part of an animation we must wait for
3602 // previous animation "frames" to be handled.
3603 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003604 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003605 if (CC_UNLIKELY(err != NO_ERROR)) {
3606 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003607 // caller after a few seconds.
3608 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3609 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003610 mAnimTransactionPending = false;
3611 break;
3612 }
3613 }
3614 }
3615
chaviwca27f252018-02-06 16:46:39 -08003616 for (const DisplayState& display : displays) {
3617 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003618 }
3619
Marissa Walle2ffb422018-10-12 11:33:52 -07003620 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003621 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003622 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003623 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003624 // If the state doesn't require a traversal and there are callbacks, send them now
3625 if (!(clientStateFlags & eTraversalNeeded)) {
3626 mTransactionCompletedThread.sendCallbacks();
3627 }
3628 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003629
chaviw273171b2018-12-26 11:46:30 -08003630 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3631
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003632 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3633 // anyway. This can be used as a flush mechanism for previous async transactions.
3634 // Empty animation transaction can be used to simulate back-pressure, so also force a
3635 // transaction for empty animation transactions.
3636 if (transactionFlags == 0 &&
3637 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003638 transactionFlags = eTransactionNeeded;
3639 }
3640
Mathias Agopian386aa982011-11-07 21:58:03 -08003641 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003642 if (mInterceptor->isEnabled()) {
3643 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003644 }
Irvel468051e2016-06-13 16:44:44 -07003645
Mathias Agopian386aa982011-11-07 21:58:03 -08003646 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003647 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3648 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003649 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003650
3651 // if this is a synchronous transaction, wait for it to take effect
3652 // before returning.
3653 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003654 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003655 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003656 if (flags & eAnimation) {
3657 mAnimTransactionPending = true;
3658 }
3659 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003660 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3661 if (CC_UNLIKELY(err != NO_ERROR)) {
3662 // just in case something goes wrong in SF, return to the
3663 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003664 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3665 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003666 break;
3667 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003668 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669 }
3670}
3671
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003672uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3673 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3674 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003675
Mathias Agopiane57f2922012-08-09 16:29:12 -07003676 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003677 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3678
3679 const uint32_t what = s.what;
3680 if (what & DisplayState::eSurfaceChanged) {
3681 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3682 state.surface = s.surface;
3683 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003684 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003685 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003686 if (what & DisplayState::eLayerStackChanged) {
3687 if (state.layerStack != s.layerStack) {
3688 state.layerStack = s.layerStack;
3689 flags |= eDisplayTransactionNeeded;
3690 }
3691 }
3692 if (what & DisplayState::eDisplayProjectionChanged) {
3693 if (state.orientation != s.orientation) {
3694 state.orientation = s.orientation;
3695 flags |= eDisplayTransactionNeeded;
3696 }
3697 if (state.frame != s.frame) {
3698 state.frame = s.frame;
3699 flags |= eDisplayTransactionNeeded;
3700 }
3701 if (state.viewport != s.viewport) {
3702 state.viewport = s.viewport;
3703 flags |= eDisplayTransactionNeeded;
3704 }
3705 }
3706 if (what & DisplayState::eDisplaySizeChanged) {
3707 if (state.width != s.width) {
3708 state.width = s.width;
3709 flags |= eDisplayTransactionNeeded;
3710 }
3711 if (state.height != s.height) {
3712 state.height = s.height;
3713 flags |= eDisplayTransactionNeeded;
3714 }
3715 }
3716
Mathias Agopiane57f2922012-08-09 16:29:12 -07003717 return flags;
3718}
3719
Robert Carrd4ae7f32018-06-07 16:10:57 -07003720bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3721 IPCThreadState* ipc = IPCThreadState::self();
3722 const int pid = ipc->getCallingPid();
3723 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003724 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003725 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003726 return false;
3727 }
3728 return true;
3729}
3730
chaviwca27f252018-02-06 16:46:39 -08003731uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3732 const layer_state_t& s = composerState.state;
3733 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3734
Mathias Agopian13127d82013-03-05 17:47:11 -08003735 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003736 if (layer == nullptr) {
3737 return 0;
3738 }
3739
chaviw8b3871a2017-11-01 17:41:01 -07003740 uint32_t flags = 0;
3741
Garfield Tan8a3083e2018-12-03 13:21:07 -08003742 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003743 bool geometryAppliesWithResize =
3744 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003745
3746 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3747 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003748 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003749 layer->pushPendingState();
3750 }
3751
chaviw8b3871a2017-11-01 17:41:01 -07003752 if (what & layer_state_t::ePositionChanged) {
3753 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3754 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003755 }
chaviw8b3871a2017-11-01 17:41:01 -07003756 }
3757 if (what & layer_state_t::eLayerChanged) {
3758 // NOTE: index needs to be calculated before we update the state
3759 const auto& p = layer->getParent();
3760 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003761 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003762 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003763 mCurrentState.layersSortedByZ.removeAt(idx);
3764 mCurrentState.layersSortedByZ.add(layer);
3765 // we need traversal (state changed)
3766 // AND transaction (list changed)
3767 flags |= eTransactionNeeded|eTraversalNeeded;
3768 }
chaviw8b3871a2017-11-01 17:41:01 -07003769 } else {
3770 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003771 flags |= eTransactionNeeded|eTraversalNeeded;
3772 }
3773 }
chaviw8b3871a2017-11-01 17:41:01 -07003774 }
3775 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003776 // NOTE: index needs to be calculated before we update the state
3777 const auto& p = layer->getParent();
3778 if (p == nullptr) {
3779 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3780 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3781 mCurrentState.layersSortedByZ.removeAt(idx);
3782 mCurrentState.layersSortedByZ.add(layer);
3783 // we need traversal (state changed)
3784 // AND transaction (list changed)
3785 flags |= eTransactionNeeded|eTraversalNeeded;
3786 }
3787 } else {
3788 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3789 flags |= eTransactionNeeded|eTraversalNeeded;
3790 }
chaviw8b3871a2017-11-01 17:41:01 -07003791 }
3792 }
3793 if (what & layer_state_t::eSizeChanged) {
3794 if (layer->setSize(s.w, s.h)) {
3795 flags |= eTraversalNeeded;
3796 }
3797 }
3798 if (what & layer_state_t::eAlphaChanged) {
3799 if (layer->setAlpha(s.alpha))
3800 flags |= eTraversalNeeded;
3801 }
3802 if (what & layer_state_t::eColorChanged) {
3803 if (layer->setColor(s.color))
3804 flags |= eTraversalNeeded;
3805 }
Peiyong Lind3788632018-09-18 16:01:31 -07003806 if (what & layer_state_t::eColorTransformChanged) {
3807 if (layer->setColorTransform(s.colorTransform)) {
3808 flags |= eTraversalNeeded;
3809 }
3810 }
chaviw8b3871a2017-11-01 17:41:01 -07003811 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003812 // TODO: b/109894387
3813 //
3814 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3815 // rotation. To see the problem observe that if we have a square parent, and a child
3816 // of the same size, then we rotate the child 45 degrees around it's center, the child
3817 // must now be cropped to a non rectangular 8 sided region.
3818 //
3819 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3820 // private API, and the WindowManager only uses rotation in one case, which is on a top
3821 // level layer in which cropping is not an issue.
3822 //
3823 // However given that abuse of rotation matrices could lead to surfaces extending outside
3824 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3825 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3826 // transformations.
3827 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003828 flags |= eTraversalNeeded;
3829 }
3830 if (what & layer_state_t::eTransparentRegionChanged) {
3831 if (layer->setTransparentRegionHint(s.transparentRegion))
3832 flags |= eTraversalNeeded;
3833 }
3834 if (what & layer_state_t::eFlagsChanged) {
3835 if (layer->setFlags(s.flags, s.mask))
3836 flags |= eTraversalNeeded;
3837 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003838 if (what & layer_state_t::eCropChanged_legacy) {
3839 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003840 flags |= eTraversalNeeded;
3841 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003842 if (what & layer_state_t::eCornerRadiusChanged) {
3843 if (layer->setCornerRadius(s.cornerRadius))
3844 flags |= eTraversalNeeded;
3845 }
chaviw8b3871a2017-11-01 17:41:01 -07003846 if (what & layer_state_t::eLayerStackChanged) {
3847 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3848 // We only allow setting layer stacks for top level layers,
3849 // everything else inherits layer stack from its parent.
3850 if (layer->hasParent()) {
3851 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3852 layer->getName().string());
3853 } else if (idx < 0) {
3854 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3855 "that also does not appear in the top level layer list. Something"
3856 " has gone wrong.", layer->getName().string());
3857 } else if (layer->setLayerStack(s.layerStack)) {
3858 mCurrentState.layersSortedByZ.removeAt(idx);
3859 mCurrentState.layersSortedByZ.add(layer);
3860 // we need traversal (state changed)
3861 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003862 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003863 }
3864 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003865 if (what & layer_state_t::eDeferTransaction_legacy) {
3866 if (s.barrierHandle_legacy != nullptr) {
3867 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3868 } else if (s.barrierGbp_legacy != nullptr) {
3869 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003870 if (authenticateSurfaceTextureLocked(gbp)) {
3871 const auto& otherLayer =
3872 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003873 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003874 } else {
3875 ALOGE("Attempt to defer transaction to to an"
3876 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003877 }
3878 }
chaviw8b3871a2017-11-01 17:41:01 -07003879 // We don't trigger a traversal here because if no other state is
3880 // changed, we don't want this to cause any more work
3881 }
3882 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003883 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003884 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003885 if (!hadParent) {
3886 mCurrentState.layersSortedByZ.remove(layer);
3887 }
chaviw8b3871a2017-11-01 17:41:01 -07003888 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003889 }
chaviw8b3871a2017-11-01 17:41:01 -07003890 }
3891 if (what & layer_state_t::eReparentChildren) {
3892 if (layer->reparentChildren(s.reparentHandle)) {
3893 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003894 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003895 }
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (what & layer_state_t::eDetachChildren) {
3897 layer->detachChildren();
3898 }
3899 if (what & layer_state_t::eOverrideScalingModeChanged) {
3900 layer->setOverrideScalingMode(s.overrideScalingMode);
3901 // We don't trigger a traversal here because if no other state is
3902 // changed, we don't want this to cause any more work
3903 }
Marissa Wall61c58622018-07-18 10:12:20 -07003904 if (what & layer_state_t::eTransformChanged) {
3905 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3906 }
3907 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3908 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3909 flags |= eTraversalNeeded;
3910 }
3911 if (what & layer_state_t::eCropChanged) {
3912 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3913 }
Marissa Wall861616d2018-10-22 12:52:23 -07003914 if (what & layer_state_t::eFrameChanged) {
3915 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3916 }
Marissa Wall61c58622018-07-18 10:12:20 -07003917 if (what & layer_state_t::eBufferChanged) {
3918 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3919 }
3920 if (what & layer_state_t::eAcquireFenceChanged) {
3921 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3922 }
3923 if (what & layer_state_t::eDataspaceChanged) {
3924 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3925 }
3926 if (what & layer_state_t::eHdrMetadataChanged) {
3927 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3928 }
3929 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3930 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3931 }
3932 if (what & layer_state_t::eApiChanged) {
3933 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3934 }
3935 if (what & layer_state_t::eSidebandStreamChanged) {
3936 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3937 }
Robert Carr720e5062018-07-30 17:45:14 -07003938 if (what & layer_state_t::eInputInfoChanged) {
3939 layer->setInputInfo(s.inputInfo);
3940 flags |= eTraversalNeeded;
3941 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003942 std::vector<sp<CallbackHandle>> callbackHandles;
3943 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3944 mTransactionCompletedThread.run();
3945 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3946 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3947 }
3948 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003949 if (what & layer_state_t::eCachedBufferChanged) {
3950 sp<GraphicBuffer> buffer =
3951 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3952 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3953 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003954 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3955 // Do not put anything that updates layer state or modifies flags after
3956 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003957 return flags;
3958}
3959
chaviw273171b2018-12-26 11:46:30 -08003960uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3961 uint32_t flags = 0;
3962 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3963 flags |= eTraversalNeeded;
3964 }
3965
3966 mInputWindowCommands.merge(inputWindowCommands);
3967 return flags;
3968}
3969
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003970status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003971 const String8& name,
3972 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003973 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003974 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003975 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003976{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003977 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003978 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003979 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003980 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003981 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003982
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003983 status_t result = NO_ERROR;
3984
3985 sp<Layer> layer;
3986
Cody Northropbc755282017-03-31 12:00:08 -06003987 String8 uniqueName = getUniqueLayerName(name);
3988
Mathias Agopian3165cc22012-08-08 19:42:09 -07003989 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003990 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003991 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3992 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003993
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003995 case ISurfaceComposerClient::eFXSurfaceBufferState:
3996 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3997 break;
chaviw13fdc492017-06-27 12:40:18 -07003998 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003999 // check if buffer size is set for color layer.
4000 if (w > 0 || h > 0) {
4001 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4002 int(w), int(h));
4003 return BAD_VALUE;
4004 }
4005
chaviw13fdc492017-06-27 12:40:18 -07004006 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004007 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004008 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004010 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004011 // check if buffer size is set for container layer.
4012 if (w > 0 || h > 0) {
4013 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4014 int(w), int(h));
4015 return BAD_VALUE;
4016 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004017 result = createContainerLayer(client,
4018 uniqueName, w, h, flags,
4019 handle, &layer);
4020 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004021 default:
4022 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023 break;
4024 }
4025
Dan Stoza7d89d062015-04-30 13:29:25 -07004026 if (result != NO_ERROR) {
4027 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004028 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004029
Chia-I Wuab0c3192017-08-01 11:29:00 -07004030 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4031 // TODO b/64227542
4032 if (windowType == 441731) {
4033 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4034 layer->setPrimaryDisplayOnly();
4035 }
4036
Albert Chaulk479c60c2017-01-27 14:21:34 -05004037 layer->setInfo(windowType, ownerUid);
4038
Robert Carrb89ea9d2018-12-10 13:01:14 -08004039 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4040 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4041 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004042 if (result != NO_ERROR) {
4043 return result;
4044 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004045 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004046
4047 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004048 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049}
4050
Cody Northropbc755282017-03-31 12:00:08 -06004051String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4052{
4053 bool matchFound = true;
4054 uint32_t dupeCounter = 0;
4055
4056 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4057 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4058
Dan Stoza436ccf32018-06-21 12:10:12 -07004059 // Grab the state lock since we're accessing mCurrentState
4060 Mutex::Autolock lock(mStateLock);
4061
Cody Northropbc755282017-03-31 12:00:08 -06004062 // Loop over layers until we're sure there is no matching name
4063 while (matchFound) {
4064 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004065 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004066 if (layer->getName() == uniqueName) {
4067 matchFound = true;
4068 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4069 }
4070 });
4071 }
4072
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004073 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4074 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004075
4076 return uniqueName;
4077}
4078
Marissa Wallfd668622018-05-10 10:21:13 -07004079status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4080 uint32_t w, uint32_t h, uint32_t flags,
4081 PixelFormat& format, sp<IBinder>* handle,
4082 sp<IGraphicBufferProducer>* gbp,
4083 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004085 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 case PIXEL_FORMAT_TRANSPARENT:
4087 case PIXEL_FORMAT_TRANSLUCENT:
4088 format = PIXEL_FORMAT_RGBA_8888;
4089 break;
4090 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004091 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004092 break;
4093 }
4094
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004095 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004096 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004097 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004098 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004099 *handle = layer->getHandle();
4100 *gbp = layer->getProducer();
4101 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004103
Marissa Wallfd668622018-05-10 10:21:13 -07004104 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004105 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004106}
4107
Marissa Wall61c58622018-07-18 10:12:20 -07004108status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4109 uint32_t w, uint32_t h, uint32_t flags,
4110 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004111 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004112 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004113 *handle = layer->getHandle();
4114 *outLayer = layer;
4115
4116 return NO_ERROR;
4117}
4118
chaviw13fdc492017-06-27 12:40:18 -07004119status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004120 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004121 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004123 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004125 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004126}
4127
Robert Carr6b3f6c52018-08-13 13:05:17 -07004128status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4129 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4130 sp<IBinder>* handle, sp<Layer>* outLayer)
4131{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004132 *outLayer =
4133 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004134 *handle = (*outLayer)->getHandle();
4135 return NO_ERROR;
4136}
4137
4138
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004139void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004140 mLayersPendingRemoval.add(layer);
4141 mLayersRemoved = true;
4142 setTransactionFlags(eTransactionNeeded);
4143}
4144
Robert Carr695d5282018-12-18 15:27:58 -08004145void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004146{
Robert Carr2e102c92018-10-23 12:11:15 -07004147 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004148 // If a layer has a parent, we allow it to out-live it's handle
4149 // with the idea that the parent holds a reference and will eventually
4150 // be cleaned up. However no one cleans up the top-level so we do so
4151 // here.
4152 if (layer->getParent() == nullptr) {
4153 mCurrentState.layersSortedByZ.remove(layer);
4154 }
4155 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004156 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004157}
4158
Mathias Agopianb60314a2012-04-10 22:09:54 -07004159// ---------------------------------------------------------------------------
4160
Andy McFadden13a082e2012-08-24 10:16:42 -07004161void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004162 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004163 if (!displayToken) return;
4164
Jesse Hall01e29052013-02-19 16:13:35 -08004165 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004166 Vector<ComposerState> state;
4167 Vector<DisplayState> displays;
4168 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004169 d.what = DisplayState::eDisplayProjectionChanged |
4170 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004171 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004172 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004173 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004174 d.frame.makeInvalid();
4175 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004176 d.width = 0;
4177 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004178 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004179 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004180
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004181 const auto display = getDisplayDevice(displayToken);
4182 if (!display) return;
4183
Dominik Laskowskie9774092018-12-11 10:04:24 -08004184 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004185
Dominik Laskowski075d3172018-05-24 15:50:06 -07004186 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004187 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004188 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004189
Brian Andersond0010582017-03-07 13:20:31 -08004190 // Use phase of 0 since phase is not known.
4191 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004192 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4193 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004194}
4195
4196void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004197 // Async since we may be called from the main thread.
4198 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004199}
4200
Dominik Laskowskie9774092018-12-11 10:04:24 -08004201void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004202 if (display->isVirtual()) {
4203 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004204 return;
4205 }
4206
Dominik Laskowski075d3172018-05-24 15:50:06 -07004207 const auto displayId = display->getId();
4208 LOG_ALWAYS_FATAL_IF(!displayId);
4209
Dominik Laskowski34157762018-10-31 13:07:19 -07004210 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004211
4212 int currentMode = display->getPowerMode();
4213 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004214 return;
4215 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004217 display->setPowerMode(mode);
4218
Lloyd Pique4dccc412018-01-22 17:21:36 -08004219 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004220 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004221 }
4222
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004223 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004224 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004225 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004226 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004227 if (mUseScheduler) {
4228 mScheduler->onScreenAcquired(mAppConnectionHandle);
4229 } else {
4230 mEventThread->onScreenAcquired();
4231 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004232 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004234
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004235 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004236 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004237 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004238
4239 struct sched_param param = {0};
4240 param.sched_priority = 1;
4241 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4242 ALOGW("Couldn't set SCHED_FIFO on display on");
4243 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004244 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004245 // Turn off the display
4246 struct sched_param param = {0};
4247 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4248 ALOGW("Couldn't set SCHED_OTHER on display off");
4249 }
4250
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004251 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004252 if (mUseScheduler) {
4253 mScheduler->disableHardwareVsync(true);
4254 } else {
4255 disableHardwareVsync(true); // also cancels any in-progress resync
4256 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004257 if (mUseScheduler) {
4258 mScheduler->onScreenReleased(mAppConnectionHandle);
4259 } else {
4260 mEventThread->onScreenReleased();
4261 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004262 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004263
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004265 mVisibleRegionsDirty = true;
4266 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004267 } else if (mode == HWC_POWER_MODE_DOZE ||
4268 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004269 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004270 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004271 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004272 if (mUseScheduler) {
4273 mScheduler->onScreenAcquired(mAppConnectionHandle);
4274 } else {
4275 mEventThread->onScreenAcquired();
4276 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004277 resyncToHardwareVsync(true);
4278 }
4279 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4280 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004282 if (mUseScheduler) {
4283 mScheduler->disableHardwareVsync(true);
4284 } else {
4285 disableHardwareVsync(true); // also cancels any in-progress resync
4286 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004287 if (mUseScheduler) {
4288 mScheduler->onScreenReleased(mAppConnectionHandle);
4289 } else {
4290 mEventThread->onScreenReleased();
4291 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004292 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004295 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004296 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004299 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004300 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004301 }
4302
Dominik Laskowski34157762018-10-31 13:07:19 -07004303 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004304}
4305
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004306void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004307 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004308 const auto display = getDisplayDevice(displayToken);
4309 if (!display) {
4310 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4311 displayToken.get());
4312 } else if (display->isVirtual()) {
4313 ALOGW("Attempt to set power mode %d for virtual display", mode);
4314 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004315 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004316 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004318}
4319
4320// ---------------------------------------------------------------------------
4321
Lloyd Pique755e3192018-01-31 16:46:15 -08004322status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4323 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004324 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004325
Mathias Agopianbd115332013-04-18 16:41:04 -07004326 IPCThreadState* ipc = IPCThreadState::self();
4327 const int pid = ipc->getCallingPid();
4328 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004329
Mathias Agopianbd115332013-04-18 16:41:04 -07004330 if ((uid != AID_SHELL) &&
4331 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4333 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004334 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004335 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004336 // (this would indicate SF is stuck, but we want to be able to
4337 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004338 status_t err = mStateLock.timedLock(s2ns(1));
4339 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004340 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004341 StringAppendF(&result,
4342 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4343 "(no locks held)\n",
4344 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004345 }
4346
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004347 bool dumpAll = true;
4348 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004349 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004350
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004351 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004352 if ((index < numArgs) &&
4353 (args[index] == String16("--list"))) {
4354 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004355 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004356 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004357 }
4358
4359 if ((index < numArgs) &&
4360 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004361 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004362 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004363 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004365
4366 if ((index < numArgs) &&
4367 (args[index] == String16("--latency-clear"))) {
4368 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004369 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004370 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004371 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004372
4373 if ((index < numArgs) &&
4374 (args[index] == String16("--dispsync"))) {
4375 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004376 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004377 dumpAll = false;
4378 }
Dan Stozab90cf072015-03-05 11:05:59 -08004379
4380 if ((index < numArgs) &&
4381 (args[index] == String16("--static-screen"))) {
4382 index++;
4383 dumpStaticScreenStats(result);
4384 dumpAll = false;
4385 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004386
4387 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004388 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004389 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004390 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004391 dumpAll = false;
4392 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004393
4394 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4395 index++;
4396 dumpWideColorInfo(result);
4397 dumpAll = false;
4398 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004399
4400 if ((index < numArgs) &&
4401 (args[index] == String16("--enable-layer-stats"))) {
4402 index++;
4403 mLayerStats.enable();
4404 dumpAll = false;
4405 }
4406
4407 if ((index < numArgs) &&
4408 (args[index] == String16("--disable-layer-stats"))) {
4409 index++;
4410 mLayerStats.disable();
4411 dumpAll = false;
4412 }
4413
4414 if ((index < numArgs) &&
4415 (args[index] == String16("--clear-layer-stats"))) {
4416 index++;
4417 mLayerStats.clear();
4418 dumpAll = false;
4419 }
4420
4421 if ((index < numArgs) &&
4422 (args[index] == String16("--dump-layer-stats"))) {
4423 index++;
4424 mLayerStats.dump(result);
4425 dumpAll = false;
4426 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004427
4428 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004429 (args[index] == String16("--frame-composition"))) {
4430 index++;
4431 dumpFrameCompositionInfo(result);
4432 dumpAll = false;
4433 }
4434
4435 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004436 (args[index] == String16("--display-identification"))) {
4437 index++;
4438 dumpDisplayIdentificationData(result);
4439 dumpAll = false;
4440 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004441
4442 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4443 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004444 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004445 dumpAll = false;
4446 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004448
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004450 if (asProto) {
4451 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4452 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4453 } else {
4454 dumpAllLocked(args, index, result);
4455 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004456 }
4457
Mathias Agopian9795c422009-08-26 16:36:26 -07004458 if (locked) {
4459 mStateLock.unlock();
4460 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004461 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004463 return NO_ERROR;
4464}
4465
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4467 std::string& result) const {
4468 mCurrentState.traverseInZOrder(
4469 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004470}
4471
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004472void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004474 String8 name;
4475 if (index < args.size()) {
4476 name = String8(args[index]);
4477 index++;
4478 }
4479
Dominik Laskowski075d3172018-05-24 15:50:06 -07004480 if (const auto displayId = getInternalDisplayId();
4481 displayId && getHwComposer().isConnected(*displayId)) {
4482 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004483 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004485 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004486
4487 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004488 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004489 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004490 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004491 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004492 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004493 }
Robert Carr2047fae2016-11-28 14:09:09 -08004494 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004495 }
4496}
4497
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004498void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004500 String8 name;
4501 if (index < args.size()) {
4502 name = String8(args[index]);
4503 index++;
4504 }
4505
Robert Carr2047fae2016-11-28 14:09:09 -08004506 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004507 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004508 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004509 }
Robert Carr2047fae2016-11-28 14:09:09 -08004510 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004511
Svetoslavd85084b2014-03-20 10:28:31 -07004512 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004513}
4514
Jamie Gennis6547ff42013-07-16 20:12:42 -07004515// This should only be called from the main thread. Otherwise it would need
4516// the lock and should use mCurrentState rather than mDrawingState.
4517void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004518 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004519 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004520 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004521
4522 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4523}
4524
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004526 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004527
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004528 if (isLayerTripleBufferingDisabled())
4529 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4532 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4533 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4534 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4535 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4536 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004537 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004538}
4539
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4541 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004542 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4543 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004544 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004545 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004547 }
David Sodman4a36e932017-11-07 14:29:47 -08004548 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004549 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004550 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4552 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004553}
4554
Dan Stozae77c7662016-05-13 11:37:28 -07004555void SurfaceFlinger::recordBufferingStats(const char* layerName,
4556 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004557 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4558 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004559 for (const auto& segment : history) {
4560 if (!segment.usedThirdBuffer) {
4561 stats.twoBufferTime += segment.totalTime;
4562 }
4563 if (segment.occupancyAverage < 1.0f) {
4564 stats.doubleBufferedTime += segment.totalTime;
4565 } else if (segment.occupancyAverage < 2.0f) {
4566 stats.tripleBufferedTime += segment.totalTime;
4567 }
4568 ++stats.numSegments;
4569 stats.totalTime += segment.totalTime;
4570 }
4571}
4572
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4574 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004575
4576 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4577 const size_t count = currentLayers.size();
4578 for (size_t i=0 ; i<count ; i++) {
4579 currentLayers[i]->dumpFrameEvents(result);
4580 }
4581}
4582
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004584 result.append("Buffering stats:\n");
4585 result.append(" [Layer name] <Active time> <Two buffer> "
4586 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004587 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004588 typedef std::tuple<std::string, float, float, float> BufferTuple;
4589 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004590 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004591 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004592 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004593 if (stats.numSegments == 0) {
4594 continue;
4595 }
4596 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4597 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4598 stats.totalTime;
4599 float doubleBufferRatio = static_cast<float>(
4600 stats.doubleBufferedTime) / stats.totalTime;
4601 float tripleBufferRatio = static_cast<float>(
4602 stats.tripleBufferedTime) / stats.totalTime;
4603 sorted.insert({activeTime, {name, twoBufferRatio,
4604 doubleBufferRatio, tripleBufferRatio}});
4605 }
4606 for (const auto& sortedPair : sorted) {
4607 float activeTime = sortedPair.first;
4608 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4610 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004611 }
4612 result.append("\n");
4613}
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004616 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004617 const auto displayId = display->getId();
4618 if (!displayId) {
4619 continue;
4620 }
4621 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004622 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004623 continue;
4624 }
4625
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result,
4627 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4628 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004629 uint8_t port;
4630 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004631 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004632 result.append("no identification data\n");
4633 continue;
4634 }
4635
4636 if (!isEdid(data)) {
4637 result.append("unknown identification data: ");
4638 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640 }
4641 result.append("\n");
4642 continue;
4643 }
4644
4645 const auto edid = parseEdid(data);
4646 if (!edid) {
4647 result.append("invalid EDID: ");
4648 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004650 }
4651 result.append("\n");
4652 continue;
4653 }
4654
Yiwei Zhang5434a782018-12-05 18:06:32 -08004655 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004656 result.append(edid->displayName.data(), edid->displayName.length());
4657 result.append("\"\n");
4658 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004659}
4660
Yiwei Zhang5434a782018-12-05 18:06:32 -08004661void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4662 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4663 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4664 StringAppendF(&result, "DisplayColorSetting: %s\n",
4665 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004666
4667 // TODO: print out if wide-color mode is active or not
4668
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004669 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004670 const auto displayId = display->getId();
4671 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004672 continue;
4673 }
4674
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004676 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004677 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004679 }
4680
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004681 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, " Current color mode: %s (%d)\n",
4683 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684 }
4685 result.append("\n");
4686}
4687
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004689 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004690 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4691 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004692 continue;
4693 }
4694
Dominik Laskowski05275f12018-11-01 15:03:24 -07004695 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4697 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004698 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 compositionInfo.dump(result, nullptr);
4700 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004701 }
4702 }
David Sodman7e4ae112018-02-09 15:02:28 -08004703}
4704
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004705LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004706 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004707 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4708 const State& state = useDrawing ? mDrawingState : mCurrentState;
4709 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004710 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004711 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004712 });
4713
4714 return layersProto;
4715}
4716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004717LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004718 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004719
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004720 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004721 resolution->set_w(display.getWidth());
4722 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004723
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004724 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4725 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4726 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004727
Dominik Laskowski075d3172018-05-24 15:50:06 -07004728 const auto displayId = display.getId();
4729 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004730 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004731 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004732 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004733 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004734 }
4735 });
4736
4737 return layersProto;
4738}
4739
Mathias Agopian74d211a2013-04-22 16:55:35 +02004740void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004741 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004742 bool colorize = false;
4743 if (index < args.size()
4744 && (args[index] == String16("--color"))) {
4745 colorize = true;
4746 index++;
4747 }
4748
4749 Colorizer colorizer(colorize);
4750
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751 // figure out if we're stuck somewhere
4752 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004753 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4755
4756 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004757 * Dump library configuration.
4758 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004759
4760 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004761 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004762 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004763 appendSfConfigString(result);
4764 appendUiConfigString(result);
4765 appendGuiConfigString(result);
4766 result.append("\n");
4767
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004768 result.append("\nDisplay identification data:\n");
4769 dumpDisplayIdentificationData(result);
4770
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004771 result.append("\nWide-Color information:\n");
4772 dumpWideColorInfo(result);
4773
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004775 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004777 result.append(SyncFeatures::getInstance().toString());
4778 result.append("\n");
4779
Andy McFadden41d67d72014-04-25 16:58:34 -07004780 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004781 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004782 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004783
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004784 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4785 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004786 if (const auto displayId = getInternalDisplayId();
4787 displayId && getHwComposer().isConnected(*displayId)) {
4788 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789 StringAppendF(&result,
4790 "Display %s: app phase %" PRId64 " ns, "
4791 "sf phase %" PRId64 " ns, "
4792 "early app phase %" PRId64 " ns, "
4793 "early sf phase %" PRId64 " ns, "
4794 "early app gl phase %" PRId64 " ns, "
4795 "early sf gl phase %" PRId64 " ns, "
4796 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4797 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4798 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4799 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004800 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004801 result.append("\n");
4802
Dan Stozab90cf072015-03-05 11:05:59 -08004803 // Dump static screen stats
4804 result.append("\n");
4805 dumpStaticScreenStats(result);
4806 result.append("\n");
4807
Yiwei Zhang5434a782018-12-05 18:06:32 -08004808 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004809
Dan Stozae77c7662016-05-13 11:37:28 -07004810 dumpBufferingStats(result);
4811
Andy McFadden4803b742012-09-24 19:07:20 -07004812 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004813 * Dump the visible layer list
4814 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004815 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004816 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4817 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4818 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004819 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004820
Chia-I Wu2f884132018-09-13 15:17:58 -07004821 {
4822 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4823 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004824 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004825 result.append("\n");
4826 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004827
David Sodman7e4ae112018-02-09 15:02:28 -08004828 result.append("\nFrame-Composition information:\n");
4829 dumpFrameCompositionInfo(result);
4830 result.append("\n");
4831
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004833 * Dump Display state
4834 */
4835
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004836 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004838 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004839 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004840 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004841 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004842 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004843
4844 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004845 * Dump SurfaceFlinger global state
4846 */
4847
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004848 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004849 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004850 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004851
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004852 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004853
Dominik Laskowski075d3172018-05-24 15:50:06 -07004854 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004855 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004856 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4857 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004858 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004859 StringAppendF(&result,
4860 " transaction-flags : %08x\n"
4861 " gpu_to_cpu_unsupported : %d\n",
4862 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004863
Dominik Laskowski075d3172018-05-24 15:50:06 -07004864 if (const auto displayId = getInternalDisplayId();
4865 displayId && getHwComposer().isConnected(*displayId)) {
4866 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004867 StringAppendF(&result,
4868 " refresh-rate : %f fps\n"
4869 " x-dpi : %f\n"
4870 " y-dpi : %f\n",
4871 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4872 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004873 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004874
Yiwei Zhang5434a782018-12-05 18:06:32 -08004875 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004876
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004878 /*
4879 * VSYNC state
4880 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004881 if (mUseScheduler) {
4882 mScheduler->dump(mAppConnectionHandle, result);
4883 } else {
4884 mEventThread->dump(result);
4885 }
Dan Stozae22aec72016-08-01 13:20:59 -07004886 result.append("\n");
4887
4888 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004889 * Tracing state
4890 */
4891 mTracing.dump(result);
4892 result.append("\n");
4893
4894 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004895 * HWC layer minidump
4896 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004897 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004898 const auto displayId = display->getId();
4899 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004900 continue;
4901 }
4902
Yiwei Zhang5434a782018-12-05 18:06:32 -08004903 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004904 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004905 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004906 result.append("\n");
4907 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004908
4909 /*
4910 * Dump HWComposer state
4911 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004912 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004913 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004914 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004915 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004916 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004917 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004918
4919 /*
4920 * Dump gralloc state
4921 */
4922 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4923 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004924
4925 /*
4926 * Dump VrFlinger state if in use.
4927 */
4928 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4929 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004930 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004931 result.append("\n");
4932 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004933}
4934
Dominik Laskowski075d3172018-05-24 15:50:06 -07004935const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004936 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004937 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004938 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004939 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004940 }
4941 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004942
Dominik Laskowski34157762018-10-31 13:07:19 -07004943 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944 static const Vector<sp<Layer>> empty;
4945 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004946}
4947
Keun young Park63f165f2012-08-31 10:53:36 -07004948bool SurfaceFlinger::startDdmConnection()
4949{
4950 void* libddmconnection_dso =
4951 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4952 if (!libddmconnection_dso) {
4953 return false;
4954 }
4955 void (*DdmConnection_start)(const char* name);
4956 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004957 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004958 if (!DdmConnection_start) {
4959 dlclose(libddmconnection_dso);
4960 return false;
4961 }
4962 (*DdmConnection_start)(getServiceName());
4963 return true;
4964}
4965
Chia-I Wu28f320b2018-05-03 11:02:56 -07004966void SurfaceFlinger::updateColorMatrixLocked() {
4967 mat4 colorMatrix;
4968 if (mGlobalSaturationFactor != 1.0f) {
4969 // Rec.709 luma coefficients
4970 float3 luminance{0.213f, 0.715f, 0.072f};
4971 luminance *= 1.0f - mGlobalSaturationFactor;
4972 mat4 saturationMatrix = mat4(
4973 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4974 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4975 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4976 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4977 );
4978 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4979 } else {
4980 colorMatrix = mClientColorMatrix * mDaltonizer();
4981 }
4982
4983 if (mCurrentState.colorMatrix != colorMatrix) {
4984 mCurrentState.colorMatrix = colorMatrix;
4985 mCurrentState.colorMatrixChanged = true;
4986 setTransactionFlags(eTransactionNeeded);
4987 }
4988}
4989
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004990status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991#pragma clang diagnostic push
4992#pragma clang diagnostic error "-Wswitch-enum"
4993 switch (static_cast<ISurfaceComposerTag>(code)) {
4994 // These methods should at minimum make sure that the client requested
4995 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004996 case BOOT_FINISHED:
4997 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 case CREATE_DISPLAY:
4999 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005000 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 case GET_ACTIVE_COLOR_MODE:
5002 case GET_ANIMATION_FRAME_STATS:
5003 case GET_HDR_CAPABILITIES:
5004 case SET_ACTIVE_CONFIG:
5005 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005006 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005007 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005008 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005009 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5010 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005011 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5012 IPCThreadState* ipc = IPCThreadState::self();
5013 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5014 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005015 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 }
Robert Carr1db73f62016-12-21 12:58:51 -08005017 return OK;
5018 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005019 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005020 IPCThreadState* ipc = IPCThreadState::self();
5021 const int pid = ipc->getCallingPid();
5022 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5024 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005025 return PERMISSION_DENIED;
5026 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005027 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005028 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005029 // Used by apps to hook Choreographer to SurfaceFlinger.
5030 case CREATE_DISPLAY_EVENT_CONNECTION:
5031 // The following calls are currently used by clients that do not
5032 // request necessary permissions. However, they do not expose any secret
5033 // information, so it is OK to pass them.
5034 case AUTHENTICATE_SURFACE:
5035 case GET_ACTIVE_CONFIG:
5036 case GET_BUILT_IN_DISPLAY:
5037 case GET_DISPLAY_COLOR_MODES:
5038 case GET_DISPLAY_CONFIGS:
5039 case GET_DISPLAY_STATS:
5040 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5041 // Calling setTransactionState is safe, because you need to have been
5042 // granted a reference to Client* and Handle* to do anything with it.
5043 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005044 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005045 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005046 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005047 case GET_PROTECTED_CONTENT_SUPPORT:
5048 case CACHE_BUFFER:
5049 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 return OK;
5051 }
5052 case CAPTURE_LAYERS:
5053 case CAPTURE_SCREEN: {
5054 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005055 IPCThreadState* ipc = IPCThreadState::self();
5056 const int pid = ipc->getCallingPid();
5057 const int uid = ipc->getCallingUid();
5058 if ((uid != AID_GRAPHICS) &&
5059 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5060 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5061 return PERMISSION_DENIED;
5062 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005063 return OK;
5064 }
5065 // The following codes are deprecated and should never be allowed to access SF.
5066 case CONNECT_DISPLAY_UNUSED:
5067 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5068 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5069 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005070 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005071 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005072
5073 // These codes are used for the IBinder protocol to either interrogate the recipient
5074 // side of the transaction for its canonical interface descriptor or to dump its state.
5075 // We let them pass by default.
5076 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5077 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5078 code == IBinder::SYSPROPS_TRANSACTION) {
5079 return OK;
5080 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005081 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005082 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005083 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005084 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5085 return OK;
5086 }
5087 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5088 return PERMISSION_DENIED;
5089#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005090}
5091
Ana Krulec13be8ad2018-08-21 02:43:56 +00005092status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5093 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005094 status_t credentialCheck = CheckTransactCodeCredentials(code);
5095 if (credentialCheck != OK) {
5096 return credentialCheck;
5097 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005099 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5100 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005101 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005102 IPCThreadState* ipc = IPCThreadState::self();
5103 const int uid = ipc->getCallingUid();
5104 if (CC_UNLIKELY(uid != AID_SYSTEM
5105 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005106 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005107 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005108 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005109 return PERMISSION_DENIED;
5110 }
5111 int n;
5112 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005113 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005114 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005115 return NO_ERROR;
5116 case 1002: // SHOW_UPDATES
5117 n = data.readInt32();
5118 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005119 invalidateHwcGeometry();
5120 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005122 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005123 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005126 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005127 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005128 setTransactionFlags(
5129 eTransactionNeeded|
5130 eDisplayTransactionNeeded|
5131 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005132 return NO_ERROR;
5133 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005134 case 1006:{ // send empty update
5135 signalRefresh();
5136 return NO_ERROR;
5137 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005138 case 1008: // toggle use of hw composer
5139 n = data.readInt32();
5140 mDebugDisableHWC = n ? 1 : 0;
5141 invalidateHwcGeometry();
5142 repaintEverything();
5143 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005144 case 1009: // toggle use of transform hint
5145 n = data.readInt32();
5146 mDebugDisableTransformHint = n ? 1 : 0;
5147 invalidateHwcGeometry();
5148 repaintEverything();
5149 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005150 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005151 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 reply->writeInt32(0);
5153 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005154 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005155 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 return NO_ERROR;
5157 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005158 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005159 if (!display) {
5160 return NAME_NOT_FOUND;
5161 }
5162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005164 return NO_ERROR;
5165 }
5166 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005167 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005168 // daltonize
5169 n = data.readInt32();
5170 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005171 case 1:
5172 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5173 break;
5174 case 2:
5175 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5176 break;
5177 case 3:
5178 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5179 break;
5180 default:
5181 mDaltonizer.setType(ColorBlindnessType::None);
5182 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005183 }
5184 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005185 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005186 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005187 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005188 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005189
5190 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005192 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005193 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005194 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005195 // apply a color matrix
5196 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005197 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005198 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005199 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005200 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005201 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005202 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005203 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005204 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005205 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005206 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005207
5208 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5209 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005210 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005211 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5212 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5213 }
5214
Chia-I Wu28f320b2018-05-03 11:02:56 -07005215 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005216 return NO_ERROR;
5217 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005218 // This is an experimental interface
5219 // Needs to be shifted to proper binder interface when we productize
5220 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005221 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005222 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005223 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005224 return NO_ERROR;
5225 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005226 case 1017: {
5227 n = data.readInt32();
5228 mForceFullDamage = static_cast<bool>(n);
5229 return NO_ERROR;
5230 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005231 case 1018: { // Modify Choreographer's phase offset
5232 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005233 if (mUseScheduler) {
5234 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5235 } else {
5236 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5237 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005238 return NO_ERROR;
5239 }
5240 case 1019: { // Modify SurfaceFlinger's phase offset
5241 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005242 if (mUseScheduler) {
5243 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5244 } else {
5245 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5246 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005247 return NO_ERROR;
5248 }
Irvel468051e2016-06-13 16:44:44 -07005249 case 1020: { // Layer updates interceptor
5250 n = data.readInt32();
5251 if (n) {
5252 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005253 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005254 }
5255 else{
5256 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005257 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005258 }
5259 return NO_ERROR;
5260 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005261 case 1021: { // Disable HWC virtual displays
5262 n = data.readInt32();
5263 mUseHwcVirtualDisplays = !n;
5264 return NO_ERROR;
5265 }
Romain Guy0147a172017-06-01 13:53:56 -07005266 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005267 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005268 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005269
Chia-I Wu28f320b2018-05-03 11:02:56 -07005270 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005271 return NO_ERROR;
5272 }
Romain Guy54f154a2017-10-24 21:40:32 +01005273 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005274 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005275 invalidateHwcGeometry();
5276 repaintEverything();
5277 return NO_ERROR;
5278 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005279 // Deprecate, use 1030 to check whether the device is color managed.
5280 case 1024: {
5281 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005282 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005283 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005284 n = data.readInt32();
5285 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005286 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005287 mTracing.enable();
5288 doTracing("tracing.enable");
5289 reply->writeInt32(NO_ERROR);
5290 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005291 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005292 status_t err = mTracing.disable();
5293 reply->writeInt32(err);
5294 }
5295 return NO_ERROR;
5296 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005297 case 1026: { // Get layer tracing status
5298 reply->writeBool(mTracing.isEnabled());
5299 return NO_ERROR;
5300 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005301 // Is a DisplayColorSetting supported?
5302 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005303 const auto display = getDefaultDisplayDevice();
5304 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005305 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005306 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005307
5308 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5309 switch (setting) {
5310 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005311 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005312 break;
5313 case DisplayColorSetting::UNMANAGED:
5314 reply->writeBool(true);
5315 break;
5316 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005317 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005318 break;
5319 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005320 reply->writeBool(
5321 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005322 break;
5323 }
5324 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005325 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005326 // Is VrFlinger active?
5327 case 1028: {
5328 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005329 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005330 return NO_ERROR;
5331 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005332 // Is device color managed?
5333 case 1030: {
5334 reply->writeBool(useColorManagement);
5335 return NO_ERROR;
5336 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005337 // Override default composition data space
5338 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5339 // && adb shell stop zygote && adb shell start zygote
5340 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5341 // adb shell stop zygote && adb shell start zygote
5342 case 1031: {
5343 Mutex::Autolock _l(mStateLock);
5344 n = data.readInt32();
5345 if (n) {
5346 n = data.readInt32();
5347 if (n) {
5348 Dataspace dataspace = static_cast<Dataspace>(n);
5349 if (!validateCompositionDataspace(dataspace)) {
5350 return BAD_VALUE;
5351 }
5352 mDefaultCompositionDataspace = dataspace;
5353 }
5354 n = data.readInt32();
5355 if (n) {
5356 Dataspace dataspace = static_cast<Dataspace>(n);
5357 if (!validateCompositionDataspace(dataspace)) {
5358 return BAD_VALUE;
5359 }
5360 mWideColorGamutCompositionDataspace = dataspace;
5361 }
5362 } else {
5363 // restore composition data space.
5364 mDefaultCompositionDataspace = defaultCompositionDataspace;
5365 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5366 }
5367 return NO_ERROR;
5368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005369 }
5370 }
5371 return err;
5372}
5373
Steven Thomas6d8110b2017-08-31 18:24:21 -07005374void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005375 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005376 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005377}
5378
Ana Krulec7d1d6832018-12-27 11:10:09 -08005379void SurfaceFlinger::repaintEverythingForHWC() {
5380 mRepaintEverything = true;
5381 mEventQueue->invalidateForHWC();
5382}
5383
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005384// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5385class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005386public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005387 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5388 ~WindowDisconnector() {
5389 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005390 }
5391
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005392private:
5393 ANativeWindow* mWindow;
5394 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005395};
5396
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005397status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005398 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5399 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005400 uint32_t reqWidth, uint32_t reqHeight,
5401 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005402 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005403 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005404
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005405 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005406
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005407 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5408
Chia-I Wu20261cb2018-08-23 12:55:44 -07005409 sp<DisplayDevice> display;
5410 {
5411 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005412
Chia-I Wu20261cb2018-08-23 12:55:44 -07005413 display = getDisplayDeviceLocked(displayToken);
5414 if (!display) return BAD_VALUE;
5415
Chia-I Wucb023152018-08-28 12:57:23 -07005416 // set the requested width/height to the logical display viewport size
5417 // by default
5418 if (reqWidth == 0 || reqHeight == 0) {
5419 reqWidth = uint32_t(display->getViewport().width());
5420 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005421 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005422 }
5423
Peiyong Lin0e003c92018-09-17 11:09:51 -07005424 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5425 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005426
5427 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005428 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005429 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5430 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005431}
5432
5433status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005434 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5435 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005436 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005437 ATRACE_CALL();
5438
5439 class LayerRenderArea : public RenderArea {
5440 public:
Robert Carr578038f2018-03-09 12:25:24 -08005441 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005442 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5443 bool childrenOnly)
5444 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005445 mLayer(layer),
5446 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005447 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005448 mFlinger(flinger),
5449 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005450 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005451 Rect getBounds() const override {
5452 const Layer::State& layerState(mLayer->getDrawingState());
5453 return mLayer->getBufferSize(layerState);
5454 }
Marissa Wall61c58622018-07-18 10:12:20 -07005455 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005456 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005457 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005458 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005459 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005460 }
chaviwa76b2712017-09-20 12:02:26 -07005461 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005462 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005463 Rect getSourceCrop() const override {
5464 if (mCrop.isEmpty()) {
5465 return getBounds();
5466 } else {
5467 return mCrop;
5468 }
5469 }
Robert Carr578038f2018-03-09 12:25:24 -08005470 class ReparentForDrawing {
5471 public:
5472 const sp<Layer>& oldParent;
5473 const sp<Layer>& newParent;
5474
5475 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5476 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005477 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005478 }
Robert Carr15eae092018-03-23 13:43:53 -07005479 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005480 };
5481
5482 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005483 const Rect sourceCrop = getSourceCrop();
5484 // no need to check rotation because there is none
5485 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5486 sourceCrop.height() != getReqHeight();
5487
Robert Carr578038f2018-03-09 12:25:24 -08005488 if (!mChildrenOnly) {
5489 mTransform = mLayer->getTransform().inverse();
5490 drawLayers();
5491 } else {
5492 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005493 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005494 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5495 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005496
5497 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5498 drawLayers();
5499 }
5500 }
chaviwa76b2712017-09-20 12:02:26 -07005501
chaviwa76b2712017-09-20 12:02:26 -07005502 private:
chaviw7206d492017-11-10 16:16:12 -08005503 const sp<Layer> mLayer;
5504 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005505
5506 // In the "childrenOnly" case we reparent the children to a screenshot
5507 // layer which has no properties set and which does not draw.
5508 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005509 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005510 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005511
5512 SurfaceFlinger* mFlinger;
5513 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005514 };
5515
5516 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5517 auto parent = layerHandle->owner.promote();
5518
Robert Carr2e102c92018-10-23 12:11:15 -07005519 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005520 ALOGE("captureLayers called with a removed parent");
5521 return NAME_NOT_FOUND;
5522 }
5523
Robert Carr578038f2018-03-09 12:25:24 -08005524 const int uid = IPCThreadState::self()->getCallingUid();
5525 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005526 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005527 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5528 return PERMISSION_DENIED;
5529 }
5530
chaviw7206d492017-11-10 16:16:12 -08005531 Rect crop(sourceCrop);
5532 if (sourceCrop.width() <= 0) {
5533 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005534 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005535 }
5536
5537 if (sourceCrop.height() <= 0) {
5538 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005539 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005540 }
5541
5542 int32_t reqWidth = crop.width() * frameScale;
5543 int32_t reqHeight = crop.height() * frameScale;
5544
Chia-I Wu20261cb2018-08-23 12:55:44 -07005545 // really small crop or frameScale
5546 if (reqWidth <= 0) {
5547 reqWidth = 1;
5548 }
5549 if (reqHeight <= 0) {
5550 reqHeight = 1;
5551 }
5552
Peiyong Lin0e003c92018-09-17 11:09:51 -07005553 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005554
Robert Carr578038f2018-03-09 12:25:24 -08005555 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005556 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5557 if (!layer->isVisible()) {
5558 return;
Robert Carr578038f2018-03-09 12:25:24 -08005559 } else if (childrenOnly && layer == parent.get()) {
5560 return;
chaviwa76b2712017-09-20 12:02:26 -07005561 }
5562 visitor(layer);
5563 });
5564 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005565 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005566}
5567
5568status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5569 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005570 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005571 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005572 bool useIdentityTransform) {
5573 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005574
Peiyong Lin0e003c92018-09-17 11:09:51 -07005575 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005576 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5577 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005578 *outBuffer =
5579 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5580 static_cast<android_pixel_format>(reqPixelFormat), 1,
5581 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582
5583 // This mutex protects syncFd and captureResult for communication of the return values from the
5584 // main thread back to this Binder thread
5585 std::mutex captureMutex;
5586 std::condition_variable captureCondition;
5587 std::unique_lock<std::mutex> captureLock(captureMutex);
5588 int syncFd = -1;
5589 std::optional<status_t> captureResult;
5590
Robert Carr03480e22018-01-04 16:02:06 -08005591 const int uid = IPCThreadState::self()->getCallingUid();
5592 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5593
Dominik Laskowski8c001672018-05-30 16:52:06 -07005594 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005595 // If there is a refresh pending, bug out early and tell the binder thread to try again
5596 // after the refresh.
5597 if (mRefreshPending) {
5598 ATRACE_NAME("Skipping screenshot for now");
5599 std::unique_lock<std::mutex> captureLock(captureMutex);
5600 captureResult = std::make_optional<status_t>(EAGAIN);
5601 captureCondition.notify_one();
5602 return;
5603 }
5604
5605 status_t result = NO_ERROR;
5606 int fd = -1;
5607 {
5608 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005609 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005610 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5611 useIdentityTransform, forSystem, &fd);
5612 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005613 }
5614
5615 {
5616 std::unique_lock<std::mutex> captureLock(captureMutex);
5617 syncFd = fd;
5618 captureResult = std::make_optional<status_t>(result);
5619 captureCondition.notify_one();
5620 }
5621 });
5622
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005623 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005624 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005625 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005626 while (*captureResult == EAGAIN) {
5627 captureResult.reset();
5628 result = postMessageAsync(message);
5629 if (result != NO_ERROR) {
5630 return result;
5631 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005632 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005633 }
5634 result = *captureResult;
5635 }
5636
5637 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005638 sync_wait(syncFd, -1);
5639 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005640 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005641
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005642 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005643}
5644
chaviwa76b2712017-09-20 12:02:26 -07005645void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005646 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005647 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005648 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005649
Lloyd Pique144e1162017-12-20 16:44:52 -08005650 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005651
chaviwa76b2712017-09-20 12:02:26 -07005652 const auto reqWidth = renderArea.getReqWidth();
5653 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005654 const auto sourceCrop = renderArea.getSourceCrop();
5655 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005656
Peiyong Lin0e003c92018-09-17 11:09:51 -07005657 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005658 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005659
Mathias Agopian180f10d2013-04-10 22:55:41 -07005660 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005661 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005662
5663 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005664 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005665 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005666
chaviw50da5042018-04-09 13:49:37 -07005667 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005668 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005669 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005670
chaviwa76b2712017-09-20 12:02:26 -07005671 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005672 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005673 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005674 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005675 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005676}
5677
chaviwa76b2712017-09-20 12:02:26 -07005678status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5679 TraverseLayersFunction traverseLayers,
5680 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005681 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005682 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005683 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005684 ATRACE_CALL();
5685
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005686 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005687
5688 traverseLayers([&](Layer* layer) {
5689 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5690 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005691
Robert Carr03480e22018-01-04 16:02:06 -08005692 // We allow the system server to take screenshots of secure layers for
5693 // use in situations like the Screen-rotation animation and place
5694 // the impetus on WindowManager to not persist them.
5695 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005696 ALOGW("FB is protected: PERMISSION_DENIED");
5697 return PERMISSION_DENIED;
5698 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005699 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005700
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005701 // this binds the given EGLImage as a framebuffer for the
5702 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005703 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005704 if (bufferBond.getStatus() != NO_ERROR) {
5705 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005706 return INVALID_OPERATION;
5707 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005708
Dan Stozaabcda352017-06-01 14:37:39 -07005709 // this will in fact render into our dequeued buffer
5710 // via an FBO, which means we didn't have to create
5711 // an EGLSurface and therefore we're not
5712 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005713 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005714
Peiyong Linfb530cf2018-12-15 05:07:38 +00005715 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005716 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005717 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005718 }
Alec Mouri492bc572018-09-11 21:40:04 +00005719 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005720
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005721 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005722}
5723
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005724// ---------------------------------------------------------------------------
5725
Dan Stoza412903f2017-04-27 13:42:17 -07005726void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5727 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005728}
5729
Dan Stoza412903f2017-04-27 13:42:17 -07005730void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5731 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005732}
5733
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005734void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005735 const LayerVector::Visitor& visitor) {
5736 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005737 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005738 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005739 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005740 continue;
5741 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005742 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005743 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005744 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005745 return;
5746 }
chaviwa76b2712017-09-20 12:02:26 -07005747 if (!layer->isVisible()) {
5748 return;
5749 }
5750 visitor(layer);
5751 });
5752 }
5753}
5754
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005755}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005756
Lloyd Pique074e8122018-07-26 12:57:23 -07005757
Mathias Agopian3f844832013-08-07 21:24:32 -07005758#if defined(__gl_h_)
5759#error "don't include gl/gl.h in this file"
5760#endif
5761
5762#if defined(__gl2_h_)
5763#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005764#endif