blob: ac6172f4716c1027bd39dad59913e317da908523 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070040#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070041#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080043#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080044#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070047#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070048#include <ui/ColorSpace.h>
49#include <ui/DebugUtils.h>
50#include <ui/DisplayInfo.h>
51#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070052#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080055#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070057#include <utils/String16.h>
58#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Robert Carr578038f2018-03-09 12:25:24 -080066#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070067#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070068#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020069#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080070#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020071#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080073#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070078#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070079#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070081#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070090#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091#include "Scheduler/EventControlThread.h"
92#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070093#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070095#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080096#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097
Mathias Agopianff2ed702013-09-01 21:36:12 -070098#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070099
David Sodman7e4ae112018-02-09 15:02:28 -0800100#include "android-base/stringprintf.h"
101
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700104#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800105#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900106#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107
chaviw1d044282017-09-27 12:19:28 -0700108#include <layerproto/LayerProtoParser.h>
109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800114using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700131 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700147ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
148 switch (rotation) {
149 case ISurfaceComposer::eRotateNone:
150 return ui::Transform::ROT_0;
151 case ISurfaceComposer::eRotate90:
152 return ui::Transform::ROT_90;
153 case ISurfaceComposer::eRotate180:
154 return ui::Transform::ROT_180;
155 case ISurfaceComposer::eRotate270:
156 return ui::Transform::ROT_270;
157 }
158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
159 return ui::Transform::ROT_0;
160}
161
Peiyong Linfca547f2018-07-09 13:03:33 -0700162#pragma clang diagnostic pop
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164class ConditionalLock {
165public:
166 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
167 if (lock) {
168 mMutex.lock();
169 }
170 }
171 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
172private:
173 Mutex& mMutex;
174 bool mLocked;
175};
Peiyong Linfca547f2018-07-09 13:03:33 -0700176
Peiyong Lin9d846a52018-11-05 13:18:20 -0800177// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
178bool validateCompositionDataspace(Dataspace dataspace) {
179 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
180}
181
Steven Thomasb02664d2017-07-26 18:48:28 -0700182} // namespace anonymous
183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184// ---------------------------------------------------------------------------
185
Mathias Agopian99b49842011-06-27 16:05:52 -0700186const String16 sHardwareTest("android.permission.HARDWARE_TEST");
187const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
188const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
189const String16 sDump("android.permission.DUMP");
190
191// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800192int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
193int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700194int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700195bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800196uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800197bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800198bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800199int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600200bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700201int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700202bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700203bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700204Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
205ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
206Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
207ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700208
Kalle Raitaa099a242017-01-11 11:17:29 -0800209std::string getHwcServiceName() {
210 char value[PROPERTY_VALUE_MAX] = {};
211 property_get("debug.sf.hwc_service_name", value, "default");
212 ALOGI("Using HWComposer service: '%s'", value);
213 return std::string(value);
214}
215
216bool useTrebleTestingOverride() {
217 char value[PROPERTY_VALUE_MAX] = {};
218 property_get("debug.sf.treble_testing_override", value, "false");
219 ALOGI("Treble testing override: '%s'", value);
220 return std::string(value) == "true";
221}
222
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
224 switch(displayColorSetting) {
225 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700226 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Enhanced");
231 default:
232 return std::string("Unknown ") +
233 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235}
236
David Sodmanbc815282017-11-05 18:57:52 -0800237SurfaceFlingerBE::SurfaceFlingerBE()
238 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800239 mFrameBuckets(),
240 mTotalTime(0),
241 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800242 mComposerSequenceId(0) {
243}
244
Lloyd Pique90c115d2018-09-18 21:39:42 -0700245SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
246 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800265 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800268 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700272 mMainThreadId(std::this_thread::get_id()),
273 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
276 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700306 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700307 getBool<V1_2::ISurfaceFlingerConfigs,
308 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
309
310 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
311 if (surfaceFlingerConfigsServiceV1_2) {
312 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700313 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
314 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
315 defaultCompositionDataspace = tmpDefaultDataspace;
316 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
317 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
318 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
319 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700320 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800321 mDefaultCompositionDataspace = defaultCompositionDataspace;
322 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600323
Peiyong Linb3839ad2018-09-05 15:37:19 -0700324 useContextPriority = getBool<ISurfaceFlingerConfigs,
325 &ISurfaceFlingerConfigs::useContextPriority>(true);
326
Iris Chang7501ed62018-04-30 14:45:42 +0800327 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700328 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
329 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800330 V1_1::DisplayOrientation::ORIENTATION_0);
331
332 switch (primaryDisplayOrientation) {
333 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800347
Lloyd Pique90c115d2018-09-18 21:39:42 -0700348 mPrimaryDispSync =
349 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
350 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 // debugging stuff...
353 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianb4b17302013-03-20 18:36:41 -0700355 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700356 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358 property_get("debug.sf.showupdates", value, "0");
359 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 property_get("debug.sf.ddms", value, "0");
362 mDebugDDMS = atoi(value);
363 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700364 if (!startDdmConnection()) {
365 // start failed, and DDMS debugging not enabled
366 mDebugDDMS = 0;
367 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700369 ALOGI_IF(mDebugRegion, "showupdates enabled");
370 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700371
372 property_get("debug.sf.disable_backpressure", value, "0");
373 mPropagateBackpressure = !atoi(value);
374 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700375
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800376 property_get("debug.sf.enable_hwc_vds", value, "0");
377 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800378 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800379
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800380 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800381 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800382 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700383
Yiwei Zhang243b3782018-05-15 17:40:04 -0700384 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700385 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
386 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
387
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200388 property_get("debug.sf.early_phase_offset_ns", value, "-1");
389 const int earlySfOffsetNs = atoi(value);
390
391 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
392 const int earlyGlSfOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
395 const int earlyAppOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
398 const int earlyGlAppOffsetNs = atoi(value);
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200403 const VSyncModulator::Offsets earlyOffsets =
404 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
405 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
406 const VSyncModulator::Offsets earlyGlOffsets =
407 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
408 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
409 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
410 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700411
Romain Guy11d63f42017-07-20 12:47:14 -0700412 // We should be reading 'persist.sys.sf.color_saturation' here
413 // but since /data may be encrypted, we need to wait until after vold
414 // comes online to attempt to read the property. The property is
415 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800416
417 if (useTrebleTestingOverride()) {
418 // Without the override SurfaceFlinger cannot connect to HIDL
419 // services that are not listed in the manifests. Considered
420 // deriving the setting from the set service name, but it
421 // would be brittle if the name that's not 'default' is used
422 // for production purposes later on.
423 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425}
426
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427void SurfaceFlinger::onFirstRef()
428{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800429 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432SurfaceFlinger::~SurfaceFlinger()
433{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434}
435
Dan Stozac7014012014-02-14 15:03:43 -0800436void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437{
438 // the window manager died on us. prepare its eulogy.
439
Andy McFadden13a082e2012-08-24 10:16:42 -0700440 // restore initial conditions (default device unblank, etc)
441 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442
443 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700444 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445}
446
Robert Carr1db73f62016-12-21 12:58:51 -0800447static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700448 status_t err = client->initCheck();
449 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 }
Robert Carr1db73f62016-12-21 12:58:51 -0800452 return nullptr;
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
456 return initClient(new Client(this));
457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 // Display ID is assigned when virtual display is allocated by HWC.
480 DisplayDeviceState state;
481 state.isSecure = secure;
482 state.displayName = displayName;
483 mCurrentState.displays.add(token, state);
484 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
492 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
498 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 mInterceptor->saveDisplayDeletion(state.sequenceId);
503 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 std::optional<DisplayId> displayId;
509
510 if (id == HWC_DISPLAY_PRIMARY) {
511 displayId = getInternalDisplayId();
512 } else if (id == HWC_DISPLAY_EXTERNAL) {
513 displayId = getExternalDisplayId();
514 }
515
516 if (!displayId) {
517 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800518 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520
521 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522}
523
Ady Abraham37965d42018-11-01 13:43:32 -0700524status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
525 if (!outGetColorManagement) {
526 return BAD_VALUE;
527 }
528 *outGetColorManagement = useColorManagement;
529 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700530}
531
Lloyd Pique441d5042018-10-18 16:49:51 -0700532HWComposer& SurfaceFlinger::getHwComposer() const {
533 return mCompositionEngine->getHwComposer();
534}
535
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700536renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
537 return mCompositionEngine->getRenderEngine();
538}
539
Lloyd Pique70d91362018-10-18 16:02:55 -0700540compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
541 return *mCompositionEngine.get();
542}
543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544void SurfaceFlinger::bootFinished()
545{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700546 if (mStartPropertySetThread->join() != NO_ERROR) {
547 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549 const nsecs_t now = systemTime();
550 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000551 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552
553 // wait patiently for the window manager death
554 const String16 name("window");
555 sp<IBinder> window(defaultServiceManager()->getService(name));
556 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700557 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558 }
Robert Carr720e5062018-07-30 17:45:14 -0700559 sp<IBinder> input(defaultServiceManager()->getService(
560 String16("inputflinger")));
561 if (input == nullptr) {
562 ALOGE("Failed to link to input service");
563 } else {
564 mInputFlinger = interface_cast<IInputFlinger>(input);
565 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700566
Steven Thomas050b2c82017-03-06 11:45:16 -0800567 if (mVrFlinger) {
568 mVrFlinger->OnBootFinished();
569 }
570
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700572 // formerly we would just kill the process, but we now ask it to exit so it
573 // can choose where to stop the animation.
574 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700575
576 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
577 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
578 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700579
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 postMessageAsync(new LambdaMessage([this] {
581 readPersistentProperties();
582 mBootStage = BootStage::FINISHED;
583 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584}
585
Dan Stoza436ccf32018-06-21 12:10:12 -0700586uint32_t SurfaceFlinger::getNewTexture() {
587 {
588 std::lock_guard lock(mTexturePoolMutex);
589 if (!mTexturePool.empty()) {
590 uint32_t name = mTexturePool.back();
591 mTexturePool.pop_back();
592 ATRACE_INT("TexturePoolSize", mTexturePool.size());
593 return name;
594 }
595
596 // The pool was too small, so increase it for the future
597 ++mTexturePoolSize;
598 }
599
600 // The pool was empty, so we need to get a new texture name directly using a
601 // blocking call to the main thread
602 uint32_t name = 0;
603 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
604 return name;
605}
606
Mathias Agopian3f844832013-08-07 21:24:32 -0700607void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700608 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700609}
610
Wei Wangf9b05ee2017-07-19 20:59:39 -0700611// Do not call property_set on main thread which will be blocked by init
612// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700614 ALOGI( "SurfaceFlinger's main thread ready to run. "
615 "Initializing graphics H/W...");
616
Thierry Strudel2924d012017-08-14 15:19:37 -0700617 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700622 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700623 mScheduler = getFactory().createScheduler([this](bool enabled) {
624 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
625 });
626
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700628 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 [this] { resyncWithRateLimit(); },
630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700632 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 [this] { resyncWithRateLimit(); },
634 [this](nsecs_t timestamp) {
635 mInterceptor->saveVSyncEvent(timestamp);
636 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800637
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700639 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
640 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 } else {
642 mEventThreadSource =
643 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
644 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
645 mEventThread =
646 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
647 [this] { resyncWithRateLimit(); },
648 impl::EventThread::InterceptVSyncsCallback(),
649 "appEventThread");
650 mSfEventThreadSource =
651 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
652 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
653
654 mSFEventThread =
655 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
656 [this] { resyncWithRateLimit(); },
657 [this](nsecs_t timestamp) {
658 mInterceptor->saveVSyncEvent(timestamp);
659 },
660 "sfEventThread");
661 mEventQueue->setEventThread(mSFEventThread.get());
662 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
663 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800664
Steven Thomasb02664d2017-07-26 18:48:28 -0700665 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700666 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700667 renderEngineFeature |= (useColorManagement ?
668 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700669 renderEngineFeature |= (useContextPriority ?
670 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700671
672 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700674 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700675 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700676
677 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
678 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700679 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
680 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800681 // Process any initial hotplug and resulting display changes.
682 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 const auto display = getDefaultDisplayDeviceLocked();
684 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 // This callback is called from the vr flinger dispatch thread. We
691 // need to call signalTransaction(), which requires holding
692 // mStateLock when we're not on the main thread. Acquiring
693 // mStateLock from the vr flinger dispatch thread might trigger a
694 // deadlock in surface flinger (see b/66916578), so post a message
695 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
698 mVrFlingerRequestsDisplay = requestDisplay;
699 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
703 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 .value_or(0),
706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Lloyd Pique90c115d2018-09-18 21:39:42 -0700712 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700713 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700714
Mathias Agopian92a979a2012-08-02 18:32:23 -0700715 // initialize our drawing state
716 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700717
Andy McFadden13a082e2012-08-24 10:16:42 -0700718 // set initial conditions (e.g. unblank default device)
719 initializeDisplays();
720
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700721 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700722
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700724
725 const bool presentFenceReliable =
726 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
727 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728
729 if (mStartPropertySetThread->Start() != NO_ERROR) {
730 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732
Ana Krulec7d1d6832018-12-27 11:10:09 -0800733 if (mUseScheduler) {
734 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
735 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
736 }
737
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700739}
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 Mutex::Autolock _l(mStateLock);
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744 char value[PROPERTY_VALUE_MAX];
745
746 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800747 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100750
751 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700752 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700770 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
809 Vector<DisplayInfo>* configs) {
810 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 const auto displayId = getPhysicalDisplayId(displayToken);
815 if (!displayId) {
816 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700817 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 // TODO: Not sure if display density should handled by SF any longer
820 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700823 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800824 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 }
827 return density;
828 }
829 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("ro.sf.lcd_density"); }
834 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Steven Thomas6d8110b2017-08-31 18:24:21 -0700838 ConditionalLock _l(mStateLock,
839 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700840 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 DisplayInfo info = DisplayInfo();
842
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 float xdpi = hwConfig->getDpiX();
844 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700846 info.w = hwConfig->getWidth();
847 info.h = hwConfig->getHeight();
848 // Default display viewport to display width and height
849 info.viewportW = info.w;
850 info.viewportH = info.h;
851
Dominik Laskowski075d3172018-05-24 15:50:06 -0700852 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 // The density of the device is provided by a build property
854 float density = Density::getBuildDensity() / 160.0f;
855 if (density == 0) {
856 // the build doesn't provide a density -- this is wrong!
857 // use xdpi instead
858 ALOGE("ro.sf.lcd_density must be defined as a build property");
859 density = xdpi / 160.0f;
860 }
861 if (Density::getEmuDensity()) {
862 // if "qemu.sf.lcd_density" is specified, it overrides everything
863 xdpi = ydpi = density = Density::getEmuDensity();
864 density /= 160.0f;
865 }
866 info.density = density;
867
868 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869 const auto display = getDefaultDisplayDeviceLocked();
870 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700871
872 // This is for screenrecord
873 const Rect viewport = display->getViewport();
874 if (viewport.isValid()) {
875 info.viewportW = uint32_t(viewport.getWidth());
876 info.viewportH = uint32_t(viewport.getHeight());
877 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 } else {
879 // TODO: where should this value come from?
880 static const int TV_DENSITY = 213;
881 info.density = TV_DENSITY / 160.0f;
882 info.orientation = 0;
883 }
884
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 info.xdpi = xdpi;
886 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900888 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800903 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700904
905 // All non-virtual displays are currently considered secure.
906 info.secure = true;
907
Dominik Laskowski075d3172018-05-24 15:50:06 -0700908 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700909 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800910 std::swap(info.w, info.h);
911 }
912
Michael Wright28f24d02016-07-12 13:30:53 -0700913 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 }
915
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 return NO_ERROR;
917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
920 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
Ana Krulece588e312018-09-18 12:32:24 -0700924 if (mUseScheduler) {
925 mScheduler->getDisplayStatInfo(stats);
926 } else {
927 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
928 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
929 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700930 return NO_ERROR;
931}
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
934 const auto display = getDisplayDevice(displayToken);
935 if (!display) {
936 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800937 return BAD_VALUE;
938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
944 ATRACE_NAME("setActiveConfigAsync");
945 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
946 return NO_ERROR;
947}
948
949status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
950 ATRACE_NAME("setActiveConfigSync");
951 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
952 return NO_ERROR;
953}
954
955void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
956 Vector<DisplayInfo> configs;
957 getDisplayConfigs(displayToken, &configs);
958 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
959 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
960 return;
961 }
962
963 const auto display = getDisplayDevice(displayToken);
964 if (!display) {
965 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
966 displayToken.get());
967 return;
968 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700969 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800970 ALOGW("Attempt to set active config %d for virtual display", mode);
971 return;
972 }
973 int currentDisplayPowerMode = display->getPowerMode();
974 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
975 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 return;
977 }
978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700980 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800981 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 return;
983 }
984
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 const auto displayId = display->getId();
986 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700990
Ana Krulec7d1d6832018-12-27 11:10:09 -0800991 ATRACE_INT("ActiveConfigMode", mode);
992 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700993}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
996 Vector<ColorMode>* outColorModes) {
997 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700998 return BAD_VALUE;
999 }
1000
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 const auto displayId = getPhysicalDisplayId(displayToken);
1002 if (!displayId) {
1003 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001004 }
1005
Peiyong Lina52f0292018-03-14 17:26:31 -07001006 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001007 {
1008 ConditionalLock _l(mStateLock,
1009 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001011 }
Michael Wright28f24d02016-07-12 13:30:53 -07001012 outColorModes->clear();
1013 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1014
1015 return NO_ERROR;
1016}
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1019 if (const auto display = getDisplayDevice(displayToken)) {
1020 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001021 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001023}
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1026 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001027 if (display->isVirtual()) {
1028 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1029 return;
1030 }
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 ColorMode currentMode = display->getActiveColorMode();
1033 Dataspace currentDataSpace = display->getCompositionDataSpace();
1034 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001035
Peiyong Lin38e9a562018-04-10 16:24:20 -07001036 if (mode == currentMode && dataSpace == currentDataSpace &&
1037 renderIntent == currentRenderIntent) {
1038 return;
1039 }
1040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 display->setActiveColorMode(mode);
1042 display->setCompositionDataSpace(dataSpace);
1043 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001044
Dominik Laskowski075d3172018-05-24 15:50:06 -07001045 const auto displayId = display->getId();
1046 LOG_ALWAYS_FATAL_IF(!displayId);
1047 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1048
Dominik Laskowski34157762018-10-31 13:07:19 -07001049 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001051 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001052}
1053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001055 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 Vector<ColorMode> modes;
1057 getDisplayColorModes(displayToken, &modes);
1058 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1059 if (mode < ColorMode::NATIVE || !exists) {
1060 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1061 decodeColorMode(mode).c_str(), mode, displayToken.get());
1062 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const auto display = getDisplayDevice(displayToken);
1065 if (!display) {
1066 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1067 decodeColorMode(mode).c_str(), mode, displayToken.get());
1068 } else if (display->isVirtual()) {
1069 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1070 decodeColorMode(mode).c_str(), mode);
1071 } else {
1072 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1073 RenderIntent::COLORIMETRIC);
1074 }
1075 }));
1076
Michael Wright28f24d02016-07-12 13:30:53 -07001077 return NO_ERROR;
1078}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001079
Svetoslavd85084b2014-03-20 10:28:31 -07001080status_t SurfaceFlinger::clearAnimationFrameStats() {
1081 Mutex::Autolock _l(mStateLock);
1082 mAnimFrameTracker.clearStats();
1083 return NO_ERROR;
1084}
1085
1086status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1087 Mutex::Autolock _l(mStateLock);
1088 mAnimFrameTracker.getStats(outStats);
1089 return NO_ERROR;
1090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1093 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001094 Mutex::Autolock _l(mStateLock);
1095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const auto display = getDisplayDeviceLocked(displayToken);
1097 if (!display) {
1098 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001099 return BAD_VALUE;
1100 }
1101
Peiyong Linfb069302018-04-25 14:34:31 -07001102 // At this point the DisplayDeivce should already be set up,
1103 // meaning the luminance information is already queried from
1104 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001106 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1107 capabilities.getDesiredMaxLuminance(),
1108 capabilities.getDesiredMaxAverageLuminance(),
1109 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110
1111 return NO_ERROR;
1112}
1113
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001114status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1115 ui::PixelFormat* outFormat,
1116 ui::Dataspace* outDataspace,
1117 uint8_t* outComponentMask) const {
1118 if (!outFormat || !outDataspace || !outComponentMask) {
1119 return BAD_VALUE;
1120 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001121 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001122 if (!display || !display->getId()) {
1123 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1124 return BAD_VALUE;
1125 }
1126 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1127 outDataspace, outComponentMask);
1128}
1129
Kevin DuBois74e53772018-11-19 10:52:38 -08001130status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1131 bool enable, uint8_t componentMask,
1132 uint64_t maxFrames) const {
1133 const auto display = getDisplayDevice(displayToken);
1134 if (!display || !display->getId()) {
1135 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1136 return BAD_VALUE;
1137 }
1138
1139 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1140 componentMask, maxFrames);
1141}
1142
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001143status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1144 uint64_t maxFrames, uint64_t timestamp,
1145 DisplayedFrameStats* outStats) const {
1146 const auto display = getDisplayDevice(displayToken);
1147 if (!display || !display->getId()) {
1148 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1149 return BAD_VALUE;
1150 }
1151
1152 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1153 outStats);
1154}
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001157 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 if (mInjectVSyncs == enable) {
1161 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001162 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163
Ana Krulec98b5b242018-08-10 15:03:23 -07001164 // TODO(akrulec): Part of the Injector should be refactored, so that it
1165 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 if (enable) {
1167 ALOGV("VSync Injections enabled");
1168 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001169 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001170 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001171 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001172 impl::EventThread::InterceptVSyncsCallback(),
1173 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001175 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 } else {
1177 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001178 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001179 }
1180
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001181 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001182 }));
1183
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001184 return NO_ERROR;
1185}
1186
1187status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 Mutex::Autolock _l(mStateLock);
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190 if (!mInjectVSyncs) {
1191 ALOGE("VSync Injections not enabled");
1192 return BAD_VALUE;
1193 }
1194 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1195 ALOGV("Injecting VSync inside SurfaceFlinger");
1196 mVSyncInjector->onInjectSyncEvent(when);
1197 }
1198 return NO_ERROR;
1199}
1200
Lloyd Pique755e3192018-01-31 16:46:15 -08001201status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1202 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001203 // Try to acquire a lock for 1s, fail gracefully
1204 const status_t err = mStateLock.timedLock(s2ns(1));
1205 const bool locked = (err == NO_ERROR);
1206 if (!locked) {
1207 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1208 return TIMED_OUT;
1209 }
1210
1211 outLayers->clear();
1212 mCurrentState.traverseInZOrder([&](Layer* layer) {
1213 outLayers->push_back(layer->getLayerDebugInfo());
1214 });
1215
1216 mStateLock.unlock();
1217 return NO_ERROR;
1218}
1219
Peiyong Linc6780972018-10-28 15:24:08 -07001220status_t SurfaceFlinger::getCompositionPreference(
1221 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1222 Dataspace* outWideColorGamutDataspace,
1223 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001224 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001225 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001226 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001227 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001228 return NO_ERROR;
1229}
1230
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001231// ----------------------------------------------------------------------------
1232
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001233sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1234 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001235 if (mUseScheduler) {
1236 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1237 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1238 } else {
1239 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1240 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001241 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001242 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1243 return mSFEventThread->createEventConnection();
1244 } else {
1245 return mEventThread->createEventConnection();
1246 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001247 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001248}
1249
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001250// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001251
1252void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001253 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001254}
1255
1256void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001257 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001261 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001265 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001266 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267}
1268
1269status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001270 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001271 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001272}
1273
1274status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001275 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001276 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277 if (res == NO_ERROR) {
1278 msg->wait();
1279 }
1280 return res;
1281}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001282
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001283void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001284 do {
1285 waitForEvent();
1286 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287}
1288
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289void SurfaceFlinger::enableHardwareVsync() {
1290 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001292 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001295 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296}
1297
Jesse Hall948fe0c2013-10-14 12:56:09 -07001298void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 Mutex::Autolock _l(mHWVsyncLock);
1300
Jesse Hall948fe0c2013-10-14 12:56:09 -07001301 if (makeAvailable) {
1302 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001303 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1304 if (mUseScheduler) {
1305 mScheduler->makeHWSyncAvailable(true);
1306 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001308 // Hardware vsync is not currently available, so abort the resync
1309 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 return;
1311 }
1312
Dominik Laskowski075d3172018-05-24 15:50:06 -07001313 const auto displayId = getInternalDisplayId();
1314 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001315 return;
1316 }
1317
Dominik Laskowski075d3172018-05-24 15:50:06 -07001318 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320
Ana Krulece588e312018-09-18 12:32:24 -07001321 if (mUseScheduler) {
1322 mScheduler->setVsyncPeriod(period);
1323 } else {
1324 mPrimaryDispSync->reset();
1325 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326
Ana Krulece588e312018-09-18 12:32:24 -07001327 if (!mPrimaryHWVsyncEnabled) {
1328 mPrimaryDispSync->beginResync();
1329 mEventControlThread->setVsyncEnabled(true);
1330 mPrimaryHWVsyncEnabled = true;
1331 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 }
1333}
1334
Jesse Hall948fe0c2013-10-14 12:56:09 -07001335void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 Mutex::Autolock _l(mHWVsyncLock);
1337 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001338 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001339 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340 mPrimaryHWVsyncEnabled = false;
1341 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001342 if (makeUnavailable) {
1343 mHWVsyncAvailable = false;
1344 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345}
1346
Tim Murray4a4e4a22016-04-19 16:29:23 +00001347void SurfaceFlinger::resyncWithRateLimit() {
1348 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001349
1350 // No explicit locking is needed here since EventThread holds a lock while calling this method
1351 static nsecs_t sLastResyncAttempted = 0;
1352 const nsecs_t now = systemTime();
1353 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001354 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001355 }
Dan Stoza57164302017-05-08 14:03:54 -07001356 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001357}
1358
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1360 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001361 ATRACE_NAME("SF onVsync");
1362
Steven Thomas3cfac282017-02-06 12:29:30 -08001363 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001365 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 return;
1367 }
1368
Dominik Laskowski075d3172018-05-24 15:50:06 -07001369 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001370 return;
1371 }
1372
Dominik Laskowski075d3172018-05-24 15:50:06 -07001373 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001374 // For now, we don't do anything with external display vsyncs.
1375 return;
1376 }
1377
Ana Krulece588e312018-09-18 12:32:24 -07001378 if (mUseScheduler) {
1379 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001380 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001381 bool needsHwVsync = false;
1382 { // Scope for the lock
1383 Mutex::Autolock _l(mHWVsyncLock);
1384 if (mPrimaryHWVsyncEnabled) {
1385 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1386 }
1387 }
1388
1389 if (needsHwVsync) {
1390 enableHardwareVsync();
1391 } else {
1392 disableHardwareVsync(false);
1393 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001394 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001395}
1396
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001398 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1399 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400}
1401
Ana Krulec7d1d6832018-12-27 11:10:09 -08001402void SurfaceFlinger::setRefreshRateTo(float newFps) {
1403 const auto displayId = getInternalDisplayId();
1404 if (!displayId || mBootStage != BootStage::FINISHED) {
1405 return;
1406 }
1407 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1408 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1409 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1410 // refresh cycle.
1411
1412 // Don't do any updating if the current fps is the same as the new one.
1413 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1414 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1415 if (currentVsyncPeriod == 0) {
1416 return;
1417 }
1418 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1419 // floating numbers.
1420 const float currentFps = 1e9 / currentVsyncPeriod;
1421 if (std::abs(currentFps - newFps) <= 1) {
1422 return;
1423 }
1424
1425 auto configs = getHwComposer().getConfigs(*displayId);
1426 for (int i = 0; i < configs.size(); i++) {
1427 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1428 if (vsyncPeriod == 0) {
1429 continue;
1430 }
1431 const float fps = 1e9 / vsyncPeriod;
1432 // TODO(b/113612090): There should be a better way at determining which config
1433 // has the right refresh rate.
1434 if (std::abs(fps - newFps) <= 1) {
1435 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1436 if (!display) return;
1437 // This is posted in async function to avoid deadlock when getDisplayDevice
1438 // requires mStateLock.
1439 setActiveConfigAsync(display, i);
1440 ATRACE_INT("FPS", newFps);
1441 }
1442 }
1443}
1444
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001445void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001446 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001447 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001448 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449
Lloyd Piqueba04e622017-12-14 17:11:26 -08001450 // Ignore events that do not have the right sequenceId.
1451 if (sequenceId != getBE().mComposerSequenceId) {
1452 return;
1453 }
1454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Only lock if we're not on the main thread. This function is normally
1456 // called on a hwbinder thread, but for the primary display it's called on
1457 // the main thread with the state lock already held, so don't attempt to
1458 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001460
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001461 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001462
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001463 if (std::this_thread::get_id() == mMainThreadId) {
1464 // Process all pending hot plug events immediately if we are on the main thread.
1465 processDisplayHotplugEventsLocked();
1466 }
1467
Lloyd Piqueba04e622017-12-14 17:11:26 -08001468 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001469}
1470
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001471void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001472 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001473 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001474 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001475 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001476 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001477}
1478
Dominik Laskowski075d3172018-05-24 15:50:06 -07001479void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001480 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001482 if (const auto displayId = getInternalDisplayId()) {
1483 getHwComposer().setVsyncEnabled(*displayId,
1484 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1485 }
Mathias Agopian86303202012-07-24 22:46:10 -07001486}
1487
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001488// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001489void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001490 if (mUseScheduler) {
1491 mScheduler->disableHardwareVsync(true);
1492 } else {
1493 disableHardwareVsync(true);
1494 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001495 // Clear the drawing state so that the logic inside of
1496 // handleTransactionLocked will fire. It will determine the delta between
1497 // mCurrentState and mDrawingState and re-apply all changes when we make the
1498 // transition.
1499 mDrawingState.displays.clear();
1500 mDisplays.clear();
1501}
1502
Steven Thomas050b2c82017-03-06 11:45:16 -08001503void SurfaceFlinger::updateVrFlinger() {
1504 if (!mVrFlinger)
1505 return;
1506 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001507 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001508 return;
1509 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001510
Lloyd Pique441d5042018-10-18 16:49:51 -07001511 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001512 ALOGE("Vr flinger is only supported for remote hardware composer"
1513 " service connections. Ignoring request to transition to vr"
1514 " flinger.");
1515 mVrFlingerRequestsDisplay = false;
1516 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001517 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001518
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001520
Steven Thomas0123ac62018-07-12 11:32:34 -07001521 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001522 LOG_ALWAYS_FATAL_IF(!display);
1523 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001524 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1525 // called below. Clear the reference now so we don't accidentally use it
1526 // later.
1527 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001532
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001534 // Delete the current instance before creating the new one
1535 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1536 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1537 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1538 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001541 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001542
1543 if (vrFlingerRequestsDisplay) {
1544 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546
1547 mVisibleRegionsDirty = true;
1548 invalidateHwcGeometry();
1549
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001550 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001551 display = getDefaultDisplayDeviceLocked();
1552 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001553 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001554
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001556 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001557 const nsecs_t period = activeConfig->getVsyncPeriod();
1558 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001559
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001560 // The present fences returned from vr_hwc are not an accurate
1561 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001562 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001563 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1564 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001565 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001566 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001567 !hasSyncFramework);
1568 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001569
Steven Thomasb02664d2017-07-26 18:48:28 -07001570 // Use phase of 0 since phase is not known.
1571 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001572 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1573 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001574
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001575 resyncToHardwareVsync(false);
1576
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001577 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001578 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001579}
1580
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001582 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001583 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001584 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001585 if (mUseScheduler) {
1586 // This call is made each time SF wakes up and creates a new frame.
1587 mScheduler->incrementFrameCounter();
1588 }
Dan Stoza50182882016-07-08 12:02:20 -07001589 bool frameMissed = !mHadClientComposition &&
1590 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001591 (mPreviousPresentFence->getSignalTime() ==
1592 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001593 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001594 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001595 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001596 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001597 if (mPropagateBackpressure) {
1598 signalLayerUpdate();
1599 break;
1600 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001601 }
Dan Stoza50182882016-07-08 12:02:20 -07001602
Steven Thomas050b2c82017-03-06 11:45:16 -08001603 // Now that we're going to make it to the handleMessageTransaction()
1604 // call below it's safe to call updateVrFlinger(), which will
1605 // potentially trigger a display handoff.
1606 updateVrFlinger();
1607
Dan Stoza6b9454d2014-11-07 16:00:59 -08001608 bool refreshNeeded = handleMessageTransaction();
1609 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001610 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001611 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001612 // Signal a refresh if a transaction modified the window state,
1613 // a new buffer was latched, or if HWC has requested a full
1614 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001615 signalRefresh();
1616 }
1617 break;
1618 }
1619 case MessageQueue::REFRESH: {
1620 handleMessageRefresh();
1621 break;
1622 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001623 }
1624}
1625
Dan Stoza6b9454d2014-11-07 16:00:59 -08001626bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001627 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001628
1629 // Apply any ready transactions in the queues if there are still transactions that have not been
1630 // applied, wake up during the next vsync period and check again
1631 bool transactionNeeded = false;
1632 if (!flushTransactionQueues()) {
1633 transactionNeeded = true;
1634 }
1635
Mathias Agopian4fec8732012-06-29 14:12:52 -07001636 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001637 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001638 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001639
1640 if (transactionNeeded) {
1641 setTransactionFlags(eTransactionNeeded);
1642 }
1643
1644 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001645}
1646
Mathias Agopian4fec8732012-06-29 14:12:52 -07001647void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001648 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001649
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001650 mRefreshPending = false;
1651
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001652 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001653 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001654 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001655 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001656 for (const auto& [token, display] : mDisplays) {
1657 beginFrame(display);
1658 prepareFrame(display);
1659 doDebugFlashRegions(display, repaintEverything);
1660 doComposition(display, repaintEverything);
1661 }
1662
Adrian Roos1e1a1282017-11-01 19:05:31 +01001663 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001664 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001665
1666 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001667 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001668
Dan Stozabfbffeb2016-07-21 14:49:33 -07001669 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001670 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001671 mHadClientComposition =
1672 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001673 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001674
Alec Mouri86770e52018-09-24 22:40:58 +00001675 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001676 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001677 if (mHadClientComposition) {
1678 base::unique_fd flushFence(getRenderEngine().flush());
1679 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1680 getBE().flushFence = new Fence(std::move(flushFence));
1681 } else {
1682 // Cleanup for hygiene.
1683 getBE().flushFence = Fence::NO_FENCE;
1684 }
1685 }
1686
Jorim Jaggi90535212018-05-23 23:44:06 +02001687 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001688
David Sodman7e4ae112018-02-09 15:02:28 -08001689 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001690 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001691 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001692 compositionInfo.hwc.hwcLayer = nullptr;
1693 }
David Sodmanba340492018-08-05 21:51:33 -07001694 }
David Sodman7e4ae112018-02-09 15:02:28 -08001695
1696 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001698
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699
1700bool SurfaceFlinger::handleMessageInvalidate() {
1701 ATRACE_CALL();
1702 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001703}
1704
David Sodman79bba0e2018-08-05 18:07:49 -07001705void SurfaceFlinger::calculateWorkingSet() {
1706 ATRACE_CALL();
1707 ALOGV(__FUNCTION__);
1708
David Sodman79bba0e2018-08-05 18:07:49 -07001709 // build the h/w work list
1710 if (CC_UNLIKELY(mGeometryInvalid)) {
1711 mGeometryInvalid = false;
1712 for (const auto& [token, display] : mDisplays) {
1713 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001714 if (!displayId) {
1715 continue;
1716 }
David Sodman79bba0e2018-08-05 18:07:49 -07001717
Dominik Laskowski075d3172018-05-24 15:50:06 -07001718 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1719 for (size_t i = 0; i < currentLayers.size(); i++) {
1720 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001721
Dominik Laskowski075d3172018-05-24 15:50:06 -07001722 if (!layer->hasHwcLayer(*displayId)) {
1723 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1724 layer->forceClientComposition(*displayId);
1725 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001726 }
1727 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728
1729 layer->setGeometry(display, i);
1730 if (mDebugDisableHWC || mDebugRegion) {
1731 layer->forceClientComposition(*displayId);
1732 }
David Sodman79bba0e2018-08-05 18:07:49 -07001733 }
1734 }
1735 }
1736
1737 // Set the per-frame data
1738 for (const auto& [token, display] : mDisplays) {
1739 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001740 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001741 continue;
1742 }
1743
1744 if (mDrawingState.colorMatrixChanged) {
1745 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746 status_t result =
1747 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001748 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1749 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001750 }
1751 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1752 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001753 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001754 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1755 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1756 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001757 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001758 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1759 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1760 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001761 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001762 }
1763
Peiyong Lind3788632018-09-18 16:01:31 -07001764 // TODO(b/111562338) remove when composer 2.3 is shipped.
1765 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001766 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001767 }
1768
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001769 if (layer->getRoundedCornerState().radius > 0.0f) {
1770 layer->forceClientComposition(*displayId);
1771 }
1772
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001774 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001775 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001776 continue;
1777 }
1778
Dominik Laskowski075d3172018-05-24 15:50:06 -07001779 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1780 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001781 }
1782
Peiyong Lin13effd12018-07-24 17:01:47 -07001783 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001784 ColorMode colorMode;
1785 Dataspace dataSpace;
1786 RenderIntent renderIntent;
1787 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1788 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1789 }
1790 }
1791
1792 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001793
1794 for (const auto& [token, display] : mDisplays) {
1795 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001796 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001797 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001798
1799 if (displayId) {
1800 if (!layer->setHwcLayer(*displayId)) {
1801 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1802 }
1803 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001804 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805
Dominik Laskowski05275f12018-11-01 15:03:24 -07001806 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001807 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1808 }
1809 }
David Sodman79bba0e2018-08-05 18:07:49 -07001810}
1811
David Sodmanfa9b2af2017-12-24 13:28:59 -08001812void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001813{
1814 // is debugging enabled
1815 if (CC_LIKELY(!mDebugRegion))
1816 return;
1817
David Sodmanfa9b2af2017-12-24 13:28:59 -08001818 if (display->isPoweredOn()) {
1819 // transform the dirty region into this screen's coordinate space
1820 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1821 if (!dirtyRegion.isEmpty()) {
1822 // redraw the whole screen
1823 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001824
David Sodmanfa9b2af2017-12-24 13:28:59 -08001825 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001826 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001827 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001828
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001829 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830 }
1831 }
1832
David Sodmanfa9b2af2017-12-24 13:28:59 -08001833 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834
1835 if (mDebugRegion > 1) {
1836 usleep(mDebugRegion * 1000);
1837 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001838
Dominik Laskowski05275f12018-11-01 15:03:24 -07001839 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840}
1841
Adrian Roos1e1a1282017-11-01 19:05:31 +01001842void SurfaceFlinger::doTracing(const char* where) {
1843 ATRACE_CALL();
1844 ATRACE_NAME(where);
1845 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001846 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001847 }
1848}
1849
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001850void SurfaceFlinger::logLayerStats() {
1851 ATRACE_CALL();
1852 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001853 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001854 if (display->isPrimary()) {
1855 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001856 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001857 }
1858 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001859
1860 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001861 }
1862}
1863
David Sodman2b406362017-12-15 13:33:47 -08001864void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 ATRACE_CALL();
1867 ALOGV("preComposition");
1868
David Sodman2b406362017-12-15 13:33:47 -08001869 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1870
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001872 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001873 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001874 needExtraInvalidate = true;
1875 }
Robert Carr2047fae2016-11-28 14:09:09 -08001876 });
1877
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878 if (needExtraInvalidate) {
1879 signalLayerUpdate();
1880 }
1881}
1882
Ana Krulece588e312018-09-18 12:32:24 -07001883void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1884 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001885 // Update queue of past composite+present times and determine the
1886 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001887 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001888 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001889 while (!getBE().mCompositePresentTimes.empty()) {
1890 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001891 // Cached values should have been updated before calling this method,
1892 // which helps avoid duplicate syscalls.
1893 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1894 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1895 break;
1896 }
1897 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001898 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 }
1900
1901 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001902 while (getBE().mCompositePresentTimes.size() > 16) {
1903 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001904 }
1905
Ana Krulece588e312018-09-18 12:32:24 -07001906 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001907}
1908
Ana Krulece588e312018-09-18 12:32:24 -07001909void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1910 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // Integer division and modulo round toward 0 not -inf, so we need to
1912 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001913 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1914 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1915 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916
Brian Andersond0010582017-03-07 13:20:31 -08001917 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1918 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001919 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001920 }
1921
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001922 // Snap the latency to a value that removes scheduling jitter from the
1923 // composition and present times, which often have >1ms of jitter.
1924 // Reducing jitter is important if an app attempts to extrapolate
1925 // something (such as user input) to an accurate diasplay time.
1926 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1927 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001928 nsecs_t bias = stats.vsyncPeriod / 2;
1929 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1930 nsecs_t snappedCompositeToPresentLatency =
1931 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932
David Sodman99974d22017-11-28 12:04:33 -08001933 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001934 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1935 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001936 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937}
1938
Ady Abraham8164d482019-01-11 14:47:59 -08001939// debug patch for b/119477596 - add stack guards to catch stack
1940// corruptions and disable clang optimizations.
1941// The code below is temporary and planned to be removed once stack
1942// corruptions are found.
1943#pragma clang optimize off
1944class StackGuard {
1945public:
1946 StackGuard(const char* name, const char* func, int line) {
1947 guarders.reserve(MIN_CAPACITY);
1948 guarders.push_back({this, name, func, line});
1949 validate();
1950 }
1951 ~StackGuard() {
1952 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1953 if (i->guard == this) {
1954 guarders.erase(i);
1955 break;
1956 }
1957 }
1958 }
1959
1960 static void validate() {
1961 for (const auto& guard : guarders) {
1962 if (guard.guard->cookie != COOKIE_VALUE) {
1963 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1964 CallStack stack(LOG_TAG);
1965 abort();
1966 }
1967 }
1968 }
1969
1970private:
1971 uint64_t cookie = COOKIE_VALUE;
1972 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1973 static constexpr size_t MIN_CAPACITY = 16;
1974
1975 struct GuarderElement {
1976 StackGuard* guard;
1977 const char* name;
1978 const char* func;
1979 int line;
1980 };
1981
1982 static std::vector<GuarderElement> guarders;
1983};
1984std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1985
1986#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1987
1988#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001989void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990{
Ady Abraham8164d482019-01-11 14:47:59 -08001991 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 ATRACE_CALL();
1993 ALOGV("postComposition");
1994
Brian Anderson3546a3f2016-07-14 11:51:14 -07001995 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001996 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001997 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001998 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001999 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002000 }
Ady Abraham8164d482019-01-11 14:47:59 -08002001 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002002
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002003 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002005 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002006
David Sodman73beded2017-11-15 11:56:06 -08002007 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002009 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2010
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002011 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002013 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002014 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002015 } else {
2016 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2017 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018
Ady Abraham8164d482019-01-11 14:47:59 -08002019 ASSERT_ON_STACK_GUARD();
2020
David Sodman73beded2017-11-15 11:56:06 -08002021 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002022 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002023 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002024 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002025 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002026 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027
Ana Krulece588e312018-09-18 12:32:24 -07002028 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002029 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002030 if (mUseScheduler) {
2031 mScheduler->getDisplayStatInfo(&stats);
2032 } else {
2033 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2034 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2035 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036
Ady Abraham8164d482019-01-11 14:47:59 -08002037 ASSERT_ON_STACK_GUARD();
2038
David Sodman2b406362017-12-15 13:33:47 -08002039 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002040 // when we started doing work for this frame, but that should be okay
2041 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002042 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002043 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(compositorTiming);
2045
Brian Andersond0010582017-03-07 13:20:31 -08002046 {
David Sodman99974d22017-11-28 12:04:33 -08002047 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002048 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002049 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002050
2051 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002052 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053
Robert Carr2047fae2016-11-28 14:09:09 -08002054 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002055 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2056 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002057 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002058 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002059 recordBufferingStats(layer->getName().string(),
2060 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002061 }
Ady Abraham8164d482019-01-11 14:47:59 -08002062 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002063 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002064
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002065 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002066 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002067 if (mUseScheduler) {
2068 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002069 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002070 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002071 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2072 enableHardwareVsync();
2073 } else {
2074 disableHardwareVsync(false);
2075 }
Ady Abraham8164d482019-01-11 14:47:59 -08002076 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002077 }
2078 }
2079
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002080 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002081 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002082 if (mUseScheduler) {
2083 mScheduler->enableHardwareVsync();
2084 } else {
2085 enableHardwareVsync();
2086 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002087 }
2088 }
2089
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
2091
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 if (mAnimCompositionPending) {
2093 mAnimCompositionPending = false;
2094
Brian Anderson4e606e32017-03-16 15:34:57 -07002095 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002096 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002097 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002098
2099 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002100 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002101 // The HWC doesn't support present fences, so use the refresh
2102 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002103 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002104 DEFINE_STACK_GUARD(presentTime);
2105
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002107 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002108 }
2109 mAnimFrameTracker.advanceFrame();
2110 }
Dan Stozab90cf072015-03-05 11:05:59 -08002111
Ady Abraham8164d482019-01-11 14:47:59 -08002112 ASSERT_ON_STACK_GUARD();
2113
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002114 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002115 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002116 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002117 }
2118
Ady Abraham8164d482019-01-11 14:47:59 -08002119 ASSERT_ON_STACK_GUARD();
2120
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002121 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002122
Ady Abraham8164d482019-01-11 14:47:59 -08002123 ASSERT_ON_STACK_GUARD();
2124
Dominik Laskowski075d3172018-05-24 15:50:06 -07002125 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002126 return;
2127 }
2128
2129 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002130 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002131 if (mHasPoweredOff) {
2132 mHasPoweredOff = false;
2133 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002134 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002135 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002136 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002137 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002138 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2139 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002140 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002141 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002142 }
David Sodman4a36e932017-11-07 14:29:47 -08002143 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002144
2145 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002146 }
David Sodman4a36e932017-11-07 14:29:47 -08002147 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002149
2150 {
2151 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002152 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002153 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002155 if (refillCount > 0) {
2156 const size_t offset = mTexturePool.size();
2157 mTexturePool.resize(mTexturePoolSize);
2158 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2159 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2160 }
Ady Abraham8164d482019-01-11 14:47:59 -08002161 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002162 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002163
Marissa Wallfda30bb2018-10-12 11:34:28 -07002164 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002165 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002166
2167 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002168}
Ady Abraham8164d482019-01-11 14:47:59 -08002169#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170
2171void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 ATRACE_CALL();
2173 ALOGV("rebuildLayerStacks");
2174
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002175 // We need to clear these out now as these may be holding on to a
2176 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2177 // also holds a reference. When the set of visible layers is recomputed,
2178 // some layers may be destroyed if the only thing keeping them alive was
2179 // that list of visible layers associated with each display. The layer
2180 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2181 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2182 for (const auto& [token, display] : mDisplays) {
2183 getBE().mCompositionInfo[token].clear();
2184 }
2185
Mathias Agopiancd60f992012-08-16 16:28:27 -07002186 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002187 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002188 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002189 mVisibleRegionsDirty = false;
2190 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002191
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002192 for (const auto& pair : mDisplays) {
2193 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002194 Region opaqueRegion;
2195 Region dirtyRegion;
2196 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002197 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002198 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002199 const Rect bounds = display->getBounds();
2200 if (display->isPoweredOn()) {
2201 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002202
Jeff Sharkey76488112017-02-27 14:15:18 -07002203 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002204 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002205 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002207 Region drawRegion(tr.transform(
2208 layer->visibleNonTransparentRegion));
2209 drawRegion.andSelf(bounds);
2210 if (!drawRegion.isEmpty()) {
2211 layersSortedByZ.add(layer);
2212 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002213 // Clear out the HWC layer if this layer was
2214 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002216 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002217 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002218 // WM changes display->layerStack upon sleep/awake.
2219 // Here we make sure we delete the HWC layers even if
2220 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002221 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002222 }
2223
2224 // If a layer is not going to get a release fence because
2225 // it is invisible, but it is also going to release its
2226 // old buffer, add it to the list of layers needing
2227 // fences.
2228 if (hwcLayerDestroyed) {
2229 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2230 mLayersWithQueuedFrames.cend(), layer);
2231 if (found != mLayersWithQueuedFrames.cend()) {
2232 layersNeedingFences.add(layer);
2233 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002234 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002235 });
2236 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002237 display->setVisibleLayersSortedByZ(layersSortedByZ);
2238 display->setLayersNeedingFences(layersNeedingFences);
2239 display->undefinedRegion.set(bounds);
2240 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2241 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002242 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002243 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002244}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002245
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002246// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002247// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002248// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002249// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002250// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002251// The returned HDR data space is one of
2252// - Dataspace::UNKNOWN
2253// - Dataspace::BT2020_HLG
2254// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002255Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2256 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002257 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002258 *outHdrDataSpace = Dataspace::UNKNOWN;
2259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002260 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002261 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002262 case Dataspace::V0_SCRGB:
2263 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002264 case Dataspace::BT2020:
2265 case Dataspace::BT2020_ITU:
2266 case Dataspace::BT2020_LINEAR:
2267 case Dataspace::DISPLAY_BT2020:
2268 bestDataSpace = Dataspace::DISPLAY_BT2020;
2269 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002271 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 case Dataspace::BT2020_PQ:
2274 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002275 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002277 case Dataspace::BT2020_HLG:
2278 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002279 // When there's mixed PQ content and HLG content, we set the HDR
2280 // data space to be BT2020_PQ and convert HLG to PQ.
2281 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2282 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002283 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 break;
2285 default:
2286 break;
2287 }
Romain Guy54f154a2017-10-24 21:40:32 +01002288 }
2289
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002291}
2292
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002293// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002294void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2295 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002296 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2297 *outMode = ColorMode::NATIVE;
2298 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002299 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002301 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002302
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002304 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305
Peiyong Lindfde5112018-06-05 10:58:41 -07002306 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002307 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002308 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002309 if (isHdr) {
2310 bestDataSpace = hdrDataSpace;
2311 }
2312
Chia-I Wu0d711262018-05-21 15:19:35 -07002313 RenderIntent intent;
2314 switch (mDisplayColorSetting) {
2315 case DisplayColorSetting::MANAGED:
2316 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002317 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002318 break;
2319 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002320 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002321 break;
2322 default: // vendor display color setting
2323 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2324 break;
2325 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002328}
2329
David Sodmanfa9b2af2017-12-24 13:28:59 -08002330void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002331{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002332 bool dirty = !display->getDirtyRegion(false).isEmpty();
2333 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2334 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002335
David Sodmanfa9b2af2017-12-24 13:28:59 -08002336 // If nothing has changed (!dirty), don't recompose.
2337 // If something changed, but we don't currently have any visible layers,
2338 // and didn't when we last did a composition, then skip it this time.
2339 // The second rule does two things:
2340 // - When all layers are removed from a display, we'll emit one black
2341 // frame, then nothing more until we get new layers.
2342 // - When a display is created with a private layer stack, we won't
2343 // emit any black frames until a layer is added to the layer stack.
2344 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002345
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 const char flagPrefix[] = {'-', '+'};
2347 static_cast<void>(flagPrefix);
2348 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2349 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2350 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002351
David Sodmanfa9b2af2017-12-24 13:28:59 -08002352 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002353
David Sodmanfa9b2af2017-12-24 13:28:59 -08002354 if (mustRecompose) {
2355 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002356 }
2357}
2358
David Sodmanfa9b2af2017-12-24 13:28:59 -08002359void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002360{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002361 if (!display->isPoweredOn()) {
2362 return;
David Sodman2b406362017-12-15 13:33:47 -08002363 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002364
Dominik Laskowski05275f12018-11-01 15:03:24 -07002365 status_t result = display->prepareFrame(getHwComposer(),
2366 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002367 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2368 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002369}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002370
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002372 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 ALOGV("doComposition");
2374
David Sodmanfa9b2af2017-12-24 13:28:59 -08002375 if (display->isPoweredOn()) {
2376 // transform the dirty region into this screen's coordinate space
2377 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002378
David Sodmanfa9b2af2017-12-24 13:28:59 -08002379 // repaint the framebuffer (if needed)
2380 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002381
David Sodmanfa9b2af2017-12-24 13:28:59 -08002382 display->dirtyRegion.clear();
2383 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002384 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002386}
2387
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388void SurfaceFlinger::postFrame()
2389{
2390 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 const auto display = getDefaultDisplayDeviceLocked();
2392 if (display && getHwComposer().isConnected(*display->getId())) {
2393 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002394 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2395 logFrameStats();
2396 }
2397 }
2398}
2399
2400void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401{
Mathias Agopian841cde52012-03-01 15:44:37 -08002402 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002404
David Sodmanfa9b2af2017-12-24 13:28:59 -08002405 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002406
David Sodmanfa9b2af2017-12-24 13:28:59 -08002407 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002408 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 if (displayId) {
2410 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002411 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002412 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002413 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002414 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002415
Chia-I Wu7b549592017-11-15 09:14:57 -08002416 // The layer buffer from the previous frame (if any) is released
2417 // by HWC only when the release fence from this frame (if any) is
2418 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 if (displayId && layer->hasHwcLayer(*displayId)) {
2420 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2421 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002422 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002423
2424 // If the layer was client composited in the previous frame, we
2425 // need to merge with the previous client target acquire fence.
2426 // Since we do not track that, always merge with the current
2427 // client target acquire fence when it is available, even though
2428 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002429 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002430 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002432 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002433
David Sodman15094112018-10-11 09:39:37 -07002434 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 }
Chia-I Wu83806892017-11-16 10:50:20 -08002436
2437 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002439 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002442 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002444 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002445 }
2446 }
2447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 if (displayId) {
2449 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002450 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452}
2453
Mathias Agopian87baae12012-07-31 12:38:26 -07002454void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455{
Mathias Agopian841cde52012-03-01 15:44:37 -08002456 ATRACE_CALL();
2457
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002458 // here we keep a copy of the drawing state (that is the state that's
2459 // going to be overwritten by handleTransactionLocked()) outside of
2460 // mStateLock so that the side-effects of the State assignment
2461 // don't happen with mStateLock held (which can cause deadlocks).
2462 State drawingState(mDrawingState);
2463
Mathias Agopianca4d3602011-05-19 15:38:14 -07002464 Mutex::Autolock _l(mStateLock);
2465 const nsecs_t now = systemTime();
2466 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467
Mathias Agopianca4d3602011-05-19 15:38:14 -07002468 // Here we're guaranteed that some transaction flags are set
2469 // so we can call handleTransactionLocked() unconditionally.
2470 // We call getTransactionFlags(), which will also clear the flags,
2471 // with mStateLock held to guarantee that mCurrentState won't change
2472 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002473
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002474 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002475 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002476 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002477
Mathias Agopianca4d3602011-05-19 15:38:14 -07002478 mLastTransactionTime = systemTime() - now;
2479 mDebugInTransaction = 0;
2480 invalidateHwcGeometry();
2481 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002482}
2483
Lloyd Piqueba04e622017-12-14 17:11:26 -08002484void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2485 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 const std::optional<DisplayIdentificationInfo> info =
2487 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002490 continue;
2491 }
2492
Lloyd Piqueba04e622017-12-14 17:11:26 -08002493 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002495 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 mPhysicalDisplayTokens[info->id] = new BBinder();
2497 DisplayDeviceState state;
2498 state.displayId = info->id;
2499 state.isSecure = true; // All physical displays are currently considered secure.
2500 state.displayName = info->name;
2501 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2502 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002503 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002504 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002505 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002506
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2508 if (index >= 0) {
2509 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2510 mInterceptor->saveDisplayDeletion(state.sequenceId);
2511 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002512 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 }
2515
2516 processDisplayChangesLocked();
2517 }
2518
2519 mPendingHotplugEvents.clear();
2520}
2521
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2524 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2525 const sp<IGraphicBufferProducer>& producer) {
2526 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002527 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002529 creationArgs.isSecure = state.isSecure;
2530 creationArgs.displaySurface = dispSurface;
2531 creationArgs.hasWideColorGamut = false;
2532 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002533
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2535 creationArgs.isPrimary = isInternalDisplay;
2536
2537 if (useColorManagement && displayId) {
2538 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002540 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002541 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002543
Dominik Laskowski7e045462018-05-30 13:02:02 -07002544 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002546 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 }
tangrobin6753a022018-08-10 10:58:54 +08002548 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 if (displayId) {
2551 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002552 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002554 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555
Lloyd Pique90c115d2018-09-18 21:39:42 -07002556 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002558 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Lloyd Pique99d3da52018-01-22 17:48:03 -08002560 // Make sure that composition can never be stalled by a virtual display
2561 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002562 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002563 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2565 }
2566
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 creationArgs.displayInstallOrientation =
2568 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002569
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002571 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572
Lloyd Pique90c115d2018-09-18 21:39:42 -07002573 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574
2575 if (maxFrameBufferAcquiredBuffers >= 3) {
2576 nativeWindowSurface->preallocateBuffers();
2577 }
2578
2579 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002580 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002583 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002585 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002586 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 if (!state.isVirtual()) {
2588 LOG_ALWAYS_FATAL_IF(!displayId);
2589 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002590 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002592 display->setLayerStack(state.layerStack);
2593 display->setProjection(state.orientation, state.viewport, state.frame);
2594 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597}
2598
Lloyd Pique347200f2017-12-14 17:00:15 -08002599void SurfaceFlinger::processDisplayChangesLocked() {
2600 // here we take advantage of Vector's copy-on-write semantics to
2601 // improve performance by skipping the transaction entirely when
2602 // know that the lists are identical
2603 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2604 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2605 if (!curr.isIdenticalTo(draw)) {
2606 mVisibleRegionsDirty = true;
2607 const size_t cc = curr.size();
2608 size_t dc = draw.size();
2609
2610 // find the displays that were removed
2611 // (ie: in drawing state but not in current state)
2612 // also handle displays that changed
2613 // (ie: displays that are in both lists)
2614 for (size_t i = 0; i < dc;) {
2615 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2616 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002617 // Save display IDs before disconnecting.
2618 const auto internalDisplayId = getInternalDisplayId();
2619 const auto externalDisplayId = getExternalDisplayId();
2620
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002622 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002623 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002624 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002626 if (mUseScheduler) {
2627 mScheduler->hotplugReceived(mAppConnectionHandle,
2628 EventThread::DisplayType::Primary, false);
2629 } else {
2630 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2631 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002633 if (mUseScheduler) {
2634 mScheduler->hotplugReceived(mAppConnectionHandle,
2635 EventThread::DisplayType::External, false);
2636 } else {
2637 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2638 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002639 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002640 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002641 } else {
2642 // this display is in both lists. see if something changed.
2643 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2646 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2647 if (state_binder != draw_binder) {
2648 // changing the surface is like destroying and
2649 // recreating the DisplayDevice, so we just remove it
2650 // from the drawing state, so that it get re-added
2651 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002653 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002655 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002656 mDrawingState.displays.removeItemsAt(i);
2657 dc--;
2658 // at this point we must loop to the next item
2659 continue;
2660 }
2661
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 }
2666 if ((state.orientation != draw[i].orientation) ||
2667 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 }
2670 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002671 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002672 }
2673 }
2674 }
2675 ++i;
2676 }
2677
2678 // find displays that were added
2679 // (ie: in current state but not in drawing state)
2680 for (size_t i = 0; i < cc; i++) {
2681 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2682 const DisplayDeviceState& state(curr[i]);
2683
2684 sp<DisplaySurface> dispSurface;
2685 sp<IGraphicBufferProducer> producer;
2686 sp<IGraphicBufferProducer> bqProducer;
2687 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002688 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002689
Dominik Laskowski075d3172018-05-24 15:50:06 -07002690 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002691 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002692 // Virtual displays without a surface are dormant:
2693 // they have external state (layer stack, projection,
2694 // etc.) but no internal state (i.e. a DisplayDevice).
2695 if (state.surface != nullptr) {
2696 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002697 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002698 int width = 0;
2699 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2700 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2701 int height = 0;
2702 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2703 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2704 int intFormat = 0;
2705 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2706 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002707 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 displayId =
2710 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712
2713 // TODO: Plumb requested format back up to consumer
2714
2715 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002716 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 bqProducer, bqConsumer,
2718 state.displayName);
2719
2720 dispSurface = vds;
2721 producer = vds;
2722 }
2723 } else {
2724 ALOGE_IF(state.surface != nullptr,
2725 "adding a supported display, but rendering "
2726 "surface is provided (%p), ignoring it",
2727 state.surface.get());
2728
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 displayId = state.displayId;
2730 LOG_ALWAYS_FATAL_IF(!displayId);
2731 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 producer = bqProducer;
2733 }
2734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002735 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002737 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002738 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002739 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002740 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 LOG_ALWAYS_FATAL_IF(!displayId);
2742
2743 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002744 if (mUseScheduler) {
2745 mScheduler->hotplugReceived(mAppConnectionHandle,
2746 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002747 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002748 } else {
2749 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2750 true);
2751 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002752 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002753 if (mUseScheduler) {
2754 mScheduler->hotplugReceived(mAppConnectionHandle,
2755 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002756 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002757 } else {
2758 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2759 true);
2760 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002761 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 }
2763 }
2764 }
2765 }
2766 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002767
2768 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002769}
2770
Mathias Agopian87baae12012-07-31 12:38:26 -07002771void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002772{
Dan Stoza7dde5992015-05-22 09:51:44 -07002773 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002774 mCurrentState.traverseInZOrder([](Layer* layer) {
2775 layer->notifyAvailableFrames();
2776 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 /*
2779 * Traversal of the children
2780 * (perform the transaction for each of them if needed)
2781 */
2782
Robert Carr720e5062018-07-30 17:45:14 -07002783 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002784 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002785 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002787 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788
2789 const uint32_t flags = layer->doTransaction(0);
2790 if (flags & Layer::eVisibleRegion)
2791 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002792
2793 if (flags & Layer::eInputInfoChanged) {
2794 inputChanged = true;
2795 }
Robert Carr2047fae2016-11-28 14:09:09 -08002796 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 }
2798
2799 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002800 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 */
2802
Mathias Agopiane57f2922012-08-09 16:29:12 -07002803 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002804 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002805 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002808 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002809 // The transform hint might have changed for some layers
2810 // (either because a display has changed, or because a layer
2811 // as changed).
2812 //
2813 // Walk through all the layers in currentLayers,
2814 // and update their transform hint.
2815 //
2816 // If a layer is visible only on a single display, then that
2817 // display is used to calculate the hint, otherwise we use the
2818 // default display.
2819 //
2820 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2821 // the hint is set before we acquire a buffer from the surface texture.
2822 //
2823 // NOTE: layer transactions have taken place already, so we use their
2824 // drawing state. However, SurfaceFlinger's own transaction has not
2825 // happened yet, so we must use the current state layer list
2826 // (soon to become the drawing state list).
2827 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002829 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002830 bool first = true;
2831 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002832 // NOTE: we rely on the fact that layers are sorted by
2833 // layerStack first (so we don't have to traverse the list
2834 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002836 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002837 currentlayerStack = layerStack;
2838 // figure out if this layerstack is mirrored
2839 // (more than one display) if so, pick the default display,
2840 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 hintDisplay = nullptr;
2842 for (const auto& [token, display] : mDisplays) {
2843 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2844 if (hintDisplay) {
2845 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002846 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002849 }
2850 }
2851 }
2852 }
Chet Haase91d25932013-04-11 15:24:55 -07002853
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002855 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2856 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002857
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002858 // could be null when this layer is using a layerStack
2859 // that is not visible on any display. Also can occur at
2860 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002861 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002862 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002863
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002865 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 if (hintDisplay) {
2867 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002868 }
Robert Carr2047fae2016-11-28 14:09:09 -08002869
2870 first = false;
2871 });
Mathias Agopian84300952012-11-21 16:02:13 -08002872 }
2873
2874
Mathias Agopian3559b072012-08-15 13:46:03 -07002875 /*
2876 * Perform our own transaction if needed
2877 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878
2879 if (mLayersAdded) {
2880 mLayersAdded = false;
2881 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002882 mVisibleRegionsDirty = true;
2883 }
2884
2885 // some layers might have been removed, so
2886 // we need to update the regions they're exposing.
2887 if (mLayersRemoved) {
2888 mLayersRemoved = false;
2889 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002890 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002891 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 // this layer is not visible anymore
2893 // TODO: we could traverse the tree from front to back and
2894 // compute the actual visible region
2895 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 Region visibleReg;
2897 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002898 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002899 }
Robert Carr2047fae2016-11-28 14:09:09 -08002900 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 }
2902
2903 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002904
Vishnu Nairde19f852018-12-18 16:11:53 -08002905 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002906 updateInputWindows();
2907 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002908 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002909
Riley Andrews03414a12014-07-01 14:22:59 -07002910 updateCursorAsync();
2911}
2912
Robert Carr720e5062018-07-30 17:45:14 -07002913void SurfaceFlinger::updateInputWindows() {
2914 ATRACE_CALL();
2915
Vishnu Nairde19f852018-12-18 16:11:53 -08002916 if (mInputFlinger == nullptr) {
2917 return;
2918 }
2919
Robert Carr720e5062018-07-30 17:45:14 -07002920 Vector<InputWindowInfo> inputHandles;
2921
2922 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2923 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002924 // When calculating the screen bounds we ignore the transparent region since it may
2925 // result in an unwanted offset.
2926 inputHandles.add(layer->fillInputInfo(
2927 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002928 }
2929 });
2930 mInputFlinger->setInputWindows(inputHandles);
2931}
2932
chaviwfbe5d9c2018-12-26 12:23:37 -08002933void SurfaceFlinger::executeInputWindowCommands() {
2934 if (!mInputFlinger) {
2935 return;
2936 }
2937
2938 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2939 if (transferTouchFocusCommand.fromToken != nullptr &&
2940 transferTouchFocusCommand.toToken != nullptr &&
2941 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2942 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2943 transferTouchFocusCommand.toToken);
2944 }
2945 }
2946
2947 mInputWindowCommands.clear();
2948}
2949
Riley Andrews03414a12014-07-01 14:22:59 -07002950void SurfaceFlinger::updateCursorAsync()
2951{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002953 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002954 continue;
2955 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002957 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2958 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002959 }
2960 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002961}
2962
chaviw61626f22018-11-15 16:26:27 -08002963void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2964 if (layer->hasReadyFrame()) {
2965 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2966 if (layer->shouldPresentNow(expectedPresentTime)) {
2967 bool ignored = false;
2968 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2969 }
2970 }
2971 layer->releasePendingBuffer(systemTime());
2972}
2973
Mathias Agopian4fec8732012-06-29 14:12:52 -07002974void SurfaceFlinger::commitTransaction()
2975{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002976 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002977 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 for (const auto& l : mLayersPendingRemoval) {
2979 recordBufferingStats(l->getName().string(),
2980 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002981
2982 // We need to release the HWC layers when the Layer is removed
2983 // from the current state otherwise the HWC layer just continues
2984 // showing at its last configured state until we eventually
2985 // abandon the buffer queue.
2986 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002987 l->destroyHwcLayersForAllDisplays();
2988 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002989 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002990 }
2991 mLayersPendingRemoval.clear();
2992 }
2993
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002994 // If this transaction is part of a window animation then the next frame
2995 // we composite should be considered an animation as well.
2996 mAnimCompositionPending = mAnimTransactionPending;
2997
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002999 // clear the "changed" flags in current state
3000 mCurrentState.colorMatrixChanged = false;
3001
Robert Carr1f0a16a2016-10-24 16:27:39 -07003002 mDrawingState.traverseInZOrder([](Layer* layer) {
3003 layer->commitChildList();
3004 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003005 mTransactionPending = false;
3006 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008}
3009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003010void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3011 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003012 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003014
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015 Region aboveOpaqueLayers;
3016 Region aboveCoveredLayers;
3017 Region dirty;
3018
Mathias Agopian87baae12012-07-31 12:38:26 -07003019 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020
Robert Carr2047fae2016-11-28 14:09:09 -08003021 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003022 // start with the whole surface at its current location
3023 const Layer::State& s(layer->getDrawingState());
3024
Jesse Hall01e29052013-02-19 16:13:35 -08003025 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003027 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003028 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003029
Mathias Agopianab028732010-03-16 16:41:46 -07003030 /*
3031 * opaqueRegion: area of a surface that is fully opaque.
3032 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003034
3035 /*
3036 * visibleRegion: area of a surface that is visible on screen
3037 * and not fully transparent. This is essentially the layer's
3038 * footprint minus the opaque regions above it.
3039 * Areas covered by a translucent surface are considered visible.
3040 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003042
3043 /*
3044 * coveredRegion: area of a surface that is covered by all
3045 * visible regions above it (which includes the translucent areas).
3046 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003048
Jesse Halla8026d22012-09-25 13:25:04 -07003049 /*
3050 * transparentRegion: area of a surface that is hinted to be completely
3051 * transparent. This is only used to tell when the layer has no visible
3052 * non-transparent regions and can be removed from the layer list. It
3053 * does not affect the visibleRegion of this layer or any layers
3054 * beneath it. The hint may not be correct if apps don't respect the
3055 * SurfaceView restrictions (which, sadly, some don't).
3056 */
3057 Region transparentRegion;
3058
Mathias Agopianab028732010-03-16 16:41:46 -07003059
3060 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003061 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003062 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003064
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003066 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003067 if (!visibleRegion.isEmpty()) {
3068 // Remove the transparent area from the visible region
3069 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003070 if (tr.preserveRects()) {
3071 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003072 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003073 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003074 // transformation too complex, can't do the
3075 // transparent region optimization.
3076 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 }
Mathias Agopianab028732010-03-16 16:41:46 -07003078 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079
Mathias Agopianab028732010-03-16 16:41:46 -07003080 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003081 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003082 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003083 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003084 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003085 // the opaque region is the layer's footprint
3086 opaqueRegion = visibleRegion;
3087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 }
3089 }
3090
Robert Carre5f4f692018-01-12 13:12:28 -08003091 if (visibleRegion.isEmpty()) {
3092 layer->clearVisibilityRegions();
3093 return;
3094 }
3095
Mathias Agopianab028732010-03-16 16:41:46 -07003096 // Clip the covered region to the visible region
3097 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3098
3099 // Update aboveCoveredLayers for next (lower) layer
3100 aboveCoveredLayers.orSelf(visibleRegion);
3101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 // subtract the opaque region covered by the layers above us
3103 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104
3105 // compute this layer's dirty region
3106 if (layer->contentDirty) {
3107 // we need to invalidate the whole region
3108 dirty = visibleRegion;
3109 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003110 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 layer->contentDirty = false;
3112 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003113 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003114 * the exposed region consists of two components:
3115 * 1) what's VISIBLE now and was COVERED before
3116 * 2) what's EXPOSED now less what was EXPOSED before
3117 *
3118 * note that (1) is conservative, we start with the whole
3119 * visible region but only keep what used to be covered by
3120 * something -- which mean it may have been exposed.
3121 *
3122 * (2) handles areas that were not covered by anything but got
3123 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003124 */
Mathias Agopianab028732010-03-16 16:41:46 -07003125 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003126 const Region oldVisibleRegion = layer->visibleRegion;
3127 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003128 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3129 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 }
3131 dirty.subtractSelf(aboveOpaqueLayers);
3132
3133 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003134 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135
Mathias Agopianab028732010-03-16 16:41:46 -07003136 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003138
Jesse Halla8026d22012-09-25 13:25:04 -07003139 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 layer->setVisibleRegion(visibleRegion);
3141 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003142 layer->setVisibleNonTransparentRegion(
3143 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003144 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145
Mathias Agopian87baae12012-07-31 12:38:26 -07003146 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147}
3148
Chia-I Wuab0c3192017-08-01 11:29:00 -07003149void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003150 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003151 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3152 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003153 }
3154 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003155}
3156
Dan Stoza6b9454d2014-11-07 16:00:59 -08003157bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003159 ALOGV("handlePageFlip");
3160
Brian Andersond6927fb2016-07-23 23:37:30 -07003161 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopian4fec8732012-06-29 14:12:52 -07003163 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003164 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003165 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003166
3167 // Store the set of layers that need updates. This set must not change as
3168 // buffers are being latched, as this could result in a deadlock.
3169 // Example: Two producers share the same command stream and:
3170 // 1.) Layer 0 is latched
3171 // 2.) Layer 0 gets a new frame
3172 // 2.) Layer 1 gets a new frame
3173 // 3.) Layer 1 is latched.
3174 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3175 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003176 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003177 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003178 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003179 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3180 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003181 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003182 } else {
3183 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003184 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003185 } else {
3186 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003187 }
Robert Carr2047fae2016-11-28 14:09:09 -08003188 });
3189
Lloyd Piquef2c79392018-12-20 16:23:33 -08003190 if (!mLayersWithQueuedFrames.empty()) {
3191 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3192 // writes to Layer current state. See also b/119481871
3193 Mutex::Autolock lock(mStateLock);
3194
3195 for (auto& layer : mLayersWithQueuedFrames) {
3196 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3197 layer->useSurfaceDamage();
3198 invalidateLayerStack(layer, dirty);
3199 if (layer->isBufferLatched()) {
3200 newDataLatched = true;
3201 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003202 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003203 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003204
Alec Mouri86770e52018-09-24 22:40:58 +00003205 // Clear the renderengine fence here...
3206 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3207 // clear instead of sp::clear.
3208 getBE().flushFence = Fence::NO_FENCE;
3209
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003210 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003211
Vishnu Nairde19f852018-12-18 16:11:53 -08003212 if (visibleRegions) {
3213 // Update input window info if the layer receives its first buffer.
3214 updateInputWindows();
3215 }
3216
Dan Stoza6b9454d2014-11-07 16:00:59 -08003217 // If we will need to wake up at some time in the future to deal with a
3218 // queued frame that shouldn't be displayed during this vsync period, wake
3219 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003220 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221 signalLayerUpdate();
3222 }
3223
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003224 // enter boot animation on first buffer latch
3225 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3226 ALOGI("Enter boot animation");
3227 mBootStage = BootStage::BOOTANIMATION;
3228 }
3229
Dan Stoza6b9454d2014-11-07 16:00:59 -08003230 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003231 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232}
3233
Mathias Agopianad456f92011-01-13 17:53:01 -08003234void SurfaceFlinger::invalidateHwcGeometry()
3235{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003236 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003237}
3238
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003239void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003240 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003241 // We only need to actually compose the display if:
3242 // 1) It is being handled by hardware composer, which may need this to
3243 // keep its virtual display state machine in sync, or
3244 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003245 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003246 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003247 return;
3248 }
3249
Dan Stoza9e56aa02015-11-02 13:00:03 -08003250 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003251 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003252
3253 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003254 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255}
3256
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003257bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003260 const Region bounds(display->bounds());
3261 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003262 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003263 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003264 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003265
Peiyong Lind3788632018-09-18 16:01:31 -07003266 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003267 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003268
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003269 // Framebuffer will live in this scope for GPU composition.
3270 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3271
Dan Stoza9e56aa02015-11-02 13:00:03 -08003272 if (hasClientComposition) {
3273 ALOGV("hasClientComposition");
3274
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003275 sp<GraphicBuffer> buf = display->dequeueBuffer();
3276
3277 if (buf == nullptr) {
3278 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3279 "client composition for this frame",
3280 display->getDisplayName().c_str());
3281 return false;
3282 }
3283
3284 // Bind the framebuffer in this scope.
3285 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3286 buf->getNativeBuffer());
3287
3288 if (fbo->getStatus() != NO_ERROR) {
3289 ALOGW("Binding buffer for display [%s] failed with status: %d",
3290 display->getDisplayName().c_str(), fbo->getStatus());
3291 return false;
3292 }
3293
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003294 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003295 if (display->hasWideColorGamut()) {
3296 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003297 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003298 getRenderEngine().setOutputDataSpace(outputDataspace);
3299 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003300 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003301
Lloyd Pique441d5042018-10-18 16:49:51 -07003302 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003303 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003304 getHwComposer()
3305 .hasDisplayCapability(displayId,
3306 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003307
Peiyong Lind3788632018-09-18 16:01:31 -07003308 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003309 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3310 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003311 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003312 }
3313
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003314 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003315
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003316 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003317 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003318 // when using overlays, we assume a fully transparent framebuffer
3319 // NOTE: we could reduce how much we need to clear, for instance
3320 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003321 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003322 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003323 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003324 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003325 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003326 // we're left with the letterbox region
3327 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003328 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003329
3330 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003331 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003332
Mathias Agopianb9494d52012-04-18 02:28:45 -07003333 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003334 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003335 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003336 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003337 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003338 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003339
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003340 const Rect& bounds = display->getBounds();
3341 const Rect& scissor = display->getScissor();
3342 if (scissor != bounds) {
3343 // scissor doesn't match the screen's dimensions, so we
3344 // need to clear everything outside of it and enable
3345 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003346
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003347 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003348 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003349 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003350 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003351
Mathias Agopian85d751c2012-08-29 16:59:24 -07003352 /*
3353 * and then, render the layers targeted at the framebuffer
3354 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003355
Dan Stoza9e56aa02015-11-02 13:00:03 -08003356 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003357 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003358 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003359 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003360 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003361 displayTransform.transform(layer->visibleRegion)));
3362 ALOGV("Layer: %s", layer->getName().string());
3363 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003364 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003365 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003366 case HWC2::Composition::Cursor:
3367 case HWC2::Composition::Device:
3368 case HWC2::Composition::Sideband:
3369 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003370 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003371 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003372 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003373 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003374 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003375 // never clear the very first layer since we're
3376 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003377 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003378 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003379 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003380 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003381 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003382 if (layer->hasColorTransform()) {
3383 mat4 tmpMatrix;
3384 if (applyColorMatrix) {
3385 tmpMatrix = mDrawingState.colorMatrix;
3386 }
3387 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003388 getRenderEngine().setColorTransform(tmpMatrix);
3389 } else {
3390 getRenderEngine().setColorTransform(colorMatrix);
3391 }
David Sodmanc1498e62018-09-12 14:36:26 -07003392 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003393 break;
3394 }
3395 default:
3396 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003397 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003398 } else {
3399 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003400 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003402 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003403
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003404 // Perform some cleanup steps if we used client composition.
3405 if (hasClientComposition) {
3406 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003407 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003408 display->finishBuffer();
3409 // Clear out error flags here so that we don't wait until next
3410 // composition to log.
3411 getRenderEngine().checkErrors();
3412 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003413 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414}
3415
Chia-I Wu28e3a252018-09-07 12:05:02 -07003416void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003417 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003418 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003419}
3420
Dan Stoza7d89d062015-04-30 13:29:25 -07003421status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003422 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003423 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003424 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003425 const sp<Layer>& parent,
3426 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003427{
Dan Stoza7d89d062015-04-30 13:29:25 -07003428 // add this layer to the current state list
3429 {
3430 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003431 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003432 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3433 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003434 return NO_MEMORY;
3435 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003436 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003437 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003438 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003439 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003440 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003441 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003442 parent->addChild(lbc);
3443 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003444
Yiwei Zhang243b3782018-05-15 17:40:04 -07003445 if (gbc != nullptr) {
3446 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3447 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3448 mMaxGraphicBufferProducerListSize,
3449 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3450 mGraphicBufferProducerList.size(),
3451 mMaxGraphicBufferProducerListSize, mNumLayers);
3452 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003453 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003454 }
3455
Mathias Agopian96f08192010-06-02 23:28:45 -07003456 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003457 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003458
Dan Stoza7d89d062015-04-30 13:29:25 -07003459 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003460}
3461
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003462uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003463 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003464}
3465
Mathias Agopian3f844832013-08-07 21:24:32 -07003466uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003467 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003468}
3469
Mathias Agopian3f844832013-08-07 21:24:32 -07003470uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003471 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003472}
3473
3474uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003475 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003476 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003477 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003479 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003480 }
3481 return old;
3482}
3483
Marissa Wall713b63f2018-10-17 15:42:43 -07003484bool SurfaceFlinger::flushTransactionQueues() {
3485 Mutex::Autolock _l(mStateLock);
3486 auto it = mTransactionQueues.begin();
3487 while (it != mTransactionQueues.end()) {
3488 auto& [applyToken, transactionQueue] = *it;
3489
3490 while (!transactionQueue.empty()) {
3491 const auto& [states, displays, flags] = transactionQueue.front();
3492 if (composerStateContainsUnsignaledFences(states)) {
3493 break;
3494 }
chaviw273171b2018-12-26 11:46:30 -08003495 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003496 transactionQueue.pop();
3497 }
3498
3499 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3500 }
3501 return mTransactionQueues.empty();
3502}
3503
chaviwca27f252018-02-06 16:46:39 -08003504bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3505 for (const ComposerState& state : states) {
3506 // Here we need to check that the interface we're given is indeed
3507 // one of our own. A malicious client could give us a nullptr
3508 // IInterface, or one of its own or even one of our own but a
3509 // different type. All these situations would cause us to crash.
3510 if (state.client == nullptr) {
3511 return true;
3512 }
3513
3514 sp<IBinder> binder = IInterface::asBinder(state.client);
3515 if (binder == nullptr) {
3516 return true;
3517 }
3518
3519 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3520 return true;
3521 }
3522 }
3523 return false;
3524}
3525
Marissa Wall713b63f2018-10-17 15:42:43 -07003526bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3527 for (const ComposerState& state : states) {
3528 const layer_state_t& s = state.state;
3529 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3530 continue;
3531 }
3532 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3533 return true;
3534 }
3535 }
3536 return false;
3537}
3538
3539void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3540 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003541 const sp<IBinder>& applyToken,
3542 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003543 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003544 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003545
chaviwca27f252018-02-06 16:46:39 -08003546 if (containsAnyInvalidClientState(states)) {
3547 return;
3548 }
3549
Marissa Wall713b63f2018-10-17 15:42:43 -07003550 // If its TransactionQueue already has a pending TransactionState or if it is pending
3551 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3552 composerStateContainsUnsignaledFences(states)) {
3553 mTransactionQueues[applyToken].emplace(states, displays, flags);
3554 setTransactionFlags(eTransactionNeeded);
3555 return;
3556 }
3557
chaviw273171b2018-12-26 11:46:30 -08003558 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003559}
3560
3561void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003562 const Vector<DisplayState>& displays, uint32_t flags,
3563 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003564 uint32_t transactionFlags = 0;
3565
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003566 if (flags & eAnimation) {
3567 // For window updates that are part of an animation we must wait for
3568 // previous animation "frames" to be handled.
3569 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003570 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003571 if (CC_UNLIKELY(err != NO_ERROR)) {
3572 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003573 // caller after a few seconds.
3574 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3575 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003576 mAnimTransactionPending = false;
3577 break;
3578 }
3579 }
3580 }
3581
chaviwca27f252018-02-06 16:46:39 -08003582 for (const DisplayState& display : displays) {
3583 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003584 }
3585
Marissa Walle2ffb422018-10-12 11:33:52 -07003586 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003587 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003588 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003589 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003590 // If the state doesn't require a traversal and there are callbacks, send them now
3591 if (!(clientStateFlags & eTraversalNeeded)) {
3592 mTransactionCompletedThread.sendCallbacks();
3593 }
3594 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003595
chaviw273171b2018-12-26 11:46:30 -08003596 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3597
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003598 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3599 // anyway. This can be used as a flush mechanism for previous async transactions.
3600 // Empty animation transaction can be used to simulate back-pressure, so also force a
3601 // transaction for empty animation transactions.
3602 if (transactionFlags == 0 &&
3603 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003604 transactionFlags = eTransactionNeeded;
3605 }
3606
Mathias Agopian386aa982011-11-07 21:58:03 -08003607 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003608 if (mInterceptor->isEnabled()) {
3609 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003610 }
Irvel468051e2016-06-13 16:44:44 -07003611
Mathias Agopian386aa982011-11-07 21:58:03 -08003612 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003613 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3614 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003615 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003616
3617 // if this is a synchronous transaction, wait for it to take effect
3618 // before returning.
3619 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003620 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003621 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003622 if (flags & eAnimation) {
3623 mAnimTransactionPending = true;
3624 }
3625 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003626 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3627 if (CC_UNLIKELY(err != NO_ERROR)) {
3628 // just in case something goes wrong in SF, return to the
3629 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3631 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003632 break;
3633 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003634 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635 }
3636}
3637
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003638uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3639 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3640 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003641
Mathias Agopiane57f2922012-08-09 16:29:12 -07003642 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003643 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3644
3645 const uint32_t what = s.what;
3646 if (what & DisplayState::eSurfaceChanged) {
3647 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3648 state.surface = s.surface;
3649 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003650 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003651 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003652 if (what & DisplayState::eLayerStackChanged) {
3653 if (state.layerStack != s.layerStack) {
3654 state.layerStack = s.layerStack;
3655 flags |= eDisplayTransactionNeeded;
3656 }
3657 }
3658 if (what & DisplayState::eDisplayProjectionChanged) {
3659 if (state.orientation != s.orientation) {
3660 state.orientation = s.orientation;
3661 flags |= eDisplayTransactionNeeded;
3662 }
3663 if (state.frame != s.frame) {
3664 state.frame = s.frame;
3665 flags |= eDisplayTransactionNeeded;
3666 }
3667 if (state.viewport != s.viewport) {
3668 state.viewport = s.viewport;
3669 flags |= eDisplayTransactionNeeded;
3670 }
3671 }
3672 if (what & DisplayState::eDisplaySizeChanged) {
3673 if (state.width != s.width) {
3674 state.width = s.width;
3675 flags |= eDisplayTransactionNeeded;
3676 }
3677 if (state.height != s.height) {
3678 state.height = s.height;
3679 flags |= eDisplayTransactionNeeded;
3680 }
3681 }
3682
Mathias Agopiane57f2922012-08-09 16:29:12 -07003683 return flags;
3684}
3685
Robert Carrd4ae7f32018-06-07 16:10:57 -07003686bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3687 IPCThreadState* ipc = IPCThreadState::self();
3688 const int pid = ipc->getCallingPid();
3689 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003690 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003691 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003692 return false;
3693 }
3694 return true;
3695}
3696
chaviwca27f252018-02-06 16:46:39 -08003697uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3698 const layer_state_t& s = composerState.state;
3699 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3700
Mathias Agopian13127d82013-03-05 17:47:11 -08003701 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003702 if (layer == nullptr) {
3703 return 0;
3704 }
3705
chaviw8b3871a2017-11-01 17:41:01 -07003706 uint32_t flags = 0;
3707
Garfield Tan8a3083e2018-12-03 13:21:07 -08003708 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003709 bool geometryAppliesWithResize =
3710 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003711
3712 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3713 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003714 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003715 layer->pushPendingState();
3716 }
3717
chaviw8b3871a2017-11-01 17:41:01 -07003718 if (what & layer_state_t::ePositionChanged) {
3719 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3720 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003721 }
chaviw8b3871a2017-11-01 17:41:01 -07003722 }
3723 if (what & layer_state_t::eLayerChanged) {
3724 // NOTE: index needs to be calculated before we update the state
3725 const auto& p = layer->getParent();
3726 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003727 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003728 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003729 mCurrentState.layersSortedByZ.removeAt(idx);
3730 mCurrentState.layersSortedByZ.add(layer);
3731 // we need traversal (state changed)
3732 // AND transaction (list changed)
3733 flags |= eTransactionNeeded|eTraversalNeeded;
3734 }
chaviw8b3871a2017-11-01 17:41:01 -07003735 } else {
3736 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003737 flags |= eTransactionNeeded|eTraversalNeeded;
3738 }
3739 }
chaviw8b3871a2017-11-01 17:41:01 -07003740 }
3741 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003742 // NOTE: index needs to be calculated before we update the state
3743 const auto& p = layer->getParent();
3744 if (p == nullptr) {
3745 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3746 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3747 mCurrentState.layersSortedByZ.removeAt(idx);
3748 mCurrentState.layersSortedByZ.add(layer);
3749 // we need traversal (state changed)
3750 // AND transaction (list changed)
3751 flags |= eTransactionNeeded|eTraversalNeeded;
3752 }
3753 } else {
3754 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3755 flags |= eTransactionNeeded|eTraversalNeeded;
3756 }
chaviw8b3871a2017-11-01 17:41:01 -07003757 }
3758 }
3759 if (what & layer_state_t::eSizeChanged) {
3760 if (layer->setSize(s.w, s.h)) {
3761 flags |= eTraversalNeeded;
3762 }
3763 }
3764 if (what & layer_state_t::eAlphaChanged) {
3765 if (layer->setAlpha(s.alpha))
3766 flags |= eTraversalNeeded;
3767 }
3768 if (what & layer_state_t::eColorChanged) {
3769 if (layer->setColor(s.color))
3770 flags |= eTraversalNeeded;
3771 }
Peiyong Lind3788632018-09-18 16:01:31 -07003772 if (what & layer_state_t::eColorTransformChanged) {
3773 if (layer->setColorTransform(s.colorTransform)) {
3774 flags |= eTraversalNeeded;
3775 }
3776 }
chaviw8b3871a2017-11-01 17:41:01 -07003777 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003778 // TODO: b/109894387
3779 //
3780 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3781 // rotation. To see the problem observe that if we have a square parent, and a child
3782 // of the same size, then we rotate the child 45 degrees around it's center, the child
3783 // must now be cropped to a non rectangular 8 sided region.
3784 //
3785 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3786 // private API, and the WindowManager only uses rotation in one case, which is on a top
3787 // level layer in which cropping is not an issue.
3788 //
3789 // However given that abuse of rotation matrices could lead to surfaces extending outside
3790 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3791 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3792 // transformations.
3793 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003794 flags |= eTraversalNeeded;
3795 }
3796 if (what & layer_state_t::eTransparentRegionChanged) {
3797 if (layer->setTransparentRegionHint(s.transparentRegion))
3798 flags |= eTraversalNeeded;
3799 }
3800 if (what & layer_state_t::eFlagsChanged) {
3801 if (layer->setFlags(s.flags, s.mask))
3802 flags |= eTraversalNeeded;
3803 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003804 if (what & layer_state_t::eCropChanged_legacy) {
3805 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003806 flags |= eTraversalNeeded;
3807 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003808 if (what & layer_state_t::eCornerRadiusChanged) {
3809 if (layer->setCornerRadius(s.cornerRadius))
3810 flags |= eTraversalNeeded;
3811 }
chaviw8b3871a2017-11-01 17:41:01 -07003812 if (what & layer_state_t::eLayerStackChanged) {
3813 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3814 // We only allow setting layer stacks for top level layers,
3815 // everything else inherits layer stack from its parent.
3816 if (layer->hasParent()) {
3817 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3818 layer->getName().string());
3819 } else if (idx < 0) {
3820 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3821 "that also does not appear in the top level layer list. Something"
3822 " has gone wrong.", layer->getName().string());
3823 } else if (layer->setLayerStack(s.layerStack)) {
3824 mCurrentState.layersSortedByZ.removeAt(idx);
3825 mCurrentState.layersSortedByZ.add(layer);
3826 // we need traversal (state changed)
3827 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003828 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003829 }
3830 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003831 if (what & layer_state_t::eDeferTransaction_legacy) {
3832 if (s.barrierHandle_legacy != nullptr) {
3833 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3834 } else if (s.barrierGbp_legacy != nullptr) {
3835 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003836 if (authenticateSurfaceTextureLocked(gbp)) {
3837 const auto& otherLayer =
3838 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003839 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003840 } else {
3841 ALOGE("Attempt to defer transaction to to an"
3842 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003843 }
3844 }
chaviw8b3871a2017-11-01 17:41:01 -07003845 // We don't trigger a traversal here because if no other state is
3846 // changed, we don't want this to cause any more work
3847 }
3848 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003849 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003850 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003851 if (!hadParent) {
3852 mCurrentState.layersSortedByZ.remove(layer);
3853 }
chaviw8b3871a2017-11-01 17:41:01 -07003854 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003855 }
chaviw8b3871a2017-11-01 17:41:01 -07003856 }
3857 if (what & layer_state_t::eReparentChildren) {
3858 if (layer->reparentChildren(s.reparentHandle)) {
3859 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003860 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003861 }
chaviw8b3871a2017-11-01 17:41:01 -07003862 if (what & layer_state_t::eDetachChildren) {
3863 layer->detachChildren();
3864 }
3865 if (what & layer_state_t::eOverrideScalingModeChanged) {
3866 layer->setOverrideScalingMode(s.overrideScalingMode);
3867 // We don't trigger a traversal here because if no other state is
3868 // changed, we don't want this to cause any more work
3869 }
Marissa Wall61c58622018-07-18 10:12:20 -07003870 if (what & layer_state_t::eTransformChanged) {
3871 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3872 }
3873 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3874 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3875 flags |= eTraversalNeeded;
3876 }
3877 if (what & layer_state_t::eCropChanged) {
3878 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3879 }
Marissa Wall861616d2018-10-22 12:52:23 -07003880 if (what & layer_state_t::eFrameChanged) {
3881 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3882 }
Marissa Wall61c58622018-07-18 10:12:20 -07003883 if (what & layer_state_t::eBufferChanged) {
3884 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3885 }
3886 if (what & layer_state_t::eAcquireFenceChanged) {
3887 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3888 }
3889 if (what & layer_state_t::eDataspaceChanged) {
3890 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3891 }
3892 if (what & layer_state_t::eHdrMetadataChanged) {
3893 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3894 }
3895 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3896 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3897 }
3898 if (what & layer_state_t::eApiChanged) {
3899 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3900 }
3901 if (what & layer_state_t::eSidebandStreamChanged) {
3902 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3903 }
Robert Carr720e5062018-07-30 17:45:14 -07003904 if (what & layer_state_t::eInputInfoChanged) {
3905 layer->setInputInfo(s.inputInfo);
3906 flags |= eTraversalNeeded;
3907 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003908 std::vector<sp<CallbackHandle>> callbackHandles;
3909 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3910 mTransactionCompletedThread.run();
3911 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3912 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3913 }
3914 }
3915 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3916 // Do not put anything that updates layer state or modifies flags after
3917 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003918 return flags;
3919}
3920
chaviw273171b2018-12-26 11:46:30 -08003921uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3922 uint32_t flags = 0;
3923 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3924 flags |= eTraversalNeeded;
3925 }
3926
3927 mInputWindowCommands.merge(inputWindowCommands);
3928 return flags;
3929}
3930
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003931status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003932 const String8& name,
3933 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003934 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003935 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003936 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003937{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003938 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003939 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003940 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003941 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003942 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003943
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003944 status_t result = NO_ERROR;
3945
3946 sp<Layer> layer;
3947
Cody Northropbc755282017-03-31 12:00:08 -06003948 String8 uniqueName = getUniqueLayerName(name);
3949
Mathias Agopian3165cc22012-08-08 19:42:09 -07003950 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003951 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003952 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3953 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003954
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003956 case ISurfaceComposerClient::eFXSurfaceBufferState:
3957 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3958 break;
chaviw13fdc492017-06-27 12:40:18 -07003959 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003960 // check if buffer size is set for color layer.
3961 if (w > 0 || h > 0) {
3962 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3963 int(w), int(h));
3964 return BAD_VALUE;
3965 }
3966
chaviw13fdc492017-06-27 12:40:18 -07003967 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003968 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003969 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003970 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003971 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003972 // check if buffer size is set for container layer.
3973 if (w > 0 || h > 0) {
3974 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3975 int(w), int(h));
3976 return BAD_VALUE;
3977 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003978 result = createContainerLayer(client,
3979 uniqueName, w, h, flags,
3980 handle, &layer);
3981 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003982 default:
3983 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003984 break;
3985 }
3986
Dan Stoza7d89d062015-04-30 13:29:25 -07003987 if (result != NO_ERROR) {
3988 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003990
Chia-I Wuab0c3192017-08-01 11:29:00 -07003991 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3992 // TODO b/64227542
3993 if (windowType == 441731) {
3994 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3995 layer->setPrimaryDisplayOnly();
3996 }
3997
Albert Chaulk479c60c2017-01-27 14:21:34 -05003998 layer->setInfo(windowType, ownerUid);
3999
Robert Carrb89ea9d2018-12-10 13:01:14 -08004000 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4001 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4002 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004003 if (result != NO_ERROR) {
4004 return result;
4005 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004006 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004007
4008 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010}
4011
Cody Northropbc755282017-03-31 12:00:08 -06004012String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4013{
4014 bool matchFound = true;
4015 uint32_t dupeCounter = 0;
4016
4017 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4018 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4019
Dan Stoza436ccf32018-06-21 12:10:12 -07004020 // Grab the state lock since we're accessing mCurrentState
4021 Mutex::Autolock lock(mStateLock);
4022
Cody Northropbc755282017-03-31 12:00:08 -06004023 // Loop over layers until we're sure there is no matching name
4024 while (matchFound) {
4025 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004026 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004027 if (layer->getName() == uniqueName) {
4028 matchFound = true;
4029 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4030 }
4031 });
4032 }
4033
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004034 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4035 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004036
4037 return uniqueName;
4038}
4039
Marissa Wallfd668622018-05-10 10:21:13 -07004040status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4041 uint32_t w, uint32_t h, uint32_t flags,
4042 PixelFormat& format, sp<IBinder>* handle,
4043 sp<IGraphicBufferProducer>* gbp,
4044 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004046 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004047 case PIXEL_FORMAT_TRANSPARENT:
4048 case PIXEL_FORMAT_TRANSLUCENT:
4049 format = PIXEL_FORMAT_RGBA_8888;
4050 break;
4051 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004052 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 break;
4054 }
4055
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004056 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004057 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004058 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004059 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004060 *handle = layer->getHandle();
4061 *gbp = layer->getProducer();
4062 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004063 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004064
Marissa Wallfd668622018-05-10 10:21:13 -07004065 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004066 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067}
4068
Marissa Wall61c58622018-07-18 10:12:20 -07004069status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4070 uint32_t w, uint32_t h, uint32_t flags,
4071 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004072 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004073 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004074 *handle = layer->getHandle();
4075 *outLayer = layer;
4076
4077 return NO_ERROR;
4078}
4079
chaviw13fdc492017-06-27 12:40:18 -07004080status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004081 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004082 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004084 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004085 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004086 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004087}
4088
Robert Carr6b3f6c52018-08-13 13:05:17 -07004089status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4090 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4091 sp<IBinder>* handle, sp<Layer>* outLayer)
4092{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004093 *outLayer =
4094 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004095 *handle = (*outLayer)->getHandle();
4096 return NO_ERROR;
4097}
4098
4099
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004100void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004101 mLayersPendingRemoval.add(layer);
4102 mLayersRemoved = true;
4103 setTransactionFlags(eTransactionNeeded);
4104}
4105
Robert Carr695d5282018-12-18 15:27:58 -08004106void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004107{
Robert Carr2e102c92018-10-23 12:11:15 -07004108 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004109 // If a layer has a parent, we allow it to out-live it's handle
4110 // with the idea that the parent holds a reference and will eventually
4111 // be cleaned up. However no one cleans up the top-level so we do so
4112 // here.
4113 if (layer->getParent() == nullptr) {
4114 mCurrentState.layersSortedByZ.remove(layer);
4115 }
4116 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004117 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004118}
4119
Mathias Agopianb60314a2012-04-10 22:09:54 -07004120// ---------------------------------------------------------------------------
4121
Andy McFadden13a082e2012-08-24 10:16:42 -07004122void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004123 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004124 if (!displayToken) return;
4125
Jesse Hall01e29052013-02-19 16:13:35 -08004126 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004127 Vector<ComposerState> state;
4128 Vector<DisplayState> displays;
4129 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004130 d.what = DisplayState::eDisplayProjectionChanged |
4131 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004132 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004133 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004134 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004135 d.frame.makeInvalid();
4136 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004137 d.width = 0;
4138 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004139 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004140 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004141
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004142 const auto display = getDisplayDevice(displayToken);
4143 if (!display) return;
4144
Dominik Laskowskie9774092018-12-11 10:04:24 -08004145 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004146
Dominik Laskowski075d3172018-05-24 15:50:06 -07004147 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004148 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004149 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004150
Brian Andersond0010582017-03-07 13:20:31 -08004151 // Use phase of 0 since phase is not known.
4152 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004153 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4154 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004155}
4156
4157void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004158 // Async since we may be called from the main thread.
4159 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004160}
4161
Dominik Laskowskie9774092018-12-11 10:04:24 -08004162void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004163 if (display->isVirtual()) {
4164 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004165 return;
4166 }
4167
Dominik Laskowski075d3172018-05-24 15:50:06 -07004168 const auto displayId = display->getId();
4169 LOG_ALWAYS_FATAL_IF(!displayId);
4170
Dominik Laskowski34157762018-10-31 13:07:19 -07004171 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004172
4173 int currentMode = display->getPowerMode();
4174 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004175 return;
4176 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004178 display->setPowerMode(mode);
4179
Lloyd Pique4dccc412018-01-22 17:21:36 -08004180 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004181 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004182 }
4183
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004184 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004185 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004186 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004187 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004188 if (mUseScheduler) {
4189 mScheduler->onScreenAcquired(mAppConnectionHandle);
4190 } else {
4191 mEventThread->onScreenAcquired();
4192 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004193 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004194 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004196 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004197 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004198 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004199
4200 struct sched_param param = {0};
4201 param.sched_priority = 1;
4202 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4203 ALOGW("Couldn't set SCHED_FIFO on display on");
4204 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004205 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004206 // Turn off the display
4207 struct sched_param param = {0};
4208 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4209 ALOGW("Couldn't set SCHED_OTHER on display off");
4210 }
4211
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004212 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004213 if (mUseScheduler) {
4214 mScheduler->disableHardwareVsync(true);
4215 } else {
4216 disableHardwareVsync(true); // also cancels any in-progress resync
4217 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004218 if (mUseScheduler) {
4219 mScheduler->onScreenReleased(mAppConnectionHandle);
4220 } else {
4221 mEventThread->onScreenReleased();
4222 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004223 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004224
Dominik Laskowski075d3172018-05-24 15:50:06 -07004225 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004226 mVisibleRegionsDirty = true;
4227 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004228 } else if (mode == HWC_POWER_MODE_DOZE ||
4229 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004230 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004231 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004232 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004233 if (mUseScheduler) {
4234 mScheduler->onScreenAcquired(mAppConnectionHandle);
4235 } else {
4236 mEventThread->onScreenAcquired();
4237 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004238 resyncToHardwareVsync(true);
4239 }
4240 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4241 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004242 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004243 if (mUseScheduler) {
4244 mScheduler->disableHardwareVsync(true);
4245 } else {
4246 disableHardwareVsync(true); // also cancels any in-progress resync
4247 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004248 if (mUseScheduler) {
4249 mScheduler->onScreenReleased(mAppConnectionHandle);
4250 } else {
4251 mEventThread->onScreenReleased();
4252 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004253 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004255 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004256 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004257 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004258 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004259
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004260 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004261 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004262 }
4263
Dominik Laskowski34157762018-10-31 13:07:19 -07004264 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004265}
4266
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004267void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004268 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004269 const auto display = getDisplayDevice(displayToken);
4270 if (!display) {
4271 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4272 displayToken.get());
4273 } else if (display->isVirtual()) {
4274 ALOGW("Attempt to set power mode %d for virtual display", mode);
4275 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004276 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004277 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004278 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004279}
4280
4281// ---------------------------------------------------------------------------
4282
Lloyd Pique755e3192018-01-31 16:46:15 -08004283status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4284 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004285 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004286
Mathias Agopianbd115332013-04-18 16:41:04 -07004287 IPCThreadState* ipc = IPCThreadState::self();
4288 const int pid = ipc->getCallingPid();
4289 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004290
Mathias Agopianbd115332013-04-18 16:41:04 -07004291 if ((uid != AID_SHELL) &&
4292 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004293 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4294 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004295 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004296 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004297 // (this would indicate SF is stuck, but we want to be able to
4298 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004299 status_t err = mStateLock.timedLock(s2ns(1));
4300 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004301 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004302 StringAppendF(&result,
4303 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4304 "(no locks held)\n",
4305 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004306 }
4307
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308 bool dumpAll = true;
4309 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004311
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004312 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004313 if ((index < numArgs) &&
4314 (args[index] == String16("--list"))) {
4315 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004316 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004317 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004318 }
4319
4320 if ((index < numArgs) &&
4321 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004322 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004323 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004324 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004325 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004326
4327 if ((index < numArgs) &&
4328 (args[index] == String16("--latency-clear"))) {
4329 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004330 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004331 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004332 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004333
4334 if ((index < numArgs) &&
4335 (args[index] == String16("--dispsync"))) {
4336 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004337 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004338 dumpAll = false;
4339 }
Dan Stozab90cf072015-03-05 11:05:59 -08004340
4341 if ((index < numArgs) &&
4342 (args[index] == String16("--static-screen"))) {
4343 index++;
4344 dumpStaticScreenStats(result);
4345 dumpAll = false;
4346 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004347
4348 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004349 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004350 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004351 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004352 dumpAll = false;
4353 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004354
4355 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4356 index++;
4357 dumpWideColorInfo(result);
4358 dumpAll = false;
4359 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004360
4361 if ((index < numArgs) &&
4362 (args[index] == String16("--enable-layer-stats"))) {
4363 index++;
4364 mLayerStats.enable();
4365 dumpAll = false;
4366 }
4367
4368 if ((index < numArgs) &&
4369 (args[index] == String16("--disable-layer-stats"))) {
4370 index++;
4371 mLayerStats.disable();
4372 dumpAll = false;
4373 }
4374
4375 if ((index < numArgs) &&
4376 (args[index] == String16("--clear-layer-stats"))) {
4377 index++;
4378 mLayerStats.clear();
4379 dumpAll = false;
4380 }
4381
4382 if ((index < numArgs) &&
4383 (args[index] == String16("--dump-layer-stats"))) {
4384 index++;
4385 mLayerStats.dump(result);
4386 dumpAll = false;
4387 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004388
4389 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004390 (args[index] == String16("--frame-composition"))) {
4391 index++;
4392 dumpFrameCompositionInfo(result);
4393 dumpAll = false;
4394 }
4395
4396 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004397 (args[index] == String16("--display-identification"))) {
4398 index++;
4399 dumpDisplayIdentificationData(result);
4400 dumpAll = false;
4401 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004402
4403 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4404 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004405 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004406 dumpAll = false;
4407 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004408 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004409
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004410 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004411 if (asProto) {
4412 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4413 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4414 } else {
4415 dumpAllLocked(args, index, result);
4416 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004417 }
4418
Mathias Agopian9795c422009-08-26 16:36:26 -07004419 if (locked) {
4420 mStateLock.unlock();
4421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004422 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 return NO_ERROR;
4425}
4426
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4428 std::string& result) const {
4429 mCurrentState.traverseInZOrder(
4430 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004431}
4432
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004433void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004434 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435 String8 name;
4436 if (index < args.size()) {
4437 name = String8(args[index]);
4438 index++;
4439 }
4440
Dominik Laskowski075d3172018-05-24 15:50:06 -07004441 if (const auto displayId = getInternalDisplayId();
4442 displayId && getHwComposer().isConnected(*displayId)) {
4443 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004444 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004446 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004447
4448 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004449 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004450 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004451 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004452 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004453 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004454 }
Robert Carr2047fae2016-11-28 14:09:09 -08004455 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 }
4457}
4458
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004459void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004461 String8 name;
4462 if (index < args.size()) {
4463 name = String8(args[index]);
4464 index++;
4465 }
4466
Robert Carr2047fae2016-11-28 14:09:09 -08004467 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004468 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004469 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004470 }
Robert Carr2047fae2016-11-28 14:09:09 -08004471 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004472
Svetoslavd85084b2014-03-20 10:28:31 -07004473 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004474}
4475
Jamie Gennis6547ff42013-07-16 20:12:42 -07004476// This should only be called from the main thread. Otherwise it would need
4477// the lock and should use mCurrentState rather than mDrawingState.
4478void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004479 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004480 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004481 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004482
4483 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4484}
4485
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004487 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004488
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004489 if (isLayerTripleBufferingDisabled())
4490 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004491
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4493 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4494 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4495 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4496 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4497 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004498 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004499}
4500
Yiwei Zhang5434a782018-12-05 18:06:32 -08004501void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4502 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004503 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4504 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004505 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004506 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004507 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004508 }
David Sodman4a36e932017-11-07 14:29:47 -08004509 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004510 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004511 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004512 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4513 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004514}
4515
Dan Stozae77c7662016-05-13 11:37:28 -07004516void SurfaceFlinger::recordBufferingStats(const char* layerName,
4517 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004518 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4519 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004520 for (const auto& segment : history) {
4521 if (!segment.usedThirdBuffer) {
4522 stats.twoBufferTime += segment.totalTime;
4523 }
4524 if (segment.occupancyAverage < 1.0f) {
4525 stats.doubleBufferedTime += segment.totalTime;
4526 } else if (segment.occupancyAverage < 2.0f) {
4527 stats.tripleBufferedTime += segment.totalTime;
4528 }
4529 ++stats.numSegments;
4530 stats.totalTime += segment.totalTime;
4531 }
4532}
4533
Yiwei Zhang5434a782018-12-05 18:06:32 -08004534void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4535 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004536
4537 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4538 const size_t count = currentLayers.size();
4539 for (size_t i=0 ; i<count ; i++) {
4540 currentLayers[i]->dumpFrameEvents(result);
4541 }
4542}
4543
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004545 result.append("Buffering stats:\n");
4546 result.append(" [Layer name] <Active time> <Two buffer> "
4547 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004548 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004549 typedef std::tuple<std::string, float, float, float> BufferTuple;
4550 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004551 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004552 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004553 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004554 if (stats.numSegments == 0) {
4555 continue;
4556 }
4557 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4558 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4559 stats.totalTime;
4560 float doubleBufferRatio = static_cast<float>(
4561 stats.doubleBufferedTime) / stats.totalTime;
4562 float tripleBufferRatio = static_cast<float>(
4563 stats.tripleBufferedTime) / stats.totalTime;
4564 sorted.insert({activeTime, {name, twoBufferRatio,
4565 doubleBufferRatio, tripleBufferRatio}});
4566 }
4567 for (const auto& sortedPair : sorted) {
4568 float activeTime = sortedPair.first;
4569 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004570 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4571 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004572 }
4573 result.append("\n");
4574}
4575
Yiwei Zhang5434a782018-12-05 18:06:32 -08004576void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004577 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004578 const auto displayId = display->getId();
4579 if (!displayId) {
4580 continue;
4581 }
4582 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004584 continue;
4585 }
4586
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587 StringAppendF(&result,
4588 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4589 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004590 uint8_t port;
4591 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004592 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004593 result.append("no identification data\n");
4594 continue;
4595 }
4596
4597 if (!isEdid(data)) {
4598 result.append("unknown identification data: ");
4599 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004600 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 }
4602 result.append("\n");
4603 continue;
4604 }
4605
4606 const auto edid = parseEdid(data);
4607 if (!edid) {
4608 result.append("invalid EDID: ");
4609 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004611 }
4612 result.append("\n");
4613 continue;
4614 }
4615
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004617 result.append(edid->displayName.data(), edid->displayName.length());
4618 result.append("\"\n");
4619 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004620}
4621
Yiwei Zhang5434a782018-12-05 18:06:32 -08004622void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4623 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4624 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4625 StringAppendF(&result, "DisplayColorSetting: %s\n",
4626 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004627
4628 // TODO: print out if wide-color mode is active or not
4629
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004630 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004631 const auto displayId = display->getId();
4632 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004633 continue;
4634 }
4635
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004637 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004638 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004640 }
4641
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004642 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result, " Current color mode: %s (%d)\n",
4644 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004645 }
4646 result.append("\n");
4647}
4648
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004650 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004651 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4652 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004653 continue;
4654 }
4655
Dominik Laskowski05275f12018-11-01 15:03:24 -07004656 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4658 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004659 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 compositionInfo.dump(result, nullptr);
4661 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004662 }
4663 }
David Sodman7e4ae112018-02-09 15:02:28 -08004664}
4665
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004666LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004667 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004668 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4669 const State& state = useDrawing ? mDrawingState : mCurrentState;
4670 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004671 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004672 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004673 });
4674
4675 return layersProto;
4676}
4677
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004678LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004679 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004680
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004681 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004682 resolution->set_w(display.getWidth());
4683 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004684
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004685 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4686 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4687 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004688
Dominik Laskowski075d3172018-05-24 15:50:06 -07004689 const auto displayId = display.getId();
4690 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004691 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004692 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004693 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004695 }
4696 });
4697
4698 return layersProto;
4699}
4700
Mathias Agopian74d211a2013-04-22 16:55:35 +02004701void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 bool colorize = false;
4704 if (index < args.size()
4705 && (args[index] == String16("--color"))) {
4706 colorize = true;
4707 index++;
4708 }
4709
4710 Colorizer colorizer(colorize);
4711
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004712 // figure out if we're stuck somewhere
4713 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4716
4717 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004718 * Dump library configuration.
4719 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720
4721 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004722 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004724 appendSfConfigString(result);
4725 appendUiConfigString(result);
4726 appendGuiConfigString(result);
4727 result.append("\n");
4728
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004729 result.append("\nDisplay identification data:\n");
4730 dumpDisplayIdentificationData(result);
4731
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004732 result.append("\nWide-Color information:\n");
4733 dumpWideColorInfo(result);
4734
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004735 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004736 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004737 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004738 result.append(SyncFeatures::getInstance().toString());
4739 result.append("\n");
4740
Andy McFadden41d67d72014-04-25 16:58:34 -07004741 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004742 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004743 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004744
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004745 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4746 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004747 if (const auto displayId = getInternalDisplayId();
4748 displayId && getHwComposer().isConnected(*displayId)) {
4749 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004750 StringAppendF(&result,
4751 "Display %s: app phase %" PRId64 " ns, "
4752 "sf phase %" PRId64 " ns, "
4753 "early app phase %" PRId64 " ns, "
4754 "early sf phase %" PRId64 " ns, "
4755 "early app gl phase %" PRId64 " ns, "
4756 "early sf gl phase %" PRId64 " ns, "
4757 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4758 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4759 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4760 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004761 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004762 result.append("\n");
4763
Dan Stozab90cf072015-03-05 11:05:59 -08004764 // Dump static screen stats
4765 result.append("\n");
4766 dumpStaticScreenStats(result);
4767 result.append("\n");
4768
Yiwei Zhang5434a782018-12-05 18:06:32 -08004769 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004770
Dan Stozae77c7662016-05-13 11:37:28 -07004771 dumpBufferingStats(result);
4772
Andy McFadden4803b742012-09-24 19:07:20 -07004773 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774 * Dump the visible layer list
4775 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4778 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4779 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004780 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004781
Chia-I Wu2f884132018-09-13 15:17:58 -07004782 {
4783 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4784 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004786 result.append("\n");
4787 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004788
David Sodman7e4ae112018-02-09 15:02:28 -08004789 result.append("\nFrame-Composition information:\n");
4790 dumpFrameCompositionInfo(result);
4791 result.append("\n");
4792
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004793 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004794 * Dump Display state
4795 */
4796
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004797 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004799 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004800 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004801 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004802 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004803 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004804
4805 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806 * Dump SurfaceFlinger global state
4807 */
4808
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004810 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004811 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004812
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004813 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814
Dominik Laskowski075d3172018-05-24 15:50:06 -07004815 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004816 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4818 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004819 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004820 StringAppendF(&result,
4821 " transaction-flags : %08x\n"
4822 " gpu_to_cpu_unsupported : %d\n",
4823 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004824
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 if (const auto displayId = getInternalDisplayId();
4826 displayId && getHwComposer().isConnected(*displayId)) {
4827 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 StringAppendF(&result,
4829 " refresh-rate : %f fps\n"
4830 " x-dpi : %f\n"
4831 " y-dpi : %f\n",
4832 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4833 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004834 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839 /*
4840 * VSYNC state
4841 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004842 if (mUseScheduler) {
4843 mScheduler->dump(mAppConnectionHandle, result);
4844 } else {
4845 mEventThread->dump(result);
4846 }
Dan Stozae22aec72016-08-01 13:20:59 -07004847 result.append("\n");
4848
4849 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004850 * Tracing state
4851 */
4852 mTracing.dump(result);
4853 result.append("\n");
4854
4855 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004856 * HWC layer minidump
4857 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004858 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004859 const auto displayId = display->getId();
4860 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004861 continue;
4862 }
4863
Yiwei Zhang5434a782018-12-05 18:06:32 -08004864 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004865 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004866 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004867 result.append("\n");
4868 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004869
4870 /*
4871 * Dump HWComposer state
4872 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004873 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004874 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004875 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004876 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004878 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879
4880 /*
4881 * Dump gralloc state
4882 */
4883 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4884 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004885
4886 /*
4887 * Dump VrFlinger state if in use.
4888 */
4889 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4890 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004891 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004892 result.append("\n");
4893 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004894}
4895
Dominik Laskowski075d3172018-05-24 15:50:06 -07004896const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004897 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004898 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004899 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004900 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004901 }
4902 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004903
Dominik Laskowski34157762018-10-31 13:07:19 -07004904 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004905 static const Vector<sp<Layer>> empty;
4906 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004907}
4908
Keun young Park63f165f2012-08-31 10:53:36 -07004909bool SurfaceFlinger::startDdmConnection()
4910{
4911 void* libddmconnection_dso =
4912 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4913 if (!libddmconnection_dso) {
4914 return false;
4915 }
4916 void (*DdmConnection_start)(const char* name);
4917 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004918 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004919 if (!DdmConnection_start) {
4920 dlclose(libddmconnection_dso);
4921 return false;
4922 }
4923 (*DdmConnection_start)(getServiceName());
4924 return true;
4925}
4926
Chia-I Wu28f320b2018-05-03 11:02:56 -07004927void SurfaceFlinger::updateColorMatrixLocked() {
4928 mat4 colorMatrix;
4929 if (mGlobalSaturationFactor != 1.0f) {
4930 // Rec.709 luma coefficients
4931 float3 luminance{0.213f, 0.715f, 0.072f};
4932 luminance *= 1.0f - mGlobalSaturationFactor;
4933 mat4 saturationMatrix = mat4(
4934 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4935 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4936 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4937 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4938 );
4939 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4940 } else {
4941 colorMatrix = mClientColorMatrix * mDaltonizer();
4942 }
4943
4944 if (mCurrentState.colorMatrix != colorMatrix) {
4945 mCurrentState.colorMatrix = colorMatrix;
4946 mCurrentState.colorMatrixChanged = true;
4947 setTransactionFlags(eTransactionNeeded);
4948 }
4949}
4950
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004951status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952#pragma clang diagnostic push
4953#pragma clang diagnostic error "-Wswitch-enum"
4954 switch (static_cast<ISurfaceComposerTag>(code)) {
4955 // These methods should at minimum make sure that the client requested
4956 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004957 case BOOT_FINISHED:
4958 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959 case CREATE_DISPLAY:
4960 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004961 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004962 case GET_ACTIVE_COLOR_MODE:
4963 case GET_ANIMATION_FRAME_STATS:
4964 case GET_HDR_CAPABILITIES:
4965 case SET_ACTIVE_CONFIG:
4966 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004967 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004968 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004969 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004970 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4971 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004972 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4973 IPCThreadState* ipc = IPCThreadState::self();
4974 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4975 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004976 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 }
Robert Carr1db73f62016-12-21 12:58:51 -08004978 return OK;
4979 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004980 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004981 IPCThreadState* ipc = IPCThreadState::self();
4982 const int pid = ipc->getCallingPid();
4983 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004984 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4985 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004986 return PERMISSION_DENIED;
4987 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004990 // Used by apps to hook Choreographer to SurfaceFlinger.
4991 case CREATE_DISPLAY_EVENT_CONNECTION:
4992 // The following calls are currently used by clients that do not
4993 // request necessary permissions. However, they do not expose any secret
4994 // information, so it is OK to pass them.
4995 case AUTHENTICATE_SURFACE:
4996 case GET_ACTIVE_CONFIG:
4997 case GET_BUILT_IN_DISPLAY:
4998 case GET_DISPLAY_COLOR_MODES:
4999 case GET_DISPLAY_CONFIGS:
5000 case GET_DISPLAY_STATS:
5001 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5002 // Calling setTransactionState is safe, because you need to have been
5003 // granted a reference to Client* and Handle* to do anything with it.
5004 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005005 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005006 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07005007 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008 return OK;
5009 }
5010 case CAPTURE_LAYERS:
5011 case CAPTURE_SCREEN: {
5012 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005013 IPCThreadState* ipc = IPCThreadState::self();
5014 const int pid = ipc->getCallingPid();
5015 const int uid = ipc->getCallingUid();
5016 if ((uid != AID_GRAPHICS) &&
5017 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5018 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5019 return PERMISSION_DENIED;
5020 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005021 return OK;
5022 }
5023 // The following codes are deprecated and should never be allowed to access SF.
5024 case CONNECT_DISPLAY_UNUSED:
5025 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5026 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5027 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005028 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030
5031 // These codes are used for the IBinder protocol to either interrogate the recipient
5032 // side of the transaction for its canonical interface descriptor or to dump its state.
5033 // We let them pass by default.
5034 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5035 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5036 code == IBinder::SYSPROPS_TRANSACTION) {
5037 return OK;
5038 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005039 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005040 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005041 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005042 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5043 return OK;
5044 }
5045 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5046 return PERMISSION_DENIED;
5047#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005048}
5049
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5051 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005052 status_t credentialCheck = CheckTransactCodeCredentials(code);
5053 if (credentialCheck != OK) {
5054 return credentialCheck;
5055 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005057 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5058 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005059 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005060 IPCThreadState* ipc = IPCThreadState::self();
5061 const int uid = ipc->getCallingUid();
5062 if (CC_UNLIKELY(uid != AID_SYSTEM
5063 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005064 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005065 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005066 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005067 return PERMISSION_DENIED;
5068 }
5069 int n;
5070 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005071 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005072 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005073 return NO_ERROR;
5074 case 1002: // SHOW_UPDATES
5075 n = data.readInt32();
5076 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005077 invalidateHwcGeometry();
5078 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005080 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005081 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005082 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005083 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005084 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005085 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005086 setTransactionFlags(
5087 eTransactionNeeded|
5088 eDisplayTransactionNeeded|
5089 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005090 return NO_ERROR;
5091 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005092 case 1006:{ // send empty update
5093 signalRefresh();
5094 return NO_ERROR;
5095 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005096 case 1008: // toggle use of hw composer
5097 n = data.readInt32();
5098 mDebugDisableHWC = n ? 1 : 0;
5099 invalidateHwcGeometry();
5100 repaintEverything();
5101 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005102 case 1009: // toggle use of transform hint
5103 n = data.readInt32();
5104 mDebugDisableTransformHint = n ? 1 : 0;
5105 invalidateHwcGeometry();
5106 repaintEverything();
5107 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005108 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005109 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005110 reply->writeInt32(0);
5111 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005112 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005113 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005114 return NO_ERROR;
5115 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005116 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005117 if (!display) {
5118 return NAME_NOT_FOUND;
5119 }
5120
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005121 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005122 return NO_ERROR;
5123 }
5124 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005125 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005126 // daltonize
5127 n = data.readInt32();
5128 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005129 case 1:
5130 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5131 break;
5132 case 2:
5133 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5134 break;
5135 case 3:
5136 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5137 break;
5138 default:
5139 mDaltonizer.setType(ColorBlindnessType::None);
5140 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005141 }
5142 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005143 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005144 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005145 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005146 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005147
5148 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005149 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005150 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005151 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005152 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005153 // apply a color matrix
5154 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005155 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005156 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005157 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005158 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005159 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005160 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005161 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005162 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005163 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005164 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005165
5166 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5167 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005168 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005169 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5170 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5171 }
5172
Chia-I Wu28f320b2018-05-03 11:02:56 -07005173 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005174 return NO_ERROR;
5175 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005176 // This is an experimental interface
5177 // Needs to be shifted to proper binder interface when we productize
5178 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005179 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005180 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005181 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005182 return NO_ERROR;
5183 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005184 case 1017: {
5185 n = data.readInt32();
5186 mForceFullDamage = static_cast<bool>(n);
5187 return NO_ERROR;
5188 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005189 case 1018: { // Modify Choreographer's phase offset
5190 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005191 if (mUseScheduler) {
5192 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5193 } else {
5194 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5195 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005196 return NO_ERROR;
5197 }
5198 case 1019: { // Modify SurfaceFlinger's phase offset
5199 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005200 if (mUseScheduler) {
5201 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5202 } else {
5203 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5204 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005205 return NO_ERROR;
5206 }
Irvel468051e2016-06-13 16:44:44 -07005207 case 1020: { // Layer updates interceptor
5208 n = data.readInt32();
5209 if (n) {
5210 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005211 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005212 }
5213 else{
5214 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005215 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005216 }
5217 return NO_ERROR;
5218 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005219 case 1021: { // Disable HWC virtual displays
5220 n = data.readInt32();
5221 mUseHwcVirtualDisplays = !n;
5222 return NO_ERROR;
5223 }
Romain Guy0147a172017-06-01 13:53:56 -07005224 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005225 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005227
Chia-I Wu28f320b2018-05-03 11:02:56 -07005228 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005229 return NO_ERROR;
5230 }
Romain Guy54f154a2017-10-24 21:40:32 +01005231 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005232 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005233 invalidateHwcGeometry();
5234 repaintEverything();
5235 return NO_ERROR;
5236 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005237 // Deprecate, use 1030 to check whether the device is color managed.
5238 case 1024: {
5239 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005240 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005241 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005242 n = data.readInt32();
5243 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005244 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005245 mTracing.enable();
5246 doTracing("tracing.enable");
5247 reply->writeInt32(NO_ERROR);
5248 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005249 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005250 status_t err = mTracing.disable();
5251 reply->writeInt32(err);
5252 }
5253 return NO_ERROR;
5254 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005255 case 1026: { // Get layer tracing status
5256 reply->writeBool(mTracing.isEnabled());
5257 return NO_ERROR;
5258 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005259 // Is a DisplayColorSetting supported?
5260 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005261 const auto display = getDefaultDisplayDevice();
5262 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005263 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005264 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005265
5266 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5267 switch (setting) {
5268 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005269 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005270 break;
5271 case DisplayColorSetting::UNMANAGED:
5272 reply->writeBool(true);
5273 break;
5274 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005275 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005276 break;
5277 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005278 reply->writeBool(
5279 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005280 break;
5281 }
5282 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005283 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005284 // Is VrFlinger active?
5285 case 1028: {
5286 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005287 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005288 return NO_ERROR;
5289 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005290 // Is device color managed?
5291 case 1030: {
5292 reply->writeBool(useColorManagement);
5293 return NO_ERROR;
5294 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005295 // Override default composition data space
5296 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5297 // && adb shell stop zygote && adb shell start zygote
5298 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5299 // adb shell stop zygote && adb shell start zygote
5300 case 1031: {
5301 Mutex::Autolock _l(mStateLock);
5302 n = data.readInt32();
5303 if (n) {
5304 n = data.readInt32();
5305 if (n) {
5306 Dataspace dataspace = static_cast<Dataspace>(n);
5307 if (!validateCompositionDataspace(dataspace)) {
5308 return BAD_VALUE;
5309 }
5310 mDefaultCompositionDataspace = dataspace;
5311 }
5312 n = data.readInt32();
5313 if (n) {
5314 Dataspace dataspace = static_cast<Dataspace>(n);
5315 if (!validateCompositionDataspace(dataspace)) {
5316 return BAD_VALUE;
5317 }
5318 mWideColorGamutCompositionDataspace = dataspace;
5319 }
5320 } else {
5321 // restore composition data space.
5322 mDefaultCompositionDataspace = defaultCompositionDataspace;
5323 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5324 }
5325 return NO_ERROR;
5326 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005327 }
5328 }
5329 return err;
5330}
5331
Steven Thomas6d8110b2017-08-31 18:24:21 -07005332void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005333 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005334 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005335}
5336
Ana Krulec7d1d6832018-12-27 11:10:09 -08005337void SurfaceFlinger::repaintEverythingForHWC() {
5338 mRepaintEverything = true;
5339 mEventQueue->invalidateForHWC();
5340}
5341
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005342// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5343class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005344public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005345 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5346 ~WindowDisconnector() {
5347 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005348 }
5349
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005350private:
5351 ANativeWindow* mWindow;
5352 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005353};
5354
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005355status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005356 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5357 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005358 uint32_t reqWidth, uint32_t reqHeight,
5359 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005360 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005361 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005362
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005363 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005364
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005365 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5366
Chia-I Wu20261cb2018-08-23 12:55:44 -07005367 sp<DisplayDevice> display;
5368 {
5369 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005370
Chia-I Wu20261cb2018-08-23 12:55:44 -07005371 display = getDisplayDeviceLocked(displayToken);
5372 if (!display) return BAD_VALUE;
5373
Chia-I Wucb023152018-08-28 12:57:23 -07005374 // set the requested width/height to the logical display viewport size
5375 // by default
5376 if (reqWidth == 0 || reqHeight == 0) {
5377 reqWidth = uint32_t(display->getViewport().width());
5378 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005379 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005380 }
5381
Peiyong Lin0e003c92018-09-17 11:09:51 -07005382 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5383 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005384
5385 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005386 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005387 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5388 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005389}
5390
5391status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005392 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5393 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005394 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005395 ATRACE_CALL();
5396
5397 class LayerRenderArea : public RenderArea {
5398 public:
Robert Carr578038f2018-03-09 12:25:24 -08005399 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005400 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5401 bool childrenOnly)
5402 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005403 mLayer(layer),
5404 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005405 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005406 mFlinger(flinger),
5407 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005408 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005409 Rect getBounds() const override {
5410 const Layer::State& layerState(mLayer->getDrawingState());
5411 return mLayer->getBufferSize(layerState);
5412 }
Marissa Wall61c58622018-07-18 10:12:20 -07005413 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005414 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005415 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005416 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005417 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005418 }
chaviwa76b2712017-09-20 12:02:26 -07005419 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005420 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005421 Rect getSourceCrop() const override {
5422 if (mCrop.isEmpty()) {
5423 return getBounds();
5424 } else {
5425 return mCrop;
5426 }
5427 }
Robert Carr578038f2018-03-09 12:25:24 -08005428 class ReparentForDrawing {
5429 public:
5430 const sp<Layer>& oldParent;
5431 const sp<Layer>& newParent;
5432
5433 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5434 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005435 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005436 }
Robert Carr15eae092018-03-23 13:43:53 -07005437 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005438 };
5439
5440 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005441 const Rect sourceCrop = getSourceCrop();
5442 // no need to check rotation because there is none
5443 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5444 sourceCrop.height() != getReqHeight();
5445
Robert Carr578038f2018-03-09 12:25:24 -08005446 if (!mChildrenOnly) {
5447 mTransform = mLayer->getTransform().inverse();
5448 drawLayers();
5449 } else {
5450 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005451 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005452 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5453 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005454
5455 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5456 drawLayers();
5457 }
5458 }
chaviwa76b2712017-09-20 12:02:26 -07005459
chaviwa76b2712017-09-20 12:02:26 -07005460 private:
chaviw7206d492017-11-10 16:16:12 -08005461 const sp<Layer> mLayer;
5462 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005463
5464 // In the "childrenOnly" case we reparent the children to a screenshot
5465 // layer which has no properties set and which does not draw.
5466 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005467 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005468 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005469
5470 SurfaceFlinger* mFlinger;
5471 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005472 };
5473
5474 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5475 auto parent = layerHandle->owner.promote();
5476
Robert Carr2e102c92018-10-23 12:11:15 -07005477 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005478 ALOGE("captureLayers called with a removed parent");
5479 return NAME_NOT_FOUND;
5480 }
5481
Robert Carr578038f2018-03-09 12:25:24 -08005482 const int uid = IPCThreadState::self()->getCallingUid();
5483 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005484 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005485 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5486 return PERMISSION_DENIED;
5487 }
5488
chaviw7206d492017-11-10 16:16:12 -08005489 Rect crop(sourceCrop);
5490 if (sourceCrop.width() <= 0) {
5491 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005492 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005493 }
5494
5495 if (sourceCrop.height() <= 0) {
5496 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005497 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005498 }
5499
5500 int32_t reqWidth = crop.width() * frameScale;
5501 int32_t reqHeight = crop.height() * frameScale;
5502
Chia-I Wu20261cb2018-08-23 12:55:44 -07005503 // really small crop or frameScale
5504 if (reqWidth <= 0) {
5505 reqWidth = 1;
5506 }
5507 if (reqHeight <= 0) {
5508 reqHeight = 1;
5509 }
5510
Peiyong Lin0e003c92018-09-17 11:09:51 -07005511 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005512
Robert Carr578038f2018-03-09 12:25:24 -08005513 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005514 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5515 if (!layer->isVisible()) {
5516 return;
Robert Carr578038f2018-03-09 12:25:24 -08005517 } else if (childrenOnly && layer == parent.get()) {
5518 return;
chaviwa76b2712017-09-20 12:02:26 -07005519 }
5520 visitor(layer);
5521 });
5522 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005523 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005524}
5525
5526status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5527 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005528 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005529 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005530 bool useIdentityTransform) {
5531 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005532
Peiyong Lin0e003c92018-09-17 11:09:51 -07005533 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005534 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5535 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005536 *outBuffer =
5537 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5538 static_cast<android_pixel_format>(reqPixelFormat), 1,
5539 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005540
5541 // This mutex protects syncFd and captureResult for communication of the return values from the
5542 // main thread back to this Binder thread
5543 std::mutex captureMutex;
5544 std::condition_variable captureCondition;
5545 std::unique_lock<std::mutex> captureLock(captureMutex);
5546 int syncFd = -1;
5547 std::optional<status_t> captureResult;
5548
Robert Carr03480e22018-01-04 16:02:06 -08005549 const int uid = IPCThreadState::self()->getCallingUid();
5550 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5551
Dominik Laskowski8c001672018-05-30 16:52:06 -07005552 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005553 // If there is a refresh pending, bug out early and tell the binder thread to try again
5554 // after the refresh.
5555 if (mRefreshPending) {
5556 ATRACE_NAME("Skipping screenshot for now");
5557 std::unique_lock<std::mutex> captureLock(captureMutex);
5558 captureResult = std::make_optional<status_t>(EAGAIN);
5559 captureCondition.notify_one();
5560 return;
5561 }
5562
5563 status_t result = NO_ERROR;
5564 int fd = -1;
5565 {
5566 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005567 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005568 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5569 useIdentityTransform, forSystem, &fd);
5570 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005571 }
5572
5573 {
5574 std::unique_lock<std::mutex> captureLock(captureMutex);
5575 syncFd = fd;
5576 captureResult = std::make_optional<status_t>(result);
5577 captureCondition.notify_one();
5578 }
5579 });
5580
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005581 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005583 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584 while (*captureResult == EAGAIN) {
5585 captureResult.reset();
5586 result = postMessageAsync(message);
5587 if (result != NO_ERROR) {
5588 return result;
5589 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005590 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005591 }
5592 result = *captureResult;
5593 }
5594
5595 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005596 sync_wait(syncFd, -1);
5597 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005598 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005599
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005600 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005601}
5602
chaviwa76b2712017-09-20 12:02:26 -07005603void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005604 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005605 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005606 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005607
Lloyd Pique144e1162017-12-20 16:44:52 -08005608 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005609
chaviwa76b2712017-09-20 12:02:26 -07005610 const auto reqWidth = renderArea.getReqWidth();
5611 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005612 const auto sourceCrop = renderArea.getSourceCrop();
5613 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005614
Peiyong Lin0e003c92018-09-17 11:09:51 -07005615 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005616 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005617
Mathias Agopian180f10d2013-04-10 22:55:41 -07005618 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005619 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005620
5621 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005622 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005623 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005624
chaviw50da5042018-04-09 13:49:37 -07005625 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005626 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005627 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005628
chaviwa76b2712017-09-20 12:02:26 -07005629 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005630 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005631 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005632 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005633 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005634}
5635
chaviwa76b2712017-09-20 12:02:26 -07005636status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5637 TraverseLayersFunction traverseLayers,
5638 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005639 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005640 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005641 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005642 ATRACE_CALL();
5643
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005644 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005645
5646 traverseLayers([&](Layer* layer) {
5647 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5648 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005649
Robert Carr03480e22018-01-04 16:02:06 -08005650 // We allow the system server to take screenshots of secure layers for
5651 // use in situations like the Screen-rotation animation and place
5652 // the impetus on WindowManager to not persist them.
5653 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005654 ALOGW("FB is protected: PERMISSION_DENIED");
5655 return PERMISSION_DENIED;
5656 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005657 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005658
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005659 // this binds the given EGLImage as a framebuffer for the
5660 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005661 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005662 if (bufferBond.getStatus() != NO_ERROR) {
5663 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005664 return INVALID_OPERATION;
5665 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005666
Dan Stozaabcda352017-06-01 14:37:39 -07005667 // this will in fact render into our dequeued buffer
5668 // via an FBO, which means we didn't have to create
5669 // an EGLSurface and therefore we're not
5670 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005671 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005672
Peiyong Linfb530cf2018-12-15 05:07:38 +00005673 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005674 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005675 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005676 }
Alec Mouri492bc572018-09-11 21:40:04 +00005677 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005678
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005679 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005680}
5681
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005682// ---------------------------------------------------------------------------
5683
Dan Stoza412903f2017-04-27 13:42:17 -07005684void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5685 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005686}
5687
Dan Stoza412903f2017-04-27 13:42:17 -07005688void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5689 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005690}
5691
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005692void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005693 const LayerVector::Visitor& visitor) {
5694 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005695 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005696 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005697 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005698 continue;
5699 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005700 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005701 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005702 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005703 return;
5704 }
chaviwa76b2712017-09-20 12:02:26 -07005705 if (!layer->isVisible()) {
5706 return;
5707 }
5708 visitor(layer);
5709 });
5710 }
5711}
5712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005713}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005714
Lloyd Pique074e8122018-07-26 12:57:23 -07005715
Mathias Agopian3f844832013-08-07 21:24:32 -07005716#if defined(__gl_h_)
5717#error "don't include gl/gl.h in this file"
5718#endif
5719
5720#if defined(__gl2_h_)
5721#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005722#endif