blob: c0059d5e2e993acdb77a31521950be782e156ae3 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070040#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070041#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080043#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080044#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070047#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070048#include <ui/ColorSpace.h>
49#include <ui/DebugUtils.h>
50#include <ui/DisplayInfo.h>
51#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070052#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080055#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070057#include <utils/String16.h>
58#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Robert Carr578038f2018-03-09 12:25:24 -080066#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070067#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070068#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020069#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080070#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020071#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080073#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070078#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070079#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070081#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070090#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091#include "Scheduler/EventControlThread.h"
92#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070093#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070095#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080096#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097
Mathias Agopianff2ed702013-09-01 21:36:12 -070098#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070099
David Sodman7e4ae112018-02-09 15:02:28 -0800100#include "android-base/stringprintf.h"
101
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700104#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800105#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900106#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107
chaviw1d044282017-09-27 12:19:28 -0700108#include <layerproto/LayerProtoParser.h>
109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800114using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700131 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700147ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
148 switch (rotation) {
149 case ISurfaceComposer::eRotateNone:
150 return ui::Transform::ROT_0;
151 case ISurfaceComposer::eRotate90:
152 return ui::Transform::ROT_90;
153 case ISurfaceComposer::eRotate180:
154 return ui::Transform::ROT_180;
155 case ISurfaceComposer::eRotate270:
156 return ui::Transform::ROT_270;
157 }
158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
159 return ui::Transform::ROT_0;
160}
161
Peiyong Linfca547f2018-07-09 13:03:33 -0700162#pragma clang diagnostic pop
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164class ConditionalLock {
165public:
166 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
167 if (lock) {
168 mMutex.lock();
169 }
170 }
171 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
172private:
173 Mutex& mMutex;
174 bool mLocked;
175};
Peiyong Linfca547f2018-07-09 13:03:33 -0700176
Peiyong Lin9d846a52018-11-05 13:18:20 -0800177// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
178bool validateCompositionDataspace(Dataspace dataspace) {
179 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
180}
181
Steven Thomasb02664d2017-07-26 18:48:28 -0700182} // namespace anonymous
183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184// ---------------------------------------------------------------------------
185
Mathias Agopian99b49842011-06-27 16:05:52 -0700186const String16 sHardwareTest("android.permission.HARDWARE_TEST");
187const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
188const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
189const String16 sDump("android.permission.DUMP");
190
191// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800192int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
193int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700194int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700195bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800196uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800197bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800198bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800199int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600200bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700201int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700202bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700203bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700204Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
205ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
206Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
207ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700208
Kalle Raitaa099a242017-01-11 11:17:29 -0800209std::string getHwcServiceName() {
210 char value[PROPERTY_VALUE_MAX] = {};
211 property_get("debug.sf.hwc_service_name", value, "default");
212 ALOGI("Using HWComposer service: '%s'", value);
213 return std::string(value);
214}
215
216bool useTrebleTestingOverride() {
217 char value[PROPERTY_VALUE_MAX] = {};
218 property_get("debug.sf.treble_testing_override", value, "false");
219 ALOGI("Treble testing override: '%s'", value);
220 return std::string(value) == "true";
221}
222
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
224 switch(displayColorSetting) {
225 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700226 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Enhanced");
231 default:
232 return std::string("Unknown ") +
233 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235}
236
David Sodmanbc815282017-11-05 18:57:52 -0800237SurfaceFlingerBE::SurfaceFlingerBE()
238 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800239 mFrameBuckets(),
240 mTotalTime(0),
241 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800242 mComposerSequenceId(0) {
243}
244
Lloyd Pique90c115d2018-09-18 21:39:42 -0700245SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
246 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800265 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800268 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700272 mMainThreadId(std::this_thread::get_id()),
273 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
276 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700306 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700307 getBool<V1_2::ISurfaceFlingerConfigs,
308 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
309
310 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
311 if (surfaceFlingerConfigsServiceV1_2) {
312 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700313 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
314 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
315 defaultCompositionDataspace = tmpDefaultDataspace;
316 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
317 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
318 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
319 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700320 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800321 mDefaultCompositionDataspace = defaultCompositionDataspace;
322 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600323
Peiyong Linb3839ad2018-09-05 15:37:19 -0700324 useContextPriority = getBool<ISurfaceFlingerConfigs,
325 &ISurfaceFlingerConfigs::useContextPriority>(true);
326
Iris Chang7501ed62018-04-30 14:45:42 +0800327 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700328 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
329 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800330 V1_1::DisplayOrientation::ORIENTATION_0);
331
332 switch (primaryDisplayOrientation) {
333 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800347
Lloyd Pique90c115d2018-09-18 21:39:42 -0700348 mPrimaryDispSync =
349 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
350 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 // debugging stuff...
353 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianb4b17302013-03-20 18:36:41 -0700355 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700356 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358 property_get("debug.sf.showupdates", value, "0");
359 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 property_get("debug.sf.ddms", value, "0");
362 mDebugDDMS = atoi(value);
363 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700364 if (!startDdmConnection()) {
365 // start failed, and DDMS debugging not enabled
366 mDebugDDMS = 0;
367 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700369 ALOGI_IF(mDebugRegion, "showupdates enabled");
370 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700371
372 property_get("debug.sf.disable_backpressure", value, "0");
373 mPropagateBackpressure = !atoi(value);
374 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700375
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800376 property_get("debug.sf.enable_hwc_vds", value, "0");
377 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800378 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800379
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800380 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800381 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800382 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700383
Yiwei Zhang243b3782018-05-15 17:40:04 -0700384 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700385 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
386 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
387
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200388 property_get("debug.sf.early_phase_offset_ns", value, "-1");
389 const int earlySfOffsetNs = atoi(value);
390
391 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
392 const int earlyGlSfOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
395 const int earlyAppOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
398 const int earlyGlAppOffsetNs = atoi(value);
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200403 const VSyncModulator::Offsets earlyOffsets =
404 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
405 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
406 const VSyncModulator::Offsets earlyGlOffsets =
407 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
408 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
409 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
410 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700411
Romain Guy11d63f42017-07-20 12:47:14 -0700412 // We should be reading 'persist.sys.sf.color_saturation' here
413 // but since /data may be encrypted, we need to wait until after vold
414 // comes online to attempt to read the property. The property is
415 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800416
417 if (useTrebleTestingOverride()) {
418 // Without the override SurfaceFlinger cannot connect to HIDL
419 // services that are not listed in the manifests. Considered
420 // deriving the setting from the set service name, but it
421 // would be brittle if the name that's not 'default' is used
422 // for production purposes later on.
423 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425}
426
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427void SurfaceFlinger::onFirstRef()
428{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800429 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432SurfaceFlinger::~SurfaceFlinger()
433{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434}
435
Dan Stozac7014012014-02-14 15:03:43 -0800436void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437{
438 // the window manager died on us. prepare its eulogy.
439
Andy McFadden13a082e2012-08-24 10:16:42 -0700440 // restore initial conditions (default device unblank, etc)
441 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442
443 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700444 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445}
446
Robert Carr1db73f62016-12-21 12:58:51 -0800447static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700448 status_t err = client->initCheck();
449 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 }
Robert Carr1db73f62016-12-21 12:58:51 -0800452 return nullptr;
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
456 return initClient(new Client(this));
457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 // Display ID is assigned when virtual display is allocated by HWC.
480 DisplayDeviceState state;
481 state.isSecure = secure;
482 state.displayName = displayName;
483 mCurrentState.displays.add(token, state);
484 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
492 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
498 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 mInterceptor->saveDisplayDeletion(state.sequenceId);
503 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 std::optional<DisplayId> displayId;
509
510 if (id == HWC_DISPLAY_PRIMARY) {
511 displayId = getInternalDisplayId();
512 } else if (id == HWC_DISPLAY_EXTERNAL) {
513 displayId = getExternalDisplayId();
514 }
515
516 if (!displayId) {
517 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800518 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520
521 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522}
523
Ady Abraham37965d42018-11-01 13:43:32 -0700524status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
525 if (!outGetColorManagement) {
526 return BAD_VALUE;
527 }
528 *outGetColorManagement = useColorManagement;
529 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700530}
531
Lloyd Pique441d5042018-10-18 16:49:51 -0700532HWComposer& SurfaceFlinger::getHwComposer() const {
533 return mCompositionEngine->getHwComposer();
534}
535
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700536renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
537 return mCompositionEngine->getRenderEngine();
538}
539
Lloyd Pique70d91362018-10-18 16:02:55 -0700540compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
541 return *mCompositionEngine.get();
542}
543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544void SurfaceFlinger::bootFinished()
545{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700546 if (mStartPropertySetThread->join() != NO_ERROR) {
547 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549 const nsecs_t now = systemTime();
550 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000551 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552
553 // wait patiently for the window manager death
554 const String16 name("window");
555 sp<IBinder> window(defaultServiceManager()->getService(name));
556 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700557 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558 }
Robert Carr720e5062018-07-30 17:45:14 -0700559 sp<IBinder> input(defaultServiceManager()->getService(
560 String16("inputflinger")));
561 if (input == nullptr) {
562 ALOGE("Failed to link to input service");
563 } else {
564 mInputFlinger = interface_cast<IInputFlinger>(input);
565 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700566
Steven Thomas050b2c82017-03-06 11:45:16 -0800567 if (mVrFlinger) {
568 mVrFlinger->OnBootFinished();
569 }
570
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700572 // formerly we would just kill the process, but we now ask it to exit so it
573 // can choose where to stop the animation.
574 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700575
576 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
577 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
578 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700579
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 postMessageAsync(new LambdaMessage([this] {
581 readPersistentProperties();
582 mBootStage = BootStage::FINISHED;
583 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584}
585
Dan Stoza436ccf32018-06-21 12:10:12 -0700586uint32_t SurfaceFlinger::getNewTexture() {
587 {
588 std::lock_guard lock(mTexturePoolMutex);
589 if (!mTexturePool.empty()) {
590 uint32_t name = mTexturePool.back();
591 mTexturePool.pop_back();
592 ATRACE_INT("TexturePoolSize", mTexturePool.size());
593 return name;
594 }
595
596 // The pool was too small, so increase it for the future
597 ++mTexturePoolSize;
598 }
599
600 // The pool was empty, so we need to get a new texture name directly using a
601 // blocking call to the main thread
602 uint32_t name = 0;
603 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
604 return name;
605}
606
Mathias Agopian3f844832013-08-07 21:24:32 -0700607void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700608 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700609}
610
Wei Wangf9b05ee2017-07-19 20:59:39 -0700611// Do not call property_set on main thread which will be blocked by init
612// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700614 ALOGI( "SurfaceFlinger's main thread ready to run. "
615 "Initializing graphics H/W...");
616
Thierry Strudel2924d012017-08-14 15:19:37 -0700617 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620
Dominik Laskowskif654d572018-12-20 11:03:06 -0800621 auto resyncCallback = makeResyncCallback();
622
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700624 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700625 mScheduler = getFactory().createScheduler([this](bool enabled) {
626 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
627 });
628
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700630 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800631 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 impl::EventThread::InterceptVSyncsCallback());
633 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700634 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800635 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 mInterceptor->saveVSyncEvent(timestamp);
637 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800638
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700640 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
641 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 } else {
643 mEventThreadSource =
644 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
645 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
646 mEventThread =
647 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 impl::EventThread::InterceptVSyncsCallback(),
649 "appEventThread");
650 mSfEventThreadSource =
651 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
652 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
653
654 mSFEventThread =
655 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700656 [this](nsecs_t timestamp) {
657 mInterceptor->saveVSyncEvent(timestamp);
658 },
659 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800660 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700661 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800663
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700665 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700666 renderEngineFeature |= (useColorManagement ?
667 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700668 renderEngineFeature |= (useContextPriority ?
669 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700670
671 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700673 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700674 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700675
676 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
677 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
679 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 const auto display = getDefaultDisplayDeviceLocked();
683 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800686
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 // This callback is called from the vr flinger dispatch thread. We
690 // need to call signalTransaction(), which requires holding
691 // mStateLock when we're not on the main thread. Acquiring
692 // mStateLock from the vr flinger dispatch thread might trigger a
693 // deadlock in surface flinger (see b/66916578), so post a message
694 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
697 mVrFlingerRequestsDisplay = requestDisplay;
698 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
702 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 .value_or(0),
705 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (!mVrFlinger) {
707 ALOGE("Failed to start vrflinger");
708 }
709 }
710
Lloyd Pique90c115d2018-09-18 21:39:42 -0700711 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700713
Mathias Agopian92a979a2012-08-02 18:32:23 -0700714 // initialize our drawing state
715 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700716
Andy McFadden13a082e2012-08-24 10:16:42 -0700717 // set initial conditions (e.g. unblank default device)
718 initializeDisplays();
719
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700720 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700721
Wei Wangf9b05ee2017-07-19 20:59:39 -0700722 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700723
724 const bool presentFenceReliable =
725 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
726 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727
728 if (mStartPropertySetThread->Start() != NO_ERROR) {
729 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800731
Ana Krulec7d1d6832018-12-27 11:10:09 -0800732 if (mUseScheduler) {
733 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
734 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
735 }
736
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700752}
753
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Start boot animation service by setting a property mailbox
756 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700757 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 if (mStartPropertySetThread->join() != NO_ERROR) {
760 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700765 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800773
Jamie Gennis582270d2011-08-17 18:19:00 -0700774bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800775 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800776 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800777 return authenticateSurfaceTextureLocked(bufferProducer);
778}
779
780bool SurfaceFlinger::authenticateSurfaceTextureLocked(
781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800782 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800783 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800784}
785
Brian Anderson6b376712017-04-04 10:51:39 -0700786status_t SurfaceFlinger::getSupportedFrameTimestamps(
787 std::vector<FrameEvent>* outSupported) const {
788 *outSupported = {
789 FrameEvent::REQUESTED_PRESENT,
790 FrameEvent::ACQUIRE,
791 FrameEvent::LATCH,
792 FrameEvent::FIRST_REFRESH_START,
793 FrameEvent::LAST_REFRESH_START,
794 FrameEvent::GPU_COMPOSITION_DONE,
795 FrameEvent::DEQUEUE_READY,
796 FrameEvent::RELEASE,
797 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700800 if (!getHwComposer().hasCapability(
801 HWC2::Capability::PresentFenceIsNotReliable)) {
802 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
803 }
804 return NO_ERROR;
805}
806
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
808 Vector<DisplayInfo>* configs) {
809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 const auto displayId = getPhysicalDisplayId(displayToken);
814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700822 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826 return density;
827 }
828 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Steven Thomas6d8110b2017-08-31 18:24:21 -0700837 ConditionalLock _l(mStateLock,
838 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 DisplayInfo info = DisplayInfo();
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 float xdpi = hwConfig->getDpiX();
843 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700845 info.w = hwConfig->getWidth();
846 info.h = hwConfig->getHeight();
847 // Default display viewport to display width and height
848 info.viewportW = info.w;
849 info.viewportH = info.h;
850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 // The density of the device is provided by a build property
853 float density = Density::getBuildDensity() / 160.0f;
854 if (density == 0) {
855 // the build doesn't provide a density -- this is wrong!
856 // use xdpi instead
857 ALOGE("ro.sf.lcd_density must be defined as a build property");
858 density = xdpi / 160.0f;
859 }
860 if (Density::getEmuDensity()) {
861 // if "qemu.sf.lcd_density" is specified, it overrides everything
862 xdpi = ydpi = density = Density::getEmuDensity();
863 density /= 160.0f;
864 }
865 info.density = density;
866
867 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868 const auto display = getDefaultDisplayDeviceLocked();
869 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
871 // This is for screenrecord
872 const Rect viewport = display->getViewport();
873 if (viewport.isValid()) {
874 info.viewportW = uint32_t(viewport.getWidth());
875 info.viewportH = uint32_t(viewport.getHeight());
876 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 } else {
878 // TODO: where should this value come from?
879 static const int TV_DENSITY = 213;
880 info.density = TV_DENSITY / 160.0f;
881 info.orientation = 0;
882 }
883
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Dominik Laskowski075d3172018-05-24 15:50:06 -0700907 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700908 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
Ana Krulece588e312018-09-18 12:32:24 -0700923 if (mUseScheduler) {
924 mScheduler->getDisplayStatInfo(stats);
925 } else {
926 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
928 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return NO_ERROR;
930}
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
933 const auto display = getDisplayDevice(displayToken);
934 if (!display) {
935 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800936 return BAD_VALUE;
937 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700940}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700941
Ana Krulec7d1d6832018-12-27 11:10:09 -0800942status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
943 ATRACE_NAME("setActiveConfigAsync");
944 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
945 return NO_ERROR;
946}
947
948status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
949 ATRACE_NAME("setActiveConfigSync");
950 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
951 return NO_ERROR;
952}
953
954void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
955 Vector<DisplayInfo> configs;
956 getDisplayConfigs(displayToken, &configs);
957 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
958 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
959 return;
960 }
961
962 const auto display = getDisplayDevice(displayToken);
963 if (!display) {
964 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
965 displayToken.get());
966 return;
967 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700968 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 return;
971 }
972 int currentDisplayPowerMode = display->getPowerMode();
973 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
974 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 return;
976 }
977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700979 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800980 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981 return;
982 }
983
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 const auto displayId = display->getId();
985 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 ATRACE_INT("ActiveConfigMode", mode);
991 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700992}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
995 Vector<ColorMode>* outColorModes) {
996 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return BAD_VALUE;
998 }
999
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 const auto displayId = getPhysicalDisplayId(displayToken);
1001 if (!displayId) {
1002 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001003 }
1004
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001006 {
1007 ConditionalLock _l(mStateLock,
1008 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001009 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001010 }
Michael Wright28f24d02016-07-12 13:30:53 -07001011 outColorModes->clear();
1012 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1013
1014 return NO_ERROR;
1015}
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1018 if (const auto display = getDisplayDevice(displayToken)) {
1019 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001020 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1025 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001026 if (display->isVirtual()) {
1027 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1028 return;
1029 }
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 ColorMode currentMode = display->getActiveColorMode();
1032 Dataspace currentDataSpace = display->getCompositionDataSpace();
1033 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001034
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 if (mode == currentMode && dataSpace == currentDataSpace &&
1036 renderIntent == currentRenderIntent) {
1037 return;
1038 }
1039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 display->setActiveColorMode(mode);
1041 display->setCompositionDataSpace(dataSpace);
1042 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001043
Dominik Laskowski075d3172018-05-24 15:50:06 -07001044 const auto displayId = display->getId();
1045 LOG_ALWAYS_FATAL_IF(!displayId);
1046 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1047
Dominik Laskowski34157762018-10-31 13:07:19 -07001048 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001050 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001051}
1052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001054 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 Vector<ColorMode> modes;
1056 getDisplayColorModes(displayToken, &modes);
1057 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1058 if (mode < ColorMode::NATIVE || !exists) {
1059 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1060 decodeColorMode(mode).c_str(), mode, displayToken.get());
1061 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001062 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 const auto display = getDisplayDevice(displayToken);
1064 if (!display) {
1065 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1066 decodeColorMode(mode).c_str(), mode, displayToken.get());
1067 } else if (display->isVirtual()) {
1068 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1069 decodeColorMode(mode).c_str(), mode);
1070 } else {
1071 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1072 RenderIntent::COLORIMETRIC);
1073 }
1074 }));
1075
Michael Wright28f24d02016-07-12 13:30:53 -07001076 return NO_ERROR;
1077}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078
Svetoslavd85084b2014-03-20 10:28:31 -07001079status_t SurfaceFlinger::clearAnimationFrameStats() {
1080 Mutex::Autolock _l(mStateLock);
1081 mAnimFrameTracker.clearStats();
1082 return NO_ERROR;
1083}
1084
1085status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1086 Mutex::Autolock _l(mStateLock);
1087 mAnimFrameTracker.getStats(outStats);
1088 return NO_ERROR;
1089}
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1092 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 Mutex::Autolock _l(mStateLock);
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const auto display = getDisplayDeviceLocked(displayToken);
1096 if (!display) {
1097 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 return BAD_VALUE;
1099 }
1100
Peiyong Linfb069302018-04-25 14:34:31 -07001101 // At this point the DisplayDeivce should already be set up,
1102 // meaning the luminance information is already queried from
1103 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001105 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1106 capabilities.getDesiredMaxLuminance(),
1107 capabilities.getDesiredMaxAverageLuminance(),
1108 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001109
1110 return NO_ERROR;
1111}
1112
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001113status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1114 ui::PixelFormat* outFormat,
1115 ui::Dataspace* outDataspace,
1116 uint8_t* outComponentMask) const {
1117 if (!outFormat || !outDataspace || !outComponentMask) {
1118 return BAD_VALUE;
1119 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001120 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001121 if (!display || !display->getId()) {
1122 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1123 return BAD_VALUE;
1124 }
1125 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1126 outDataspace, outComponentMask);
1127}
1128
Kevin DuBois74e53772018-11-19 10:52:38 -08001129status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1130 bool enable, uint8_t componentMask,
1131 uint64_t maxFrames) const {
1132 const auto display = getDisplayDevice(displayToken);
1133 if (!display || !display->getId()) {
1134 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1135 return BAD_VALUE;
1136 }
1137
1138 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1139 componentMask, maxFrames);
1140}
1141
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001142status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1143 uint64_t maxFrames, uint64_t timestamp,
1144 DisplayedFrameStats* outStats) const {
1145 const auto display = getDisplayDevice(displayToken);
1146 if (!display || !display->getId()) {
1147 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1148 return BAD_VALUE;
1149 }
1150
1151 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1152 outStats);
1153}
1154
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001155status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1156 if (!outSupported) {
1157 return BAD_VALUE;
1158 }
1159 *outSupported = getRenderEngine().supportsProtectedContent();
1160 return NO_ERROR;
1161}
1162
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001164 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 if (mInjectVSyncs == enable) {
1168 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170
Dominik Laskowskif654d572018-12-20 11:03:06 -08001171 auto resyncCallback = makeResyncCallback();
1172
Ana Krulec98b5b242018-08-10 15:03:23 -07001173 // TODO(akrulec): Part of the Injector should be refactored, so that it
1174 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 if (enable) {
1176 ALOGV("VSync Injections enabled");
1177 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001178 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001179 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001180 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001181 impl::EventThread::InterceptVSyncsCallback(),
1182 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001184 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185 } else {
1186 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001187 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 }
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001191 }));
1192
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001193 return NO_ERROR;
1194}
1195
1196status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 Mutex::Autolock _l(mStateLock);
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199 if (!mInjectVSyncs) {
1200 ALOGE("VSync Injections not enabled");
1201 return BAD_VALUE;
1202 }
1203 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1204 ALOGV("Injecting VSync inside SurfaceFlinger");
1205 mVSyncInjector->onInjectSyncEvent(when);
1206 }
1207 return NO_ERROR;
1208}
1209
Lloyd Pique755e3192018-01-31 16:46:15 -08001210status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1211 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001212 // Try to acquire a lock for 1s, fail gracefully
1213 const status_t err = mStateLock.timedLock(s2ns(1));
1214 const bool locked = (err == NO_ERROR);
1215 if (!locked) {
1216 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1217 return TIMED_OUT;
1218 }
1219
1220 outLayers->clear();
1221 mCurrentState.traverseInZOrder([&](Layer* layer) {
1222 outLayers->push_back(layer->getLayerDebugInfo());
1223 });
1224
1225 mStateLock.unlock();
1226 return NO_ERROR;
1227}
1228
Peiyong Linc6780972018-10-28 15:24:08 -07001229status_t SurfaceFlinger::getCompositionPreference(
1230 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1231 Dataspace* outWideColorGamutDataspace,
1232 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001233 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001234 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001235 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001236 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001237 return NO_ERROR;
1238}
1239
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001240// ----------------------------------------------------------------------------
1241
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001242sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1243 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001244 auto resyncCallback = makeResyncCallback();
1245
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 if (mUseScheduler) {
1247 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001248 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001249 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001252 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001255 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001256 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001257 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001258 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001259}
1260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262
1263void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001276 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001286 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001287 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288 if (res == NO_ERROR) {
1289 msg->wait();
1290 }
1291 return res;
1292}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001295 do {
1296 waitForEvent();
1297 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001298}
1299
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300void SurfaceFlinger::enableHardwareVsync() {
1301 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001303 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001304 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001306 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307}
1308
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310 Mutex::Autolock _l(mHWVsyncLock);
1311
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 if (makeAvailable) {
1313 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001314 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1315 if (mUseScheduler) {
1316 mScheduler->makeHWSyncAvailable(true);
1317 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001318 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001319 // Hardware vsync is not currently available, so abort the resync
1320 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001321 return;
1322 }
1323
Dominik Laskowski075d3172018-05-24 15:50:06 -07001324 const auto displayId = getInternalDisplayId();
1325 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001326 return;
1327 }
1328
Dominik Laskowski075d3172018-05-24 15:50:06 -07001329 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331
Ana Krulece588e312018-09-18 12:32:24 -07001332 if (mUseScheduler) {
1333 mScheduler->setVsyncPeriod(period);
1334 } else {
1335 mPrimaryDispSync->reset();
1336 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337
Ana Krulece588e312018-09-18 12:32:24 -07001338 if (!mPrimaryHWVsyncEnabled) {
1339 mPrimaryDispSync->beginResync();
1340 mEventControlThread->setVsyncEnabled(true);
1341 mPrimaryHWVsyncEnabled = true;
1342 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343 }
1344}
1345
Jesse Hall948fe0c2013-10-14 12:56:09 -07001346void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347 Mutex::Autolock _l(mHWVsyncLock);
1348 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001349 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001350 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351 mPrimaryHWVsyncEnabled = false;
1352 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001353 if (makeUnavailable) {
1354 mHWVsyncAvailable = false;
1355 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356}
1357
Dominik Laskowskif654d572018-12-20 11:03:06 -08001358void SurfaceFlinger::VsyncState::resync() {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001359 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001360
1361 // No explicit locking is needed here since EventThread holds a lock while calling this method
Dan Stoza57164302017-05-08 14:03:54 -07001362 const nsecs_t now = systemTime();
Dominik Laskowskif654d572018-12-20 11:03:06 -08001363 if (now - lastResyncTime > kIgnoreDelay) {
1364 flinger.resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001365 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001366 lastResyncTime = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001367}
1368
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001369void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1370 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001371 ATRACE_NAME("SF onVsync");
1372
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001375 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 return;
1377 }
1378
Dominik Laskowski075d3172018-05-24 15:50:06 -07001379 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 return;
1381 }
1382
Dominik Laskowski075d3172018-05-24 15:50:06 -07001383 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001384 // For now, we don't do anything with external display vsyncs.
1385 return;
1386 }
1387
Ana Krulece588e312018-09-18 12:32:24 -07001388 if (mUseScheduler) {
1389 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001390 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001391 bool needsHwVsync = false;
1392 { // Scope for the lock
1393 Mutex::Autolock _l(mHWVsyncLock);
1394 if (mPrimaryHWVsyncEnabled) {
1395 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1396 }
1397 }
1398
1399 if (needsHwVsync) {
1400 enableHardwareVsync();
1401 } else {
1402 disableHardwareVsync(false);
1403 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001404 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001405}
1406
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001408 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1409 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410}
1411
Ana Krulec7d1d6832018-12-27 11:10:09 -08001412void SurfaceFlinger::setRefreshRateTo(float newFps) {
1413 const auto displayId = getInternalDisplayId();
1414 if (!displayId || mBootStage != BootStage::FINISHED) {
1415 return;
1416 }
1417 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1418 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1419 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1420 // refresh cycle.
1421
1422 // Don't do any updating if the current fps is the same as the new one.
1423 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1424 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1425 if (currentVsyncPeriod == 0) {
1426 return;
1427 }
1428 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1429 // floating numbers.
1430 const float currentFps = 1e9 / currentVsyncPeriod;
1431 if (std::abs(currentFps - newFps) <= 1) {
1432 return;
1433 }
1434
1435 auto configs = getHwComposer().getConfigs(*displayId);
1436 for (int i = 0; i < configs.size(); i++) {
1437 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1438 if (vsyncPeriod == 0) {
1439 continue;
1440 }
1441 const float fps = 1e9 / vsyncPeriod;
1442 // TODO(b/113612090): There should be a better way at determining which config
1443 // has the right refresh rate.
1444 if (std::abs(fps - newFps) <= 1) {
1445 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1446 if (!display) return;
1447 // This is posted in async function to avoid deadlock when getDisplayDevice
1448 // requires mStateLock.
1449 setActiveConfigAsync(display, i);
1450 ATRACE_INT("FPS", newFps);
1451 }
1452 }
1453}
1454
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001455void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001456 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001457 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001458 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459
Lloyd Piqueba04e622017-12-14 17:11:26 -08001460 // Ignore events that do not have the right sequenceId.
1461 if (sequenceId != getBE().mComposerSequenceId) {
1462 return;
1463 }
1464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 // Only lock if we're not on the main thread. This function is normally
1466 // called on a hwbinder thread, but for the primary display it's called on
1467 // the main thread with the state lock already held, so don't attempt to
1468 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001469 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001470
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001471 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001472
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001473 if (std::this_thread::get_id() == mMainThreadId) {
1474 // Process all pending hot plug events immediately if we are on the main thread.
1475 processDisplayHotplugEventsLocked();
1476 }
1477
Lloyd Piqueba04e622017-12-14 17:11:26 -08001478 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001479}
1480
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001481void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001482 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001483 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001485 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001487}
1488
Dominik Laskowski075d3172018-05-24 15:50:06 -07001489void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001490 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001492 if (const auto displayId = getInternalDisplayId()) {
1493 getHwComposer().setVsyncEnabled(*displayId,
1494 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1495 }
Mathias Agopian86303202012-07-24 22:46:10 -07001496}
1497
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001498// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001499void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001500 if (mUseScheduler) {
1501 mScheduler->disableHardwareVsync(true);
1502 } else {
1503 disableHardwareVsync(true);
1504 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001505 // Clear the drawing state so that the logic inside of
1506 // handleTransactionLocked will fire. It will determine the delta between
1507 // mCurrentState and mDrawingState and re-apply all changes when we make the
1508 // transition.
1509 mDrawingState.displays.clear();
1510 mDisplays.clear();
1511}
1512
Steven Thomas050b2c82017-03-06 11:45:16 -08001513void SurfaceFlinger::updateVrFlinger() {
1514 if (!mVrFlinger)
1515 return;
1516 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001518 return;
1519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520
Lloyd Pique441d5042018-10-18 16:49:51 -07001521 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 ALOGE("Vr flinger is only supported for remote hardware composer"
1523 " service connections. Ignoring request to transition to vr"
1524 " flinger.");
1525 mVrFlingerRequestsDisplay = false;
1526 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001527 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001530
Steven Thomas0123ac62018-07-12 11:32:34 -07001531 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001532 LOG_ALWAYS_FATAL_IF(!display);
1533 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001534 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1535 // called below. Clear the reference now so we don't accidentally use it
1536 // later.
1537 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001538
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001542
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001544 // Delete the current instance before creating the new one
1545 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1546 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1547 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1548 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549
Lloyd Pique441d5042018-10-18 16:49:51 -07001550 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001551 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001552
1553 if (vrFlingerRequestsDisplay) {
1554 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001555 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
1557 mVisibleRegionsDirty = true;
1558 invalidateHwcGeometry();
1559
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001560 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001561 display = getDefaultDisplayDeviceLocked();
1562 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001563 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001566 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 const nsecs_t period = activeConfig->getVsyncPeriod();
1568 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001569
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570 // The present fences returned from vr_hwc are not an accurate
1571 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001572 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001573 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1574 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001575 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001576 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001577 !hasSyncFramework);
1578 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Use phase of 0 since phase is not known.
1581 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001582 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1583 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001584
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001585 resyncToHardwareVsync(false);
1586
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001587 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001589}
1590
Mathias Agopian4fec8732012-06-29 14:12:52 -07001591void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001592 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001593 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001594 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001595 if (mUseScheduler) {
1596 // This call is made each time SF wakes up and creates a new frame.
1597 mScheduler->incrementFrameCounter();
1598 }
Dan Stoza50182882016-07-08 12:02:20 -07001599 bool frameMissed = !mHadClientComposition &&
1600 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 (mPreviousPresentFence->getSignalTime() ==
1602 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001603 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001604 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001605 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001606 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001607 if (mPropagateBackpressure) {
1608 signalLayerUpdate();
1609 break;
1610 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 }
Dan Stoza50182882016-07-08 12:02:20 -07001612
Steven Thomas050b2c82017-03-06 11:45:16 -08001613 // Now that we're going to make it to the handleMessageTransaction()
1614 // call below it's safe to call updateVrFlinger(), which will
1615 // potentially trigger a display handoff.
1616 updateVrFlinger();
1617
Dan Stoza6b9454d2014-11-07 16:00:59 -08001618 bool refreshNeeded = handleMessageTransaction();
1619 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001620 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001621 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001622 // Signal a refresh if a transaction modified the window state,
1623 // a new buffer was latched, or if HWC has requested a full
1624 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625 signalRefresh();
1626 }
1627 break;
1628 }
1629 case MessageQueue::REFRESH: {
1630 handleMessageRefresh();
1631 break;
1632 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001633 }
1634}
1635
Dan Stoza6b9454d2014-11-07 16:00:59 -08001636bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001637 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001638
1639 // Apply any ready transactions in the queues if there are still transactions that have not been
1640 // applied, wake up during the next vsync period and check again
1641 bool transactionNeeded = false;
1642 if (!flushTransactionQueues()) {
1643 transactionNeeded = true;
1644 }
1645
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001647 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001648 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001649
1650 if (transactionNeeded) {
1651 setTransactionFlags(eTransactionNeeded);
1652 }
1653
1654 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655}
1656
Mathias Agopian4fec8732012-06-29 14:12:52 -07001657void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001658 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001659
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001660 mRefreshPending = false;
1661
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001662 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001663 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001664 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001665 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001666 for (const auto& [token, display] : mDisplays) {
1667 beginFrame(display);
1668 prepareFrame(display);
1669 doDebugFlashRegions(display, repaintEverything);
1670 doComposition(display, repaintEverything);
1671 }
1672
Adrian Roos1e1a1282017-11-01 19:05:31 +01001673 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001674 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675
1676 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001677 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001678
Dan Stozabfbffeb2016-07-21 14:49:33 -07001679 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001680 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001681 mHadClientComposition =
1682 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001683 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001684
Alec Mouri86770e52018-09-24 22:40:58 +00001685 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001686 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001687 if (mHadClientComposition) {
1688 base::unique_fd flushFence(getRenderEngine().flush());
1689 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1690 getBE().flushFence = new Fence(std::move(flushFence));
1691 } else {
1692 // Cleanup for hygiene.
1693 getBE().flushFence = Fence::NO_FENCE;
1694 }
1695 }
1696
Jorim Jaggi90535212018-05-23 23:44:06 +02001697 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001698
David Sodman7e4ae112018-02-09 15:02:28 -08001699 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001700 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001701 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001702 compositionInfo.hwc.hwcLayer = nullptr;
1703 }
David Sodmanba340492018-08-05 21:51:33 -07001704 }
David Sodman7e4ae112018-02-09 15:02:28 -08001705
1706 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001708
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709
1710bool SurfaceFlinger::handleMessageInvalidate() {
1711 ATRACE_CALL();
1712 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713}
1714
David Sodman79bba0e2018-08-05 18:07:49 -07001715void SurfaceFlinger::calculateWorkingSet() {
1716 ATRACE_CALL();
1717 ALOGV(__FUNCTION__);
1718
David Sodman79bba0e2018-08-05 18:07:49 -07001719 // build the h/w work list
1720 if (CC_UNLIKELY(mGeometryInvalid)) {
1721 mGeometryInvalid = false;
1722 for (const auto& [token, display] : mDisplays) {
1723 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001724 if (!displayId) {
1725 continue;
1726 }
David Sodman79bba0e2018-08-05 18:07:49 -07001727
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1729 for (size_t i = 0; i < currentLayers.size(); i++) {
1730 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001731
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 if (!layer->hasHwcLayer(*displayId)) {
1733 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1734 layer->forceClientComposition(*displayId);
1735 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001736 }
1737 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738
1739 layer->setGeometry(display, i);
1740 if (mDebugDisableHWC || mDebugRegion) {
1741 layer->forceClientComposition(*displayId);
1742 }
David Sodman79bba0e2018-08-05 18:07:49 -07001743 }
1744 }
1745 }
1746
1747 // Set the per-frame data
1748 for (const auto& [token, display] : mDisplays) {
1749 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001750 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001751 continue;
1752 }
1753
1754 if (mDrawingState.colorMatrixChanged) {
1755 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001756 status_t result =
1757 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001758 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1759 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001760 }
1761 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1762 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001764 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1765 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1766 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001767 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001768 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1769 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1770 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001772 }
1773
Peiyong Lind3788632018-09-18 16:01:31 -07001774 // TODO(b/111562338) remove when composer 2.3 is shipped.
1775 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001777 }
1778
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001779 if (layer->getRoundedCornerState().radius > 0.0f) {
1780 layer->forceClientComposition(*displayId);
1781 }
1782
Dominik Laskowski075d3172018-05-24 15:50:06 -07001783 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001784 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001786 continue;
1787 }
1788
Dominik Laskowski075d3172018-05-24 15:50:06 -07001789 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1790 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
1792
Peiyong Lin13effd12018-07-24 17:01:47 -07001793 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 ColorMode colorMode;
1795 Dataspace dataSpace;
1796 RenderIntent renderIntent;
1797 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1798 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1799 }
1800 }
1801
1802 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001803
1804 for (const auto& [token, display] : mDisplays) {
1805 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001806 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001807 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001808
1809 if (displayId) {
1810 if (!layer->setHwcLayer(*displayId)) {
1811 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1812 }
1813 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001814 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815
Dominik Laskowski05275f12018-11-01 15:03:24 -07001816 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001817 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1818 }
1819 }
David Sodman79bba0e2018-08-05 18:07:49 -07001820}
1821
David Sodmanfa9b2af2017-12-24 13:28:59 -08001822void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823{
1824 // is debugging enabled
1825 if (CC_LIKELY(!mDebugRegion))
1826 return;
1827
David Sodmanfa9b2af2017-12-24 13:28:59 -08001828 if (display->isPoweredOn()) {
1829 // transform the dirty region into this screen's coordinate space
1830 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1831 if (!dirtyRegion.isEmpty()) {
1832 // redraw the whole screen
1833 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834
David Sodmanfa9b2af2017-12-24 13:28:59 -08001835 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001837 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001838
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001839 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840 }
1841 }
1842
David Sodmanfa9b2af2017-12-24 13:28:59 -08001843 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844
1845 if (mDebugRegion > 1) {
1846 usleep(mDebugRegion * 1000);
1847 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001848
Dominik Laskowski05275f12018-11-01 15:03:24 -07001849 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850}
1851
Adrian Roos1e1a1282017-11-01 19:05:31 +01001852void SurfaceFlinger::doTracing(const char* where) {
1853 ATRACE_CALL();
1854 ATRACE_NAME(where);
1855 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001856 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001857 }
1858}
1859
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001860void SurfaceFlinger::logLayerStats() {
1861 ATRACE_CALL();
1862 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001863 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001864 if (display->isPrimary()) {
1865 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001866 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001867 }
1868 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001869
1870 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001871 }
1872}
1873
David Sodman2b406362017-12-15 13:33:47 -08001874void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 ATRACE_CALL();
1877 ALOGV("preComposition");
1878
David Sodman2b406362017-12-15 13:33:47 -08001879 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1880
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001882 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001883 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884 needExtraInvalidate = true;
1885 }
Robert Carr2047fae2016-11-28 14:09:09 -08001886 });
1887
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 if (needExtraInvalidate) {
1889 signalLayerUpdate();
1890 }
1891}
1892
Ana Krulece588e312018-09-18 12:32:24 -07001893void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1894 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001895 // Update queue of past composite+present times and determine the
1896 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001897 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001899 while (!getBE().mCompositePresentTimes.empty()) {
1900 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001901 // Cached values should have been updated before calling this method,
1902 // which helps avoid duplicate syscalls.
1903 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1904 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1905 break;
1906 }
1907 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001908 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 }
1910
1911 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001912 while (getBE().mCompositePresentTimes.size() > 16) {
1913 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914 }
1915
Ana Krulece588e312018-09-18 12:32:24 -07001916 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001917}
1918
Ana Krulece588e312018-09-18 12:32:24 -07001919void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1920 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // Integer division and modulo round toward 0 not -inf, so we need to
1922 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001923 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1924 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1925 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926
Brian Andersond0010582017-03-07 13:20:31 -08001927 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1928 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001929 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001930 }
1931
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932 // Snap the latency to a value that removes scheduling jitter from the
1933 // composition and present times, which often have >1ms of jitter.
1934 // Reducing jitter is important if an app attempts to extrapolate
1935 // something (such as user input) to an accurate diasplay time.
1936 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1937 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001938 nsecs_t bias = stats.vsyncPeriod / 2;
1939 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1940 nsecs_t snappedCompositeToPresentLatency =
1941 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942
David Sodman99974d22017-11-28 12:04:33 -08001943 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001944 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1945 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001946 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947}
1948
Ady Abraham8164d482019-01-11 14:47:59 -08001949// debug patch for b/119477596 - add stack guards to catch stack
1950// corruptions and disable clang optimizations.
1951// The code below is temporary and planned to be removed once stack
1952// corruptions are found.
1953#pragma clang optimize off
1954class StackGuard {
1955public:
1956 StackGuard(const char* name, const char* func, int line) {
1957 guarders.reserve(MIN_CAPACITY);
1958 guarders.push_back({this, name, func, line});
1959 validate();
1960 }
1961 ~StackGuard() {
1962 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1963 if (i->guard == this) {
1964 guarders.erase(i);
1965 break;
1966 }
1967 }
1968 }
1969
1970 static void validate() {
1971 for (const auto& guard : guarders) {
1972 if (guard.guard->cookie != COOKIE_VALUE) {
1973 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1974 CallStack stack(LOG_TAG);
1975 abort();
1976 }
1977 }
1978 }
1979
1980private:
1981 uint64_t cookie = COOKIE_VALUE;
1982 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1983 static constexpr size_t MIN_CAPACITY = 16;
1984
1985 struct GuarderElement {
1986 StackGuard* guard;
1987 const char* name;
1988 const char* func;
1989 int line;
1990 };
1991
1992 static std::vector<GuarderElement> guarders;
1993};
1994std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1995
1996#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1997
1998#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001999void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000{
Ady Abraham8164d482019-01-11 14:47:59 -08002001 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 ATRACE_CALL();
2003 ALOGV("postComposition");
2004
Brian Anderson3546a3f2016-07-14 11:51:14 -07002005 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002006 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002007 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002008 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002009 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002010 }
Ady Abraham8164d482019-01-11 14:47:59 -08002011 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002014 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002015 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016
David Sodman73beded2017-11-15 11:56:06 -08002017 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002019 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2020
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002021 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002024 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 } else {
2026 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2027 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028
Ady Abraham8164d482019-01-11 14:47:59 -08002029 ASSERT_ON_STACK_GUARD();
2030
David Sodman73beded2017-11-15 11:56:06 -08002031 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002032 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002033 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002034 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002035 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002036 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037
Ana Krulece588e312018-09-18 12:32:24 -07002038 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002039 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002040 if (mUseScheduler) {
2041 mScheduler->getDisplayStatInfo(&stats);
2042 } else {
2043 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2044 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2045 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002046
Ady Abraham8164d482019-01-11 14:47:59 -08002047 ASSERT_ON_STACK_GUARD();
2048
David Sodman2b406362017-12-15 13:33:47 -08002049 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 // when we started doing work for this frame, but that should be okay
2051 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002052 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002053 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002054 DEFINE_STACK_GUARD(compositorTiming);
2055
Brian Andersond0010582017-03-07 13:20:31 -08002056 {
David Sodman99974d22017-11-28 12:04:33 -08002057 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002058 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002059 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002060
2061 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002062 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063
Robert Carr2047fae2016-11-28 14:09:09 -08002064 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002065 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2066 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002068 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002069 recordBufferingStats(layer->getName().string(),
2070 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002071 }
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002073 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002074
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002075 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002076 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002077 if (mUseScheduler) {
2078 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002079 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002080 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002081 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2082 enableHardwareVsync();
2083 } else {
2084 disableHardwareVsync(false);
2085 }
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002087 }
2088 }
2089
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002090 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002091 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002092 if (mUseScheduler) {
2093 mScheduler->enableHardwareVsync();
2094 } else {
2095 enableHardwareVsync();
2096 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002097 }
2098 }
2099
Ady Abraham8164d482019-01-11 14:47:59 -08002100 ASSERT_ON_STACK_GUARD();
2101
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 if (mAnimCompositionPending) {
2103 mAnimCompositionPending = false;
2104
Brian Anderson4e606e32017-03-16 15:34:57 -07002105 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002106 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002107 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002108
2109 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002110 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002111 // The HWC doesn't support present fences, so use the refresh
2112 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002113 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002114 DEFINE_STACK_GUARD(presentTime);
2115
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002117 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002118 }
2119 mAnimFrameTracker.advanceFrame();
2120 }
Dan Stozab90cf072015-03-05 11:05:59 -08002121
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
2123
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002124 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002125 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002126 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002127 }
2128
Ady Abraham8164d482019-01-11 14:47:59 -08002129 ASSERT_ON_STACK_GUARD();
2130
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002131 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002132
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
2134
Dominik Laskowski075d3172018-05-24 15:50:06 -07002135 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002136 return;
2137 }
2138
2139 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002140 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002141 if (mHasPoweredOff) {
2142 mHasPoweredOff = false;
2143 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002144 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002146 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002147 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002148 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2149 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002150 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002151 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002152 }
David Sodman4a36e932017-11-07 14:29:47 -08002153 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002154
2155 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002156 }
David Sodman4a36e932017-11-07 14:29:47 -08002157 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002158 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002159
2160 {
2161 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002162 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002163 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002164 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002165 if (refillCount > 0) {
2166 const size_t offset = mTexturePool.size();
2167 mTexturePool.resize(mTexturePoolSize);
2168 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2169 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2170 }
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002172 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002173
Marissa Wallfda30bb2018-10-12 11:34:28 -07002174 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002175 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002176
2177 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002178}
Ady Abraham8164d482019-01-11 14:47:59 -08002179#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002180
2181void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 ATRACE_CALL();
2183 ALOGV("rebuildLayerStacks");
2184
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002185 // We need to clear these out now as these may be holding on to a
2186 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2187 // also holds a reference. When the set of visible layers is recomputed,
2188 // some layers may be destroyed if the only thing keeping them alive was
2189 // that list of visible layers associated with each display. The layer
2190 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2191 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2192 for (const auto& [token, display] : mDisplays) {
2193 getBE().mCompositionInfo[token].clear();
2194 }
2195
Mathias Agopiancd60f992012-08-16 16:28:27 -07002196 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002197 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002198 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002199 mVisibleRegionsDirty = false;
2200 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002201
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002202 for (const auto& pair : mDisplays) {
2203 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 Region opaqueRegion;
2205 Region dirtyRegion;
2206 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002207 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002208 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 const Rect bounds = display->getBounds();
2210 if (display->isPoweredOn()) {
2211 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002212
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002214 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002216 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002217 Region drawRegion(tr.transform(
2218 layer->visibleNonTransparentRegion));
2219 drawRegion.andSelf(bounds);
2220 if (!drawRegion.isEmpty()) {
2221 layersSortedByZ.add(layer);
2222 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002223 // Clear out the HWC layer if this layer was
2224 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002225 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002226 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002227 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002228 // WM changes display->layerStack upon sleep/awake.
2229 // Here we make sure we delete the HWC layers even if
2230 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002231 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002232 }
2233
2234 // If a layer is not going to get a release fence because
2235 // it is invisible, but it is also going to release its
2236 // old buffer, add it to the list of layers needing
2237 // fences.
2238 if (hwcLayerDestroyed) {
2239 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2240 mLayersWithQueuedFrames.cend(), layer);
2241 if (found != mLayersWithQueuedFrames.cend()) {
2242 layersNeedingFences.add(layer);
2243 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002244 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 });
2246 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 display->setVisibleLayersSortedByZ(layersSortedByZ);
2248 display->setLayersNeedingFences(layersNeedingFences);
2249 display->undefinedRegion.set(bounds);
2250 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2251 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002252 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002255
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002256// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002258// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002260// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261// The returned HDR data space is one of
2262// - Dataspace::UNKNOWN
2263// - Dataspace::BT2020_HLG
2264// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2266 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002267 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002268 *outHdrDataSpace = Dataspace::UNKNOWN;
2269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002270 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002271 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 case Dataspace::V0_SCRGB:
2273 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002274 case Dataspace::BT2020:
2275 case Dataspace::BT2020_ITU:
2276 case Dataspace::BT2020_LINEAR:
2277 case Dataspace::DISPLAY_BT2020:
2278 bestDataSpace = Dataspace::DISPLAY_BT2020;
2279 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002280 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002281 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 case Dataspace::BT2020_PQ:
2284 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002285 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002287 case Dataspace::BT2020_HLG:
2288 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002289 // When there's mixed PQ content and HLG content, we set the HDR
2290 // data space to be BT2020_PQ and convert HLG to PQ.
2291 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2292 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002293 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294 break;
2295 default:
2296 break;
2297 }
Romain Guy54f154a2017-10-24 21:40:32 +01002298 }
2299
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002301}
2302
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002304void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2305 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002306 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2307 *outMode = ColorMode::NATIVE;
2308 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002309 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002311 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002312
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002314 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315
Peiyong Lindfde5112018-06-05 10:58:41 -07002316 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002317 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002318 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002319 if (isHdr) {
2320 bestDataSpace = hdrDataSpace;
2321 }
2322
Chia-I Wu0d711262018-05-21 15:19:35 -07002323 RenderIntent intent;
2324 switch (mDisplayColorSetting) {
2325 case DisplayColorSetting::MANAGED:
2326 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002327 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002328 break;
2329 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002330 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002331 break;
2332 default: // vendor display color setting
2333 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2334 break;
2335 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002338}
2339
David Sodmanfa9b2af2017-12-24 13:28:59 -08002340void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002341{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002342 bool dirty = !display->getDirtyRegion(false).isEmpty();
2343 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2344 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002345
David Sodmanfa9b2af2017-12-24 13:28:59 -08002346 // If nothing has changed (!dirty), don't recompose.
2347 // If something changed, but we don't currently have any visible layers,
2348 // and didn't when we last did a composition, then skip it this time.
2349 // The second rule does two things:
2350 // - When all layers are removed from a display, we'll emit one black
2351 // frame, then nothing more until we get new layers.
2352 // - When a display is created with a private layer stack, we won't
2353 // emit any black frames until a layer is added to the layer stack.
2354 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002355
Dominik Laskowski075d3172018-05-24 15:50:06 -07002356 const char flagPrefix[] = {'-', '+'};
2357 static_cast<void>(flagPrefix);
2358 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2359 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2360 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002361
David Sodmanfa9b2af2017-12-24 13:28:59 -08002362 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002363
David Sodmanfa9b2af2017-12-24 13:28:59 -08002364 if (mustRecompose) {
2365 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002366 }
2367}
2368
David Sodmanfa9b2af2017-12-24 13:28:59 -08002369void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002370{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371 if (!display->isPoweredOn()) {
2372 return;
David Sodman2b406362017-12-15 13:33:47 -08002373 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002374
Dominik Laskowski05275f12018-11-01 15:03:24 -07002375 status_t result = display->prepareFrame(getHwComposer(),
2376 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002377 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2378 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002379}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002380
David Sodmanfa9b2af2017-12-24 13:28:59 -08002381void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002382 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 ALOGV("doComposition");
2384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 if (display->isPoweredOn()) {
2386 // transform the dirty region into this screen's coordinate space
2387 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002388
David Sodmanfa9b2af2017-12-24 13:28:59 -08002389 // repaint the framebuffer (if needed)
2390 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392 display->dirtyRegion.clear();
2393 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002394 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002396}
2397
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398void SurfaceFlinger::postFrame()
2399{
2400 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 const auto display = getDefaultDisplayDeviceLocked();
2402 if (display && getHwComposer().isConnected(*display->getId())) {
2403 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002404 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2405 logFrameStats();
2406 }
2407 }
2408}
2409
2410void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411{
Mathias Agopian841cde52012-03-01 15:44:37 -08002412 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002414
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002416
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002418 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 if (displayId) {
2420 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002421 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002422 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002423 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002424 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002425
Chia-I Wu7b549592017-11-15 09:14:57 -08002426 // The layer buffer from the previous frame (if any) is released
2427 // by HWC only when the release fence from this frame (if any) is
2428 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 if (displayId && layer->hasHwcLayer(*displayId)) {
2430 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2431 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002432 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002433
2434 // If the layer was client composited in the previous frame, we
2435 // need to merge with the previous client target acquire fence.
2436 // Since we do not track that, always merge with the current
2437 // client target acquire fence when it is available, even though
2438 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002439 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002440 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002442 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002443
David Sodman15094112018-10-11 09:39:37 -07002444 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 }
Chia-I Wu83806892017-11-16 10:50:20 -08002446
2447 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002449 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002452 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002454 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002455 }
2456 }
2457
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (displayId) {
2459 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002460 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462}
2463
Mathias Agopian87baae12012-07-31 12:38:26 -07002464void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465{
Mathias Agopian841cde52012-03-01 15:44:37 -08002466 ATRACE_CALL();
2467
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002468 // here we keep a copy of the drawing state (that is the state that's
2469 // going to be overwritten by handleTransactionLocked()) outside of
2470 // mStateLock so that the side-effects of the State assignment
2471 // don't happen with mStateLock held (which can cause deadlocks).
2472 State drawingState(mDrawingState);
2473
Mathias Agopianca4d3602011-05-19 15:38:14 -07002474 Mutex::Autolock _l(mStateLock);
2475 const nsecs_t now = systemTime();
2476 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477
Mathias Agopianca4d3602011-05-19 15:38:14 -07002478 // Here we're guaranteed that some transaction flags are set
2479 // so we can call handleTransactionLocked() unconditionally.
2480 // We call getTransactionFlags(), which will also clear the flags,
2481 // with mStateLock held to guarantee that mCurrentState won't change
2482 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002483
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002484 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002485 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002487
Mathias Agopianca4d3602011-05-19 15:38:14 -07002488 mLastTransactionTime = systemTime() - now;
2489 mDebugInTransaction = 0;
2490 invalidateHwcGeometry();
2491 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002492}
2493
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2495 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 const std::optional<DisplayIdentificationInfo> info =
2497 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002500 continue;
2501 }
2502
Lloyd Piqueba04e622017-12-14 17:11:26 -08002503 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002505 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 mPhysicalDisplayTokens[info->id] = new BBinder();
2507 DisplayDeviceState state;
2508 state.displayId = info->id;
2509 state.isSecure = true; // All physical displays are currently considered secure.
2510 state.displayName = info->name;
2511 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2512 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002513 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002515 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002516
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2518 if (index >= 0) {
2519 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2520 mInterceptor->saveDisplayDeletion(state.sequenceId);
2521 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002522 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524 }
2525
2526 processDisplayChangesLocked();
2527 }
2528
2529 mPendingHotplugEvents.clear();
2530}
2531
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2534 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2535 const sp<IGraphicBufferProducer>& producer) {
2536 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002537 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002539 creationArgs.isSecure = state.isSecure;
2540 creationArgs.displaySurface = dispSurface;
2541 creationArgs.hasWideColorGamut = false;
2542 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002543
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2545 creationArgs.isPrimary = isInternalDisplay;
2546
2547 if (useColorManagement && displayId) {
2548 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002550 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002551 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002552 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002553
Dominik Laskowski7e045462018-05-30 13:02:02 -07002554 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 }
tangrobin6753a022018-08-10 10:58:54 +08002558 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 if (displayId) {
2561 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002564 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002565
Lloyd Pique90c115d2018-09-18 21:39:42 -07002566 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002567 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002568 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002569
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570 // Make sure that composition can never be stalled by a virtual display
2571 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002572 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002573 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2575 }
2576
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 creationArgs.displayInstallOrientation =
2578 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002579
Lloyd Pique99d3da52018-01-22 17:48:03 -08002580 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582
Lloyd Pique90c115d2018-09-18 21:39:42 -07002583 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584
2585 if (maxFrameBufferAcquiredBuffers >= 3) {
2586 nativeWindowSurface->preallocateBuffers();
2587 }
2588
2589 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002590 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002591 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002593 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002595 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002596 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 if (!state.isVirtual()) {
2598 LOG_ALWAYS_FATAL_IF(!displayId);
2599 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002600 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 display->setLayerStack(state.layerStack);
2603 display->setProjection(state.orientation, state.viewport, state.frame);
2604 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607}
2608
Lloyd Pique347200f2017-12-14 17:00:15 -08002609void SurfaceFlinger::processDisplayChangesLocked() {
2610 // here we take advantage of Vector's copy-on-write semantics to
2611 // improve performance by skipping the transaction entirely when
2612 // know that the lists are identical
2613 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2614 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2615 if (!curr.isIdenticalTo(draw)) {
2616 mVisibleRegionsDirty = true;
2617 const size_t cc = curr.size();
2618 size_t dc = draw.size();
2619
2620 // find the displays that were removed
2621 // (ie: in drawing state but not in current state)
2622 // also handle displays that changed
2623 // (ie: displays that are in both lists)
2624 for (size_t i = 0; i < dc;) {
2625 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2626 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 // Save display IDs before disconnecting.
2628 const auto internalDisplayId = getInternalDisplayId();
2629 const auto externalDisplayId = getExternalDisplayId();
2630
Lloyd Pique347200f2017-12-14 17:00:15 -08002631 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002632 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2633 display->disconnect(getHwComposer());
2634 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002636 if (mUseScheduler) {
2637 mScheduler->hotplugReceived(mAppConnectionHandle,
2638 EventThread::DisplayType::Primary, false);
2639 } else {
2640 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2641 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002643 if (mUseScheduler) {
2644 mScheduler->hotplugReceived(mAppConnectionHandle,
2645 EventThread::DisplayType::External, false);
2646 } else {
2647 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2648 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002649 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002650 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 } else {
2652 // this display is in both lists. see if something changed.
2653 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2656 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2657 if (state_binder != draw_binder) {
2658 // changing the surface is like destroying and
2659 // recreating the DisplayDevice, so we just remove it
2660 // from the drawing state, so that it get re-added
2661 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2663 display->disconnect(getHwComposer());
2664 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002666 mDrawingState.displays.removeItemsAt(i);
2667 dc--;
2668 // at this point we must loop to the next item
2669 continue;
2670 }
2671
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002675 }
2676 if ((state.orientation != draw[i].orientation) ||
2677 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002679 }
2680 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 }
2683 }
2684 }
2685 ++i;
2686 }
2687
2688 // find displays that were added
2689 // (ie: in current state but not in drawing state)
2690 for (size_t i = 0; i < cc; i++) {
2691 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2692 const DisplayDeviceState& state(curr[i]);
2693
2694 sp<DisplaySurface> dispSurface;
2695 sp<IGraphicBufferProducer> producer;
2696 sp<IGraphicBufferProducer> bqProducer;
2697 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002698 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002699
Dominik Laskowski075d3172018-05-24 15:50:06 -07002700 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002701 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 // Virtual displays without a surface are dormant:
2703 // they have external state (layer stack, projection,
2704 // etc.) but no internal state (i.e. a DisplayDevice).
2705 if (state.surface != nullptr) {
2706 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002707 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 int width = 0;
2709 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2710 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2711 int height = 0;
2712 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2713 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2714 int intFormat = 0;
2715 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2716 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002717 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718
Dominik Laskowski075d3172018-05-24 15:50:06 -07002719 displayId =
2720 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 }
2722
2723 // TODO: Plumb requested format back up to consumer
2724
2725 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002726 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 bqProducer, bqConsumer,
2728 state.displayName);
2729
2730 dispSurface = vds;
2731 producer = vds;
2732 }
2733 } else {
2734 ALOGE_IF(state.surface != nullptr,
2735 "adding a supported display, but rendering "
2736 "surface is provided (%p), ignoring it",
2737 state.surface.get());
2738
Dominik Laskowski075d3172018-05-24 15:50:06 -07002739 displayId = state.displayId;
2740 LOG_ALWAYS_FATAL_IF(!displayId);
2741 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 producer = bqProducer;
2743 }
2744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002747 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002748 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002749 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002750 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 LOG_ALWAYS_FATAL_IF(!displayId);
2752
2753 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002754 if (mUseScheduler) {
2755 mScheduler->hotplugReceived(mAppConnectionHandle,
2756 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002757 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002758 } else {
2759 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2760 true);
2761 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002762 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002763 if (mUseScheduler) {
2764 mScheduler->hotplugReceived(mAppConnectionHandle,
2765 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002766 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002767 } else {
2768 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2769 true);
2770 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002771 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 }
2773 }
2774 }
2775 }
2776 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002777
2778 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002779}
2780
Mathias Agopian87baae12012-07-31 12:38:26 -07002781void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002782{
Dan Stoza7dde5992015-05-22 09:51:44 -07002783 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002784 mCurrentState.traverseInZOrder([](Layer* layer) {
2785 layer->notifyAvailableFrames();
2786 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 /*
2789 * Traversal of the children
2790 * (perform the transaction for each of them if needed)
2791 */
2792
Robert Carr720e5062018-07-30 17:45:14 -07002793 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002794 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002795 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002797 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798
2799 const uint32_t flags = layer->doTransaction(0);
2800 if (flags & Layer::eVisibleRegion)
2801 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002802
2803 if (flags & Layer::eInputInfoChanged) {
2804 inputChanged = true;
2805 }
Robert Carr2047fae2016-11-28 14:09:09 -08002806 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 }
2808
2809 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 */
2812
Mathias Agopiane57f2922012-08-09 16:29:12 -07002813 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002814 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002815 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002818 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002819 // The transform hint might have changed for some layers
2820 // (either because a display has changed, or because a layer
2821 // as changed).
2822 //
2823 // Walk through all the layers in currentLayers,
2824 // and update their transform hint.
2825 //
2826 // If a layer is visible only on a single display, then that
2827 // display is used to calculate the hint, otherwise we use the
2828 // default display.
2829 //
2830 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2831 // the hint is set before we acquire a buffer from the surface texture.
2832 //
2833 // NOTE: layer transactions have taken place already, so we use their
2834 // drawing state. However, SurfaceFlinger's own transaction has not
2835 // happened yet, so we must use the current state layer list
2836 // (soon to become the drawing state list).
2837 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002839 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002840 bool first = true;
2841 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002842 // NOTE: we rely on the fact that layers are sorted by
2843 // layerStack first (so we don't have to traverse the list
2844 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002845 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002846 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002847 currentlayerStack = layerStack;
2848 // figure out if this layerstack is mirrored
2849 // (more than one display) if so, pick the default display,
2850 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 hintDisplay = nullptr;
2852 for (const auto& [token, display] : mDisplays) {
2853 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2854 if (hintDisplay) {
2855 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002856 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002859 }
2860 }
2861 }
2862 }
Chet Haase91d25932013-04-11 15:24:55 -07002863
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002865 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2866 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002867
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002868 // could be null when this layer is using a layerStack
2869 // that is not visible on any display. Also can occur at
2870 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002872 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002873
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002875 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 if (hintDisplay) {
2877 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002878 }
Robert Carr2047fae2016-11-28 14:09:09 -08002879
2880 first = false;
2881 });
Mathias Agopian84300952012-11-21 16:02:13 -08002882 }
2883
2884
Mathias Agopian3559b072012-08-15 13:46:03 -07002885 /*
2886 * Perform our own transaction if needed
2887 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888
2889 if (mLayersAdded) {
2890 mLayersAdded = false;
2891 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 mVisibleRegionsDirty = true;
2893 }
2894
2895 // some layers might have been removed, so
2896 // we need to update the regions they're exposing.
2897 if (mLayersRemoved) {
2898 mLayersRemoved = false;
2899 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002900 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002902 // this layer is not visible anymore
2903 // TODO: we could traverse the tree from front to back and
2904 // compute the actual visible region
2905 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 Region visibleReg;
2907 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002908 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002909 }
Robert Carr2047fae2016-11-28 14:09:09 -08002910 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911 }
2912
2913 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002914
Vishnu Nairde19f852018-12-18 16:11:53 -08002915 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002916 updateInputWindows();
2917 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002918 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002919
Riley Andrews03414a12014-07-01 14:22:59 -07002920 updateCursorAsync();
2921}
2922
Robert Carr720e5062018-07-30 17:45:14 -07002923void SurfaceFlinger::updateInputWindows() {
2924 ATRACE_CALL();
2925
Vishnu Nairde19f852018-12-18 16:11:53 -08002926 if (mInputFlinger == nullptr) {
2927 return;
2928 }
2929
Robert Carr720e5062018-07-30 17:45:14 -07002930 Vector<InputWindowInfo> inputHandles;
2931
2932 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2933 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002934 // When calculating the screen bounds we ignore the transparent region since it may
2935 // result in an unwanted offset.
2936 inputHandles.add(layer->fillInputInfo(
2937 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002938 }
2939 });
2940 mInputFlinger->setInputWindows(inputHandles);
2941}
2942
chaviwfbe5d9c2018-12-26 12:23:37 -08002943void SurfaceFlinger::executeInputWindowCommands() {
2944 if (!mInputFlinger) {
2945 return;
2946 }
2947
2948 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2949 if (transferTouchFocusCommand.fromToken != nullptr &&
2950 transferTouchFocusCommand.toToken != nullptr &&
2951 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2952 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2953 transferTouchFocusCommand.toToken);
2954 }
2955 }
2956
2957 mInputWindowCommands.clear();
2958}
2959
Riley Andrews03414a12014-07-01 14:22:59 -07002960void SurfaceFlinger::updateCursorAsync()
2961{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002962 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002963 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002964 continue;
2965 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002967 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2968 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002969 }
2970 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002971}
2972
chaviw61626f22018-11-15 16:26:27 -08002973void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2974 if (layer->hasReadyFrame()) {
2975 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2976 if (layer->shouldPresentNow(expectedPresentTime)) {
2977 bool ignored = false;
2978 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2979 }
2980 }
2981 layer->releasePendingBuffer(systemTime());
2982}
2983
Mathias Agopian4fec8732012-06-29 14:12:52 -07002984void SurfaceFlinger::commitTransaction()
2985{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002986 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002987 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 for (const auto& l : mLayersPendingRemoval) {
2989 recordBufferingStats(l->getName().string(),
2990 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002991
2992 // We need to release the HWC layers when the Layer is removed
2993 // from the current state otherwise the HWC layer just continues
2994 // showing at its last configured state until we eventually
2995 // abandon the buffer queue.
2996 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002997 l->destroyHwcLayersForAllDisplays();
2998 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 }
3001 mLayersPendingRemoval.clear();
3002 }
3003
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003004 // If this transaction is part of a window animation then the next frame
3005 // we composite should be considered an animation as well.
3006 mAnimCompositionPending = mAnimTransactionPending;
3007
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003009 // clear the "changed" flags in current state
3010 mCurrentState.colorMatrixChanged = false;
3011
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 mDrawingState.traverseInZOrder([](Layer* layer) {
3013 layer->commitChildList();
3014 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003015 mTransactionPending = false;
3016 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003017 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018}
3019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3021 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003022 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025 Region aboveOpaqueLayers;
3026 Region aboveCoveredLayers;
3027 Region dirty;
3028
Mathias Agopian87baae12012-07-31 12:38:26 -07003029 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030
Robert Carr2047fae2016-11-28 14:09:09 -08003031 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003032 // start with the whole surface at its current location
3033 const Layer::State& s(layer->getDrawingState());
3034
Jesse Hall01e29052013-02-19 16:13:35 -08003035 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003037 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003038 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003039
Mathias Agopianab028732010-03-16 16:41:46 -07003040 /*
3041 * opaqueRegion: area of a surface that is fully opaque.
3042 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003044
3045 /*
3046 * visibleRegion: area of a surface that is visible on screen
3047 * and not fully transparent. This is essentially the layer's
3048 * footprint minus the opaque regions above it.
3049 * Areas covered by a translucent surface are considered visible.
3050 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003052
3053 /*
3054 * coveredRegion: area of a surface that is covered by all
3055 * visible regions above it (which includes the translucent areas).
3056 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003058
Jesse Halla8026d22012-09-25 13:25:04 -07003059 /*
3060 * transparentRegion: area of a surface that is hinted to be completely
3061 * transparent. This is only used to tell when the layer has no visible
3062 * non-transparent regions and can be removed from the layer list. It
3063 * does not affect the visibleRegion of this layer or any layers
3064 * beneath it. The hint may not be correct if apps don't respect the
3065 * SurfaceView restrictions (which, sadly, some don't).
3066 */
3067 Region transparentRegion;
3068
Mathias Agopianab028732010-03-16 16:41:46 -07003069
3070 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003071 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003072 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003076 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003077 if (!visibleRegion.isEmpty()) {
3078 // Remove the transparent area from the visible region
3079 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003080 if (tr.preserveRects()) {
3081 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003082 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003083 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003084 // transformation too complex, can't do the
3085 // transparent region optimization.
3086 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003087 }
Mathias Agopianab028732010-03-16 16:41:46 -07003088 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089
Mathias Agopianab028732010-03-16 16:41:46 -07003090 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003092 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003093 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003094 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003095 // the opaque region is the layer's footprint
3096 opaqueRegion = visibleRegion;
3097 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 }
3099 }
3100
Robert Carre5f4f692018-01-12 13:12:28 -08003101 if (visibleRegion.isEmpty()) {
3102 layer->clearVisibilityRegions();
3103 return;
3104 }
3105
Mathias Agopianab028732010-03-16 16:41:46 -07003106 // Clip the covered region to the visible region
3107 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3108
3109 // Update aboveCoveredLayers for next (lower) layer
3110 aboveCoveredLayers.orSelf(visibleRegion);
3111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 // subtract the opaque region covered by the layers above us
3113 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114
3115 // compute this layer's dirty region
3116 if (layer->contentDirty) {
3117 // we need to invalidate the whole region
3118 dirty = visibleRegion;
3119 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003120 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 layer->contentDirty = false;
3122 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003123 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003124 * the exposed region consists of two components:
3125 * 1) what's VISIBLE now and was COVERED before
3126 * 2) what's EXPOSED now less what was EXPOSED before
3127 *
3128 * note that (1) is conservative, we start with the whole
3129 * visible region but only keep what used to be covered by
3130 * something -- which mean it may have been exposed.
3131 *
3132 * (2) handles areas that were not covered by anything but got
3133 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003134 */
Mathias Agopianab028732010-03-16 16:41:46 -07003135 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003136 const Region oldVisibleRegion = layer->visibleRegion;
3137 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003138 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3139 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 }
3141 dirty.subtractSelf(aboveOpaqueLayers);
3142
3143 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003144 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145
Mathias Agopianab028732010-03-16 16:41:46 -07003146 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003148
Jesse Halla8026d22012-09-25 13:25:04 -07003149 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 layer->setVisibleRegion(visibleRegion);
3151 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003152 layer->setVisibleNonTransparentRegion(
3153 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003154 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155
Mathias Agopian87baae12012-07-31 12:38:26 -07003156 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Chia-I Wuab0c3192017-08-01 11:29:00 -07003159void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003160 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003161 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3162 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003163 }
3164 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003165}
3166
Dan Stoza6b9454d2014-11-07 16:00:59 -08003167bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003169 ALOGV("handlePageFlip");
3170
Brian Andersond6927fb2016-07-23 23:37:30 -07003171 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003174 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003175 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003176
3177 // Store the set of layers that need updates. This set must not change as
3178 // buffers are being latched, as this could result in a deadlock.
3179 // Example: Two producers share the same command stream and:
3180 // 1.) Layer 0 is latched
3181 // 2.) Layer 0 gets a new frame
3182 // 2.) Layer 1 gets a new frame
3183 // 3.) Layer 1 is latched.
3184 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3185 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003186 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003187 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003188 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003189 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3190 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003191 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003192 } else {
3193 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003194 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003195 } else {
3196 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003197 }
Robert Carr2047fae2016-11-28 14:09:09 -08003198 });
3199
Lloyd Piquef2c79392018-12-20 16:23:33 -08003200 if (!mLayersWithQueuedFrames.empty()) {
3201 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3202 // writes to Layer current state. See also b/119481871
3203 Mutex::Autolock lock(mStateLock);
3204
3205 for (auto& layer : mLayersWithQueuedFrames) {
3206 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3207 layer->useSurfaceDamage();
3208 invalidateLayerStack(layer, dirty);
3209 if (layer->isBufferLatched()) {
3210 newDataLatched = true;
3211 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003212 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003213 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003214
Alec Mouri86770e52018-09-24 22:40:58 +00003215 // Clear the renderengine fence here...
3216 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3217 // clear instead of sp::clear.
3218 getBE().flushFence = Fence::NO_FENCE;
3219
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003220 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221
Vishnu Nairde19f852018-12-18 16:11:53 -08003222 if (visibleRegions) {
3223 // Update input window info if the layer receives its first buffer.
3224 updateInputWindows();
3225 }
3226
Dan Stoza6b9454d2014-11-07 16:00:59 -08003227 // If we will need to wake up at some time in the future to deal with a
3228 // queued frame that shouldn't be displayed during this vsync period, wake
3229 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003230 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231 signalLayerUpdate();
3232 }
3233
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003234 // enter boot animation on first buffer latch
3235 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3236 ALOGI("Enter boot animation");
3237 mBootStage = BootStage::BOOTANIMATION;
3238 }
3239
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003241 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Mathias Agopianad456f92011-01-13 17:53:01 -08003244void SurfaceFlinger::invalidateHwcGeometry()
3245{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003246 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003247}
3248
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003249void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003250 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003251 // We only need to actually compose the display if:
3252 // 1) It is being handled by hardware composer, which may need this to
3253 // keep its virtual display state machine in sync, or
3254 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003255 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003256 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003257 return;
3258 }
3259
Dan Stoza9e56aa02015-11-02 13:00:03 -08003260 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003261 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003262
3263 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003264 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265}
3266
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003267bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003268 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003270 const Region bounds(display->bounds());
3271 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003272 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003273 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003274 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003275
Peiyong Lind3788632018-09-18 16:01:31 -07003276 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003277 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003278
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003279 // Framebuffer will live in this scope for GPU composition.
3280 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3281
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 if (hasClientComposition) {
3283 ALOGV("hasClientComposition");
3284
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003285 sp<GraphicBuffer> buf = display->dequeueBuffer();
3286
3287 if (buf == nullptr) {
3288 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3289 "client composition for this frame",
3290 display->getDisplayName().c_str());
3291 return false;
3292 }
3293
3294 // Bind the framebuffer in this scope.
3295 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3296 buf->getNativeBuffer());
3297
3298 if (fbo->getStatus() != NO_ERROR) {
3299 ALOGW("Binding buffer for display [%s] failed with status: %d",
3300 display->getDisplayName().c_str(), fbo->getStatus());
3301 return false;
3302 }
3303
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003304 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003305 if (display->hasWideColorGamut()) {
3306 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003307 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003308 getRenderEngine().setOutputDataSpace(outputDataspace);
3309 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003310 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003311
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003313 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003314 getHwComposer()
3315 .hasDisplayCapability(displayId,
3316 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003317
Peiyong Lind3788632018-09-18 16:01:31 -07003318 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003319 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3320 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003321 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003322 }
3323
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003324 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003325
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003326 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003327 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003328 // when using overlays, we assume a fully transparent framebuffer
3329 // NOTE: we could reduce how much we need to clear, for instance
3330 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003331 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003332 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003333 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003334 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003335 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003336 // we're left with the letterbox region
3337 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003338 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003339
3340 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003341 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003342
Mathias Agopianb9494d52012-04-18 02:28:45 -07003343 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003344 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003345 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003346 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003347 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003348 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003349
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003350 const Rect& bounds = display->getBounds();
3351 const Rect& scissor = display->getScissor();
3352 if (scissor != bounds) {
3353 // scissor doesn't match the screen's dimensions, so we
3354 // need to clear everything outside of it and enable
3355 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003356
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003357 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003358 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003359 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003361
Mathias Agopian85d751c2012-08-29 16:59:24 -07003362 /*
3363 * and then, render the layers targeted at the framebuffer
3364 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003365
Dan Stoza9e56aa02015-11-02 13:00:03 -08003366 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003367 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003368 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003369 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003370 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003371 displayTransform.transform(layer->visibleRegion)));
3372 ALOGV("Layer: %s", layer->getName().string());
3373 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003374 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003375 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003376 case HWC2::Composition::Cursor:
3377 case HWC2::Composition::Device:
3378 case HWC2::Composition::Sideband:
3379 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003380 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003382 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003383 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003384 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003385 // never clear the very first layer since we're
3386 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003387 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003388 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003389 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003390 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003391 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003392 if (layer->hasColorTransform()) {
3393 mat4 tmpMatrix;
3394 if (applyColorMatrix) {
3395 tmpMatrix = mDrawingState.colorMatrix;
3396 }
3397 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003398 getRenderEngine().setColorTransform(tmpMatrix);
3399 } else {
3400 getRenderEngine().setColorTransform(colorMatrix);
3401 }
David Sodmanc1498e62018-09-12 14:36:26 -07003402 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003403 break;
3404 }
3405 default:
3406 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003407 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 } else {
3409 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003410 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003412 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003413
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003414 // Perform some cleanup steps if we used client composition.
3415 if (hasClientComposition) {
3416 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003417 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003418 display->finishBuffer();
3419 // Clear out error flags here so that we don't wait until next
3420 // composition to log.
3421 getRenderEngine().checkErrors();
3422 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003423 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424}
3425
Chia-I Wu28e3a252018-09-07 12:05:02 -07003426void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003427 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003428 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003429}
3430
Dan Stoza7d89d062015-04-30 13:29:25 -07003431status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003432 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003433 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003434 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003435 const sp<Layer>& parent,
3436 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003437{
Dan Stoza7d89d062015-04-30 13:29:25 -07003438 // add this layer to the current state list
3439 {
3440 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003441 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003442 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3443 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003444 return NO_MEMORY;
3445 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003446 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003447 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003448 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003449 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003450 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003451 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003452 parent->addChild(lbc);
3453 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003454
Yiwei Zhang243b3782018-05-15 17:40:04 -07003455 if (gbc != nullptr) {
3456 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3457 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3458 mMaxGraphicBufferProducerListSize,
3459 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3460 mGraphicBufferProducerList.size(),
3461 mMaxGraphicBufferProducerListSize, mNumLayers);
3462 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003464 }
3465
Mathias Agopian96f08192010-06-02 23:28:45 -07003466 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003467 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003468
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003470}
3471
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003472uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003473 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003474}
3475
Mathias Agopian3f844832013-08-07 21:24:32 -07003476uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003477 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478}
3479
Mathias Agopian3f844832013-08-07 21:24:32 -07003480uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003481 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003482}
3483
3484uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003485 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003486 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003487 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003489 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490 }
3491 return old;
3492}
3493
Marissa Wall713b63f2018-10-17 15:42:43 -07003494bool SurfaceFlinger::flushTransactionQueues() {
3495 Mutex::Autolock _l(mStateLock);
3496 auto it = mTransactionQueues.begin();
3497 while (it != mTransactionQueues.end()) {
3498 auto& [applyToken, transactionQueue] = *it;
3499
3500 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003501 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3502 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003503 break;
3504 }
chaviw273171b2018-12-26 11:46:30 -08003505 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003506 transactionQueue.pop();
3507 }
3508
3509 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3510 }
3511 return mTransactionQueues.empty();
3512}
3513
chaviwca27f252018-02-06 16:46:39 -08003514bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3515 for (const ComposerState& state : states) {
3516 // Here we need to check that the interface we're given is indeed
3517 // one of our own. A malicious client could give us a nullptr
3518 // IInterface, or one of its own or even one of our own but a
3519 // different type. All these situations would cause us to crash.
3520 if (state.client == nullptr) {
3521 return true;
3522 }
3523
3524 sp<IBinder> binder = IInterface::asBinder(state.client);
3525 if (binder == nullptr) {
3526 return true;
3527 }
3528
3529 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3530 return true;
3531 }
3532 }
3533 return false;
3534}
3535
Marissa Wall17b4e452018-12-26 16:32:34 -08003536bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3537 const Vector<ComposerState>& states) {
3538 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3539 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3540 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3541 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3542 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3543 return false;
3544 }
3545
Marissa Wall713b63f2018-10-17 15:42:43 -07003546 for (const ComposerState& state : states) {
3547 const layer_state_t& s = state.state;
3548 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3549 continue;
3550 }
3551 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003552 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003553 }
3554 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003555 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003556}
3557
3558void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3559 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003560 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003561 const InputWindowCommands& inputWindowCommands,
3562 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003563 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003564 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565
chaviwca27f252018-02-06 16:46:39 -08003566 if (containsAnyInvalidClientState(states)) {
3567 return;
3568 }
3569
Marissa Wall713b63f2018-10-17 15:42:43 -07003570 // If its TransactionQueue already has a pending TransactionState or if it is pending
3571 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003572 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3573 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003574 setTransactionFlags(eTransactionNeeded);
3575 return;
3576 }
3577
chaviw273171b2018-12-26 11:46:30 -08003578 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003579}
3580
3581void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003582 const Vector<DisplayState>& displays, uint32_t flags,
3583 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003584 uint32_t transactionFlags = 0;
3585
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003586 if (flags & eAnimation) {
3587 // For window updates that are part of an animation we must wait for
3588 // previous animation "frames" to be handled.
3589 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003590 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003591 if (CC_UNLIKELY(err != NO_ERROR)) {
3592 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003593 // caller after a few seconds.
3594 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3595 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003596 mAnimTransactionPending = false;
3597 break;
3598 }
3599 }
3600 }
3601
chaviwca27f252018-02-06 16:46:39 -08003602 for (const DisplayState& display : displays) {
3603 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003604 }
3605
Marissa Walle2ffb422018-10-12 11:33:52 -07003606 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003607 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003608 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003609 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003610 // If the state doesn't require a traversal and there are callbacks, send them now
3611 if (!(clientStateFlags & eTraversalNeeded)) {
3612 mTransactionCompletedThread.sendCallbacks();
3613 }
3614 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003615
chaviw273171b2018-12-26 11:46:30 -08003616 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3617
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003618 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3619 // anyway. This can be used as a flush mechanism for previous async transactions.
3620 // Empty animation transaction can be used to simulate back-pressure, so also force a
3621 // transaction for empty animation transactions.
3622 if (transactionFlags == 0 &&
3623 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003624 transactionFlags = eTransactionNeeded;
3625 }
3626
Mathias Agopian386aa982011-11-07 21:58:03 -08003627 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003628 if (mInterceptor->isEnabled()) {
3629 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003630 }
Irvel468051e2016-06-13 16:44:44 -07003631
Mathias Agopian386aa982011-11-07 21:58:03 -08003632 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003633 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3634 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003635 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003636
3637 // if this is a synchronous transaction, wait for it to take effect
3638 // before returning.
3639 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003640 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003641 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003642 if (flags & eAnimation) {
3643 mAnimTransactionPending = true;
3644 }
3645 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003646 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3647 if (CC_UNLIKELY(err != NO_ERROR)) {
3648 // just in case something goes wrong in SF, return to the
3649 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003650 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3651 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003652 break;
3653 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003655 }
3656}
3657
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003658uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3659 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3660 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003661
Mathias Agopiane57f2922012-08-09 16:29:12 -07003662 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003663 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3664
3665 const uint32_t what = s.what;
3666 if (what & DisplayState::eSurfaceChanged) {
3667 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3668 state.surface = s.surface;
3669 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003670 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003671 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003672 if (what & DisplayState::eLayerStackChanged) {
3673 if (state.layerStack != s.layerStack) {
3674 state.layerStack = s.layerStack;
3675 flags |= eDisplayTransactionNeeded;
3676 }
3677 }
3678 if (what & DisplayState::eDisplayProjectionChanged) {
3679 if (state.orientation != s.orientation) {
3680 state.orientation = s.orientation;
3681 flags |= eDisplayTransactionNeeded;
3682 }
3683 if (state.frame != s.frame) {
3684 state.frame = s.frame;
3685 flags |= eDisplayTransactionNeeded;
3686 }
3687 if (state.viewport != s.viewport) {
3688 state.viewport = s.viewport;
3689 flags |= eDisplayTransactionNeeded;
3690 }
3691 }
3692 if (what & DisplayState::eDisplaySizeChanged) {
3693 if (state.width != s.width) {
3694 state.width = s.width;
3695 flags |= eDisplayTransactionNeeded;
3696 }
3697 if (state.height != s.height) {
3698 state.height = s.height;
3699 flags |= eDisplayTransactionNeeded;
3700 }
3701 }
3702
Mathias Agopiane57f2922012-08-09 16:29:12 -07003703 return flags;
3704}
3705
Robert Carrd4ae7f32018-06-07 16:10:57 -07003706bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3707 IPCThreadState* ipc = IPCThreadState::self();
3708 const int pid = ipc->getCallingPid();
3709 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003710 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003711 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003712 return false;
3713 }
3714 return true;
3715}
3716
chaviwca27f252018-02-06 16:46:39 -08003717uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3718 const layer_state_t& s = composerState.state;
3719 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3720
Mathias Agopian13127d82013-03-05 17:47:11 -08003721 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003722 if (layer == nullptr) {
3723 return 0;
3724 }
3725
chaviw8b3871a2017-11-01 17:41:01 -07003726 uint32_t flags = 0;
3727
Garfield Tan8a3083e2018-12-03 13:21:07 -08003728 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003729 bool geometryAppliesWithResize =
3730 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003731
3732 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3733 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003734 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003735 layer->pushPendingState();
3736 }
3737
chaviw8b3871a2017-11-01 17:41:01 -07003738 if (what & layer_state_t::ePositionChanged) {
3739 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3740 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003741 }
chaviw8b3871a2017-11-01 17:41:01 -07003742 }
3743 if (what & layer_state_t::eLayerChanged) {
3744 // NOTE: index needs to be calculated before we update the state
3745 const auto& p = layer->getParent();
3746 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003747 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003748 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003749 mCurrentState.layersSortedByZ.removeAt(idx);
3750 mCurrentState.layersSortedByZ.add(layer);
3751 // we need traversal (state changed)
3752 // AND transaction (list changed)
3753 flags |= eTransactionNeeded|eTraversalNeeded;
3754 }
chaviw8b3871a2017-11-01 17:41:01 -07003755 } else {
3756 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003757 flags |= eTransactionNeeded|eTraversalNeeded;
3758 }
3759 }
chaviw8b3871a2017-11-01 17:41:01 -07003760 }
3761 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003762 // NOTE: index needs to be calculated before we update the state
3763 const auto& p = layer->getParent();
3764 if (p == nullptr) {
3765 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3766 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3767 mCurrentState.layersSortedByZ.removeAt(idx);
3768 mCurrentState.layersSortedByZ.add(layer);
3769 // we need traversal (state changed)
3770 // AND transaction (list changed)
3771 flags |= eTransactionNeeded|eTraversalNeeded;
3772 }
3773 } else {
3774 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3775 flags |= eTransactionNeeded|eTraversalNeeded;
3776 }
chaviw8b3871a2017-11-01 17:41:01 -07003777 }
3778 }
3779 if (what & layer_state_t::eSizeChanged) {
3780 if (layer->setSize(s.w, s.h)) {
3781 flags |= eTraversalNeeded;
3782 }
3783 }
3784 if (what & layer_state_t::eAlphaChanged) {
3785 if (layer->setAlpha(s.alpha))
3786 flags |= eTraversalNeeded;
3787 }
3788 if (what & layer_state_t::eColorChanged) {
3789 if (layer->setColor(s.color))
3790 flags |= eTraversalNeeded;
3791 }
Peiyong Lind3788632018-09-18 16:01:31 -07003792 if (what & layer_state_t::eColorTransformChanged) {
3793 if (layer->setColorTransform(s.colorTransform)) {
3794 flags |= eTraversalNeeded;
3795 }
3796 }
chaviw8b3871a2017-11-01 17:41:01 -07003797 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003798 // TODO: b/109894387
3799 //
3800 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3801 // rotation. To see the problem observe that if we have a square parent, and a child
3802 // of the same size, then we rotate the child 45 degrees around it's center, the child
3803 // must now be cropped to a non rectangular 8 sided region.
3804 //
3805 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3806 // private API, and the WindowManager only uses rotation in one case, which is on a top
3807 // level layer in which cropping is not an issue.
3808 //
3809 // However given that abuse of rotation matrices could lead to surfaces extending outside
3810 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3811 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3812 // transformations.
3813 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003814 flags |= eTraversalNeeded;
3815 }
3816 if (what & layer_state_t::eTransparentRegionChanged) {
3817 if (layer->setTransparentRegionHint(s.transparentRegion))
3818 flags |= eTraversalNeeded;
3819 }
3820 if (what & layer_state_t::eFlagsChanged) {
3821 if (layer->setFlags(s.flags, s.mask))
3822 flags |= eTraversalNeeded;
3823 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003824 if (what & layer_state_t::eCropChanged_legacy) {
3825 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003826 flags |= eTraversalNeeded;
3827 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003828 if (what & layer_state_t::eCornerRadiusChanged) {
3829 if (layer->setCornerRadius(s.cornerRadius))
3830 flags |= eTraversalNeeded;
3831 }
chaviw8b3871a2017-11-01 17:41:01 -07003832 if (what & layer_state_t::eLayerStackChanged) {
3833 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3834 // We only allow setting layer stacks for top level layers,
3835 // everything else inherits layer stack from its parent.
3836 if (layer->hasParent()) {
3837 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3838 layer->getName().string());
3839 } else if (idx < 0) {
3840 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3841 "that also does not appear in the top level layer list. Something"
3842 " has gone wrong.", layer->getName().string());
3843 } else if (layer->setLayerStack(s.layerStack)) {
3844 mCurrentState.layersSortedByZ.removeAt(idx);
3845 mCurrentState.layersSortedByZ.add(layer);
3846 // we need traversal (state changed)
3847 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003848 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003849 }
3850 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003851 if (what & layer_state_t::eDeferTransaction_legacy) {
3852 if (s.barrierHandle_legacy != nullptr) {
3853 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3854 } else if (s.barrierGbp_legacy != nullptr) {
3855 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003856 if (authenticateSurfaceTextureLocked(gbp)) {
3857 const auto& otherLayer =
3858 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003859 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003860 } else {
3861 ALOGE("Attempt to defer transaction to to an"
3862 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003863 }
3864 }
chaviw8b3871a2017-11-01 17:41:01 -07003865 // We don't trigger a traversal here because if no other state is
3866 // changed, we don't want this to cause any more work
3867 }
3868 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003869 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003870 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003871 if (!hadParent) {
3872 mCurrentState.layersSortedByZ.remove(layer);
3873 }
chaviw8b3871a2017-11-01 17:41:01 -07003874 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003875 }
chaviw8b3871a2017-11-01 17:41:01 -07003876 }
3877 if (what & layer_state_t::eReparentChildren) {
3878 if (layer->reparentChildren(s.reparentHandle)) {
3879 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003880 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003881 }
chaviw8b3871a2017-11-01 17:41:01 -07003882 if (what & layer_state_t::eDetachChildren) {
3883 layer->detachChildren();
3884 }
3885 if (what & layer_state_t::eOverrideScalingModeChanged) {
3886 layer->setOverrideScalingMode(s.overrideScalingMode);
3887 // We don't trigger a traversal here because if no other state is
3888 // changed, we don't want this to cause any more work
3889 }
Marissa Wall61c58622018-07-18 10:12:20 -07003890 if (what & layer_state_t::eTransformChanged) {
3891 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3892 }
3893 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3894 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3895 flags |= eTraversalNeeded;
3896 }
3897 if (what & layer_state_t::eCropChanged) {
3898 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3899 }
Marissa Wall861616d2018-10-22 12:52:23 -07003900 if (what & layer_state_t::eFrameChanged) {
3901 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3902 }
Marissa Wall61c58622018-07-18 10:12:20 -07003903 if (what & layer_state_t::eBufferChanged) {
3904 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3905 }
3906 if (what & layer_state_t::eAcquireFenceChanged) {
3907 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3908 }
3909 if (what & layer_state_t::eDataspaceChanged) {
3910 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3911 }
3912 if (what & layer_state_t::eHdrMetadataChanged) {
3913 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3914 }
3915 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3916 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3917 }
3918 if (what & layer_state_t::eApiChanged) {
3919 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eSidebandStreamChanged) {
3922 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3923 }
Robert Carr720e5062018-07-30 17:45:14 -07003924 if (what & layer_state_t::eInputInfoChanged) {
3925 layer->setInputInfo(s.inputInfo);
3926 flags |= eTraversalNeeded;
3927 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003928 std::vector<sp<CallbackHandle>> callbackHandles;
3929 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3930 mTransactionCompletedThread.run();
3931 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3932 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3933 }
3934 }
3935 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3936 // Do not put anything that updates layer state or modifies flags after
3937 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003938 return flags;
3939}
3940
chaviw273171b2018-12-26 11:46:30 -08003941uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3942 uint32_t flags = 0;
3943 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3944 flags |= eTraversalNeeded;
3945 }
3946
3947 mInputWindowCommands.merge(inputWindowCommands);
3948 return flags;
3949}
3950
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003951status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003952 const String8& name,
3953 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003955 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003956 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003957{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003958 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003959 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003960 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003961 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003962 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003963
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003964 status_t result = NO_ERROR;
3965
3966 sp<Layer> layer;
3967
Cody Northropbc755282017-03-31 12:00:08 -06003968 String8 uniqueName = getUniqueLayerName(name);
3969
Mathias Agopian3165cc22012-08-08 19:42:09 -07003970 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003971 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003972 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3973 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003974
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003975 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003976 case ISurfaceComposerClient::eFXSurfaceBufferState:
3977 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3978 break;
chaviw13fdc492017-06-27 12:40:18 -07003979 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003980 // check if buffer size is set for color layer.
3981 if (w > 0 || h > 0) {
3982 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3983 int(w), int(h));
3984 return BAD_VALUE;
3985 }
3986
chaviw13fdc492017-06-27 12:40:18 -07003987 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003988 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003989 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003991 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003992 // check if buffer size is set for container layer.
3993 if (w > 0 || h > 0) {
3994 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3995 int(w), int(h));
3996 return BAD_VALUE;
3997 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003998 result = createContainerLayer(client,
3999 uniqueName, w, h, flags,
4000 handle, &layer);
4001 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004002 default:
4003 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 break;
4005 }
4006
Dan Stoza7d89d062015-04-30 13:29:25 -07004007 if (result != NO_ERROR) {
4008 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004010
Chia-I Wuab0c3192017-08-01 11:29:00 -07004011 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4012 // TODO b/64227542
4013 if (windowType == 441731) {
4014 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4015 layer->setPrimaryDisplayOnly();
4016 }
4017
Albert Chaulk479c60c2017-01-27 14:21:34 -05004018 layer->setInfo(windowType, ownerUid);
4019
Robert Carrb89ea9d2018-12-10 13:01:14 -08004020 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4021 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4022 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004023 if (result != NO_ERROR) {
4024 return result;
4025 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004026 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004027
4028 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004029 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004030}
4031
Cody Northropbc755282017-03-31 12:00:08 -06004032String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4033{
4034 bool matchFound = true;
4035 uint32_t dupeCounter = 0;
4036
4037 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4038 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4039
Dan Stoza436ccf32018-06-21 12:10:12 -07004040 // Grab the state lock since we're accessing mCurrentState
4041 Mutex::Autolock lock(mStateLock);
4042
Cody Northropbc755282017-03-31 12:00:08 -06004043 // Loop over layers until we're sure there is no matching name
4044 while (matchFound) {
4045 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004046 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004047 if (layer->getName() == uniqueName) {
4048 matchFound = true;
4049 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4050 }
4051 });
4052 }
4053
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004054 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4055 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004056
4057 return uniqueName;
4058}
4059
Marissa Wallfd668622018-05-10 10:21:13 -07004060status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4061 uint32_t w, uint32_t h, uint32_t flags,
4062 PixelFormat& format, sp<IBinder>* handle,
4063 sp<IGraphicBufferProducer>* gbp,
4064 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004065 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004066 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 case PIXEL_FORMAT_TRANSPARENT:
4068 case PIXEL_FORMAT_TRANSLUCENT:
4069 format = PIXEL_FORMAT_RGBA_8888;
4070 break;
4071 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004072 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 break;
4074 }
4075
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004076 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004077 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004078 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004079 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004080 *handle = layer->getHandle();
4081 *gbp = layer->getProducer();
4082 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004084
Marissa Wallfd668622018-05-10 10:21:13 -07004085 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004086 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087}
4088
Marissa Wall61c58622018-07-18 10:12:20 -07004089status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4090 uint32_t w, uint32_t h, uint32_t flags,
4091 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004092 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004093 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004094 *handle = layer->getHandle();
4095 *outLayer = layer;
4096
4097 return NO_ERROR;
4098}
4099
chaviw13fdc492017-06-27 12:40:18 -07004100status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004101 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004102 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004104 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004105 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004107}
4108
Robert Carr6b3f6c52018-08-13 13:05:17 -07004109status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4110 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4111 sp<IBinder>* handle, sp<Layer>* outLayer)
4112{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004113 *outLayer =
4114 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004115 *handle = (*outLayer)->getHandle();
4116 return NO_ERROR;
4117}
4118
4119
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004120void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004121 mLayersPendingRemoval.add(layer);
4122 mLayersRemoved = true;
4123 setTransactionFlags(eTransactionNeeded);
4124}
4125
Robert Carr695d5282018-12-18 15:27:58 -08004126void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004127{
Robert Carr2e102c92018-10-23 12:11:15 -07004128 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004129 // If a layer has a parent, we allow it to out-live it's handle
4130 // with the idea that the parent holds a reference and will eventually
4131 // be cleaned up. However no one cleans up the top-level so we do so
4132 // here.
4133 if (layer->getParent() == nullptr) {
4134 mCurrentState.layersSortedByZ.remove(layer);
4135 }
4136 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004137 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004138}
4139
Mathias Agopianb60314a2012-04-10 22:09:54 -07004140// ---------------------------------------------------------------------------
4141
Andy McFadden13a082e2012-08-24 10:16:42 -07004142void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004143 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004144 if (!displayToken) return;
4145
Jesse Hall01e29052013-02-19 16:13:35 -08004146 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004147 Vector<ComposerState> state;
4148 Vector<DisplayState> displays;
4149 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004150 d.what = DisplayState::eDisplayProjectionChanged |
4151 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004152 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004153 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004154 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004155 d.frame.makeInvalid();
4156 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004157 d.width = 0;
4158 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004159 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004160 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004161
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004162 const auto display = getDisplayDevice(displayToken);
4163 if (!display) return;
4164
Dominik Laskowskie9774092018-12-11 10:04:24 -08004165 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004166
Dominik Laskowski075d3172018-05-24 15:50:06 -07004167 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004168 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004169 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004170
Brian Andersond0010582017-03-07 13:20:31 -08004171 // Use phase of 0 since phase is not known.
4172 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004173 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4174 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004175}
4176
4177void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004178 // Async since we may be called from the main thread.
4179 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004180}
4181
Dominik Laskowskie9774092018-12-11 10:04:24 -08004182void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004183 if (display->isVirtual()) {
4184 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004185 return;
4186 }
4187
Dominik Laskowski075d3172018-05-24 15:50:06 -07004188 const auto displayId = display->getId();
4189 LOG_ALWAYS_FATAL_IF(!displayId);
4190
Dominik Laskowski34157762018-10-31 13:07:19 -07004191 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004192
4193 int currentMode = display->getPowerMode();
4194 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004195 return;
4196 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004197
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004198 display->setPowerMode(mode);
4199
Lloyd Pique4dccc412018-01-22 17:21:36 -08004200 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004201 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004202 }
4203
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004204 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004205 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004206 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004207 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004208 if (mUseScheduler) {
4209 mScheduler->onScreenAcquired(mAppConnectionHandle);
4210 } else {
4211 mEventThread->onScreenAcquired();
4212 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004213 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004214 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004215
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004216 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004217 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004218 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004219
4220 struct sched_param param = {0};
4221 param.sched_priority = 1;
4222 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4223 ALOGW("Couldn't set SCHED_FIFO on display on");
4224 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004225 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004226 // Turn off the display
4227 struct sched_param param = {0};
4228 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4229 ALOGW("Couldn't set SCHED_OTHER on display off");
4230 }
4231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004232 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004233 if (mUseScheduler) {
4234 mScheduler->disableHardwareVsync(true);
4235 } else {
4236 disableHardwareVsync(true); // also cancels any in-progress resync
4237 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004238 if (mUseScheduler) {
4239 mScheduler->onScreenReleased(mAppConnectionHandle);
4240 } else {
4241 mEventThread->onScreenReleased();
4242 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004243 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004244
Dominik Laskowski075d3172018-05-24 15:50:06 -07004245 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004246 mVisibleRegionsDirty = true;
4247 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004248 } else if (mode == HWC_POWER_MODE_DOZE ||
4249 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004250 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004253 if (mUseScheduler) {
4254 mScheduler->onScreenAcquired(mAppConnectionHandle);
4255 } else {
4256 mEventThread->onScreenAcquired();
4257 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004258 resyncToHardwareVsync(true);
4259 }
4260 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4261 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004262 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004263 if (mUseScheduler) {
4264 mScheduler->disableHardwareVsync(true);
4265 } else {
4266 disableHardwareVsync(true); // also cancels any in-progress resync
4267 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004268 if (mUseScheduler) {
4269 mScheduler->onScreenReleased(mAppConnectionHandle);
4270 } else {
4271 mEventThread->onScreenReleased();
4272 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004273 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004275 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004276 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004278 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004280 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004281 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004282 }
4283
Dominik Laskowski34157762018-10-31 13:07:19 -07004284 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004285}
4286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004287void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004288 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 const auto display = getDisplayDevice(displayToken);
4290 if (!display) {
4291 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4292 displayToken.get());
4293 } else if (display->isVirtual()) {
4294 ALOGW("Attempt to set power mode %d for virtual display", mode);
4295 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004296 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004299}
4300
4301// ---------------------------------------------------------------------------
4302
Lloyd Pique755e3192018-01-31 16:46:15 -08004303status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4304 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004305 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004306
Mathias Agopianbd115332013-04-18 16:41:04 -07004307 IPCThreadState* ipc = IPCThreadState::self();
4308 const int pid = ipc->getCallingPid();
4309 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004310
Mathias Agopianbd115332013-04-18 16:41:04 -07004311 if ((uid != AID_SHELL) &&
4312 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4314 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004315 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004316 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004317 // (this would indicate SF is stuck, but we want to be able to
4318 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004319 status_t err = mStateLock.timedLock(s2ns(1));
4320 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004321 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004322 StringAppendF(&result,
4323 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4324 "(no locks held)\n",
4325 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004326 }
4327
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 bool dumpAll = true;
4329 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004330 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004331
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004332 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004333 if ((index < numArgs) &&
4334 (args[index] == String16("--list"))) {
4335 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004336 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004337 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004338 }
4339
4340 if ((index < numArgs) &&
4341 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004343 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004344 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004346
4347 if ((index < numArgs) &&
4348 (args[index] == String16("--latency-clear"))) {
4349 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004351 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004352 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004353
4354 if ((index < numArgs) &&
4355 (args[index] == String16("--dispsync"))) {
4356 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004357 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004358 dumpAll = false;
4359 }
Dan Stozab90cf072015-03-05 11:05:59 -08004360
4361 if ((index < numArgs) &&
4362 (args[index] == String16("--static-screen"))) {
4363 index++;
4364 dumpStaticScreenStats(result);
4365 dumpAll = false;
4366 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004367
4368 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004369 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004370 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004371 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004372 dumpAll = false;
4373 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004374
4375 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4376 index++;
4377 dumpWideColorInfo(result);
4378 dumpAll = false;
4379 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004380
4381 if ((index < numArgs) &&
4382 (args[index] == String16("--enable-layer-stats"))) {
4383 index++;
4384 mLayerStats.enable();
4385 dumpAll = false;
4386 }
4387
4388 if ((index < numArgs) &&
4389 (args[index] == String16("--disable-layer-stats"))) {
4390 index++;
4391 mLayerStats.disable();
4392 dumpAll = false;
4393 }
4394
4395 if ((index < numArgs) &&
4396 (args[index] == String16("--clear-layer-stats"))) {
4397 index++;
4398 mLayerStats.clear();
4399 dumpAll = false;
4400 }
4401
4402 if ((index < numArgs) &&
4403 (args[index] == String16("--dump-layer-stats"))) {
4404 index++;
4405 mLayerStats.dump(result);
4406 dumpAll = false;
4407 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004408
4409 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004410 (args[index] == String16("--frame-composition"))) {
4411 index++;
4412 dumpFrameCompositionInfo(result);
4413 dumpAll = false;
4414 }
4415
4416 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004417 (args[index] == String16("--display-identification"))) {
4418 index++;
4419 dumpDisplayIdentificationData(result);
4420 dumpAll = false;
4421 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004422
4423 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4424 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004425 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004426 dumpAll = false;
4427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004428 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004429
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004430 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004431 if (asProto) {
4432 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4433 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4434 } else {
4435 dumpAllLocked(args, index, result);
4436 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004437 }
4438
Mathias Agopian9795c422009-08-26 16:36:26 -07004439 if (locked) {
4440 mStateLock.unlock();
4441 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004442 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004444 return NO_ERROR;
4445}
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4448 std::string& result) const {
4449 mCurrentState.traverseInZOrder(
4450 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004451}
4452
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004453void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004454 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004455 String8 name;
4456 if (index < args.size()) {
4457 name = String8(args[index]);
4458 index++;
4459 }
4460
Dominik Laskowski075d3172018-05-24 15:50:06 -07004461 if (const auto displayId = getInternalDisplayId();
4462 displayId && getHwComposer().isConnected(*displayId)) {
4463 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004464 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004466 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004467
4468 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004469 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004470 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004471 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004472 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004473 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004474 }
Robert Carr2047fae2016-11-28 14:09:09 -08004475 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004476 }
4477}
4478
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004479void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004481 String8 name;
4482 if (index < args.size()) {
4483 name = String8(args[index]);
4484 index++;
4485 }
4486
Robert Carr2047fae2016-11-28 14:09:09 -08004487 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004488 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004489 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004490 }
Robert Carr2047fae2016-11-28 14:09:09 -08004491 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004492
Svetoslavd85084b2014-03-20 10:28:31 -07004493 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004494}
4495
Jamie Gennis6547ff42013-07-16 20:12:42 -07004496// This should only be called from the main thread. Otherwise it would need
4497// the lock and should use mCurrentState rather than mDrawingState.
4498void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004499 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004500 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004501 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004502
4503 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4504}
4505
Yiwei Zhang5434a782018-12-05 18:06:32 -08004506void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004507 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004508
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004509 if (isLayerTripleBufferingDisabled())
4510 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004511
Yiwei Zhang5434a782018-12-05 18:06:32 -08004512 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4513 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4514 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4515 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4516 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4517 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004518 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004519}
4520
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4522 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004523 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4524 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004525 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004526 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004527 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004528 }
David Sodman4a36e932017-11-07 14:29:47 -08004529 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004530 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004531 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4533 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004534}
4535
Dan Stozae77c7662016-05-13 11:37:28 -07004536void SurfaceFlinger::recordBufferingStats(const char* layerName,
4537 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004538 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4539 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004540 for (const auto& segment : history) {
4541 if (!segment.usedThirdBuffer) {
4542 stats.twoBufferTime += segment.totalTime;
4543 }
4544 if (segment.occupancyAverage < 1.0f) {
4545 stats.doubleBufferedTime += segment.totalTime;
4546 } else if (segment.occupancyAverage < 2.0f) {
4547 stats.tripleBufferedTime += segment.totalTime;
4548 }
4549 ++stats.numSegments;
4550 stats.totalTime += segment.totalTime;
4551 }
4552}
4553
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4555 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004556
4557 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4558 const size_t count = currentLayers.size();
4559 for (size_t i=0 ; i<count ; i++) {
4560 currentLayers[i]->dumpFrameEvents(result);
4561 }
4562}
4563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004565 result.append("Buffering stats:\n");
4566 result.append(" [Layer name] <Active time> <Two buffer> "
4567 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004568 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004569 typedef std::tuple<std::string, float, float, float> BufferTuple;
4570 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004571 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004572 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004573 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004574 if (stats.numSegments == 0) {
4575 continue;
4576 }
4577 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4578 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4579 stats.totalTime;
4580 float doubleBufferRatio = static_cast<float>(
4581 stats.doubleBufferedTime) / stats.totalTime;
4582 float tripleBufferRatio = static_cast<float>(
4583 stats.tripleBufferedTime) / stats.totalTime;
4584 sorted.insert({activeTime, {name, twoBufferRatio,
4585 doubleBufferRatio, tripleBufferRatio}});
4586 }
4587 for (const auto& sortedPair : sorted) {
4588 float activeTime = sortedPair.first;
4589 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4591 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004592 }
4593 result.append("\n");
4594}
4595
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004597 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004598 const auto displayId = display->getId();
4599 if (!displayId) {
4600 continue;
4601 }
4602 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004603 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004604 continue;
4605 }
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result,
4608 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4609 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004610 uint8_t port;
4611 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004612 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004613 result.append("no identification data\n");
4614 continue;
4615 }
4616
4617 if (!isEdid(data)) {
4618 result.append("unknown identification data: ");
4619 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 }
4622 result.append("\n");
4623 continue;
4624 }
4625
4626 const auto edid = parseEdid(data);
4627 if (!edid) {
4628 result.append("invalid EDID: ");
4629 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004631 }
4632 result.append("\n");
4633 continue;
4634 }
4635
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004637 result.append(edid->displayName.data(), edid->displayName.length());
4638 result.append("\"\n");
4639 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640}
4641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4643 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4644 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4645 StringAppendF(&result, "DisplayColorSetting: %s\n",
4646 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004647
4648 // TODO: print out if wide-color mode is active or not
4649
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004650 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004651 const auto displayId = display->getId();
4652 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004653 continue;
4654 }
4655
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004657 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004658 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004660 }
4661
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004662 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, " Current color mode: %s (%d)\n",
4664 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004665 }
4666 result.append("\n");
4667}
4668
Yiwei Zhang5434a782018-12-05 18:06:32 -08004669void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004670 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004671 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4672 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004673 continue;
4674 }
4675
Dominik Laskowski05275f12018-11-01 15:03:24 -07004676 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4678 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004679 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 compositionInfo.dump(result, nullptr);
4681 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004682 }
4683 }
David Sodman7e4ae112018-02-09 15:02:28 -08004684}
4685
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004686LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004687 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004688 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4689 const State& state = useDrawing ? mDrawingState : mCurrentState;
4690 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004691 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004692 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004693 });
4694
4695 return layersProto;
4696}
4697
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004698LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004699 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004700
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004701 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004702 resolution->set_w(display.getWidth());
4703 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004705 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4706 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4707 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004708
Dominik Laskowski075d3172018-05-24 15:50:06 -07004709 const auto displayId = display.getId();
4710 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004711 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004712 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004713 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004714 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004715 }
4716 });
4717
4718 return layersProto;
4719}
4720
Mathias Agopian74d211a2013-04-22 16:55:35 +02004721void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 bool colorize = false;
4724 if (index < args.size()
4725 && (args[index] == String16("--color"))) {
4726 colorize = true;
4727 index++;
4728 }
4729
4730 Colorizer colorizer(colorize);
4731
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732 // figure out if we're stuck somewhere
4733 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004735 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4736
4737 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004738 * Dump library configuration.
4739 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004740
4741 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004742 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004743 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004744 appendSfConfigString(result);
4745 appendUiConfigString(result);
4746 appendGuiConfigString(result);
4747 result.append("\n");
4748
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004749 result.append("\nDisplay identification data:\n");
4750 dumpDisplayIdentificationData(result);
4751
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004752 result.append("\nWide-Color information:\n");
4753 dumpWideColorInfo(result);
4754
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004755 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004756 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004757 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004758 result.append(SyncFeatures::getInstance().toString());
4759 result.append("\n");
4760
Andy McFadden41d67d72014-04-25 16:58:34 -07004761 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004762 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004763 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004764
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004765 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4766 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004767 if (const auto displayId = getInternalDisplayId();
4768 displayId && getHwComposer().isConnected(*displayId)) {
4769 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770 StringAppendF(&result,
4771 "Display %s: app phase %" PRId64 " ns, "
4772 "sf phase %" PRId64 " ns, "
4773 "early app phase %" PRId64 " ns, "
4774 "early sf phase %" PRId64 " ns, "
4775 "early app gl phase %" PRId64 " ns, "
4776 "early sf gl phase %" PRId64 " ns, "
4777 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4778 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4779 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4780 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004781 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004782 result.append("\n");
4783
Dan Stozab90cf072015-03-05 11:05:59 -08004784 // Dump static screen stats
4785 result.append("\n");
4786 dumpStaticScreenStats(result);
4787 result.append("\n");
4788
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004790
Dan Stozae77c7662016-05-13 11:37:28 -07004791 dumpBufferingStats(result);
4792
Andy McFadden4803b742012-09-24 19:07:20 -07004793 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794 * Dump the visible layer list
4795 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004796 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004797 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4798 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4799 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004800 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004801
Chia-I Wu2f884132018-09-13 15:17:58 -07004802 {
4803 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4804 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004806 result.append("\n");
4807 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808
David Sodman7e4ae112018-02-09 15:02:28 -08004809 result.append("\nFrame-Composition information:\n");
4810 dumpFrameCompositionInfo(result);
4811 result.append("\n");
4812
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004813 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004814 * Dump Display state
4815 */
4816
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004817 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004819 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004820 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004821 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004822 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004823 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004824
4825 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004826 * Dump SurfaceFlinger global state
4827 */
4828
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004829 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004830 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004831 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004833 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004834
Dominik Laskowski075d3172018-05-24 15:50:06 -07004835 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004836 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4838 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004839 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004840 StringAppendF(&result,
4841 " transaction-flags : %08x\n"
4842 " gpu_to_cpu_unsupported : %d\n",
4843 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844
Dominik Laskowski075d3172018-05-24 15:50:06 -07004845 if (const auto displayId = getInternalDisplayId();
4846 displayId && getHwComposer().isConnected(*displayId)) {
4847 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 StringAppendF(&result,
4849 " refresh-rate : %f fps\n"
4850 " x-dpi : %f\n"
4851 " y-dpi : %f\n",
4852 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4853 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004854 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004855
Yiwei Zhang5434a782018-12-05 18:06:32 -08004856 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004857
Yiwei Zhang5434a782018-12-05 18:06:32 -08004858 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004859 /*
4860 * VSYNC state
4861 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004862 if (mUseScheduler) {
4863 mScheduler->dump(mAppConnectionHandle, result);
4864 } else {
4865 mEventThread->dump(result);
4866 }
Dan Stozae22aec72016-08-01 13:20:59 -07004867 result.append("\n");
4868
4869 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004870 * Tracing state
4871 */
4872 mTracing.dump(result);
4873 result.append("\n");
4874
4875 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004876 * HWC layer minidump
4877 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004878 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004879 const auto displayId = display->getId();
4880 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004881 continue;
4882 }
4883
Yiwei Zhang5434a782018-12-05 18:06:32 -08004884 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004885 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004887 result.append("\n");
4888 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889
4890 /*
4891 * Dump HWComposer state
4892 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004893 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004894 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004895 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004896 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004897 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004898 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004899
4900 /*
4901 * Dump gralloc state
4902 */
4903 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4904 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004905
4906 /*
4907 * Dump VrFlinger state if in use.
4908 */
4909 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4910 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004911 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004912 result.append("\n");
4913 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004914}
4915
Dominik Laskowski075d3172018-05-24 15:50:06 -07004916const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004917 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004918 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004919 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004920 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004921 }
4922 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004923
Dominik Laskowski34157762018-10-31 13:07:19 -07004924 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004925 static const Vector<sp<Layer>> empty;
4926 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004927}
4928
Keun young Park63f165f2012-08-31 10:53:36 -07004929bool SurfaceFlinger::startDdmConnection()
4930{
4931 void* libddmconnection_dso =
4932 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4933 if (!libddmconnection_dso) {
4934 return false;
4935 }
4936 void (*DdmConnection_start)(const char* name);
4937 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004938 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004939 if (!DdmConnection_start) {
4940 dlclose(libddmconnection_dso);
4941 return false;
4942 }
4943 (*DdmConnection_start)(getServiceName());
4944 return true;
4945}
4946
Chia-I Wu28f320b2018-05-03 11:02:56 -07004947void SurfaceFlinger::updateColorMatrixLocked() {
4948 mat4 colorMatrix;
4949 if (mGlobalSaturationFactor != 1.0f) {
4950 // Rec.709 luma coefficients
4951 float3 luminance{0.213f, 0.715f, 0.072f};
4952 luminance *= 1.0f - mGlobalSaturationFactor;
4953 mat4 saturationMatrix = mat4(
4954 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4955 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4956 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4957 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4958 );
4959 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4960 } else {
4961 colorMatrix = mClientColorMatrix * mDaltonizer();
4962 }
4963
4964 if (mCurrentState.colorMatrix != colorMatrix) {
4965 mCurrentState.colorMatrix = colorMatrix;
4966 mCurrentState.colorMatrixChanged = true;
4967 setTransactionFlags(eTransactionNeeded);
4968 }
4969}
4970
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004971status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972#pragma clang diagnostic push
4973#pragma clang diagnostic error "-Wswitch-enum"
4974 switch (static_cast<ISurfaceComposerTag>(code)) {
4975 // These methods should at minimum make sure that the client requested
4976 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004977 case BOOT_FINISHED:
4978 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979 case CREATE_DISPLAY:
4980 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004981 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004982 case GET_ACTIVE_COLOR_MODE:
4983 case GET_ANIMATION_FRAME_STATS:
4984 case GET_HDR_CAPABILITIES:
4985 case SET_ACTIVE_CONFIG:
4986 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004987 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004988 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004989 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004990 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4991 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004992 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4993 IPCThreadState* ipc = IPCThreadState::self();
4994 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4995 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004996 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 }
Robert Carr1db73f62016-12-21 12:58:51 -08004998 return OK;
4999 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005001 IPCThreadState* ipc = IPCThreadState::self();
5002 const int pid = ipc->getCallingPid();
5003 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5005 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005006 return PERMISSION_DENIED;
5007 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005010 // Used by apps to hook Choreographer to SurfaceFlinger.
5011 case CREATE_DISPLAY_EVENT_CONNECTION:
5012 // The following calls are currently used by clients that do not
5013 // request necessary permissions. However, they do not expose any secret
5014 // information, so it is OK to pass them.
5015 case AUTHENTICATE_SURFACE:
5016 case GET_ACTIVE_CONFIG:
5017 case GET_BUILT_IN_DISPLAY:
5018 case GET_DISPLAY_COLOR_MODES:
5019 case GET_DISPLAY_CONFIGS:
5020 case GET_DISPLAY_STATS:
5021 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5022 // Calling setTransactionState is safe, because you need to have been
5023 // granted a reference to Client* and Handle* to do anything with it.
5024 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005025 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005026 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005027 case GET_COMPOSITION_PREFERENCE:
5028 case GET_PROTECTED_CONTENT_SUPPORT: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005029 return OK;
5030 }
5031 case CAPTURE_LAYERS:
5032 case CAPTURE_SCREEN: {
5033 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005034 IPCThreadState* ipc = IPCThreadState::self();
5035 const int pid = ipc->getCallingPid();
5036 const int uid = ipc->getCallingUid();
5037 if ((uid != AID_GRAPHICS) &&
5038 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5039 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5040 return PERMISSION_DENIED;
5041 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005042 return OK;
5043 }
5044 // The following codes are deprecated and should never be allowed to access SF.
5045 case CONNECT_DISPLAY_UNUSED:
5046 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5047 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5048 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051
5052 // These codes are used for the IBinder protocol to either interrogate the recipient
5053 // side of the transaction for its canonical interface descriptor or to dump its state.
5054 // We let them pass by default.
5055 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5056 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5057 code == IBinder::SYSPROPS_TRANSACTION) {
5058 return OK;
5059 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005060 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005061 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005062 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005063 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5064 return OK;
5065 }
5066 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5067 return PERMISSION_DENIED;
5068#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005069}
5070
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5072 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005073 status_t credentialCheck = CheckTransactCodeCredentials(code);
5074 if (credentialCheck != OK) {
5075 return credentialCheck;
5076 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005077
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005078 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5079 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005080 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005081 IPCThreadState* ipc = IPCThreadState::self();
5082 const int uid = ipc->getCallingUid();
5083 if (CC_UNLIKELY(uid != AID_SYSTEM
5084 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005085 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005086 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005087 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005088 return PERMISSION_DENIED;
5089 }
5090 int n;
5091 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005092 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005093 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 return NO_ERROR;
5095 case 1002: // SHOW_UPDATES
5096 n = data.readInt32();
5097 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005098 invalidateHwcGeometry();
5099 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005102 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005103 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005104 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005105 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005106 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005107 setTransactionFlags(
5108 eTransactionNeeded|
5109 eDisplayTransactionNeeded|
5110 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005111 return NO_ERROR;
5112 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005113 case 1006:{ // send empty update
5114 signalRefresh();
5115 return NO_ERROR;
5116 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005117 case 1008: // toggle use of hw composer
5118 n = data.readInt32();
5119 mDebugDisableHWC = n ? 1 : 0;
5120 invalidateHwcGeometry();
5121 repaintEverything();
5122 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005123 case 1009: // toggle use of transform hint
5124 n = data.readInt32();
5125 mDebugDisableTransformHint = n ? 1 : 0;
5126 invalidateHwcGeometry();
5127 repaintEverything();
5128 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005129 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005130 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005131 reply->writeInt32(0);
5132 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005133 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005134 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005135 return NO_ERROR;
5136 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005137 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005138 if (!display) {
5139 return NAME_NOT_FOUND;
5140 }
5141
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005142 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005143 return NO_ERROR;
5144 }
5145 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005146 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005147 // daltonize
5148 n = data.readInt32();
5149 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005150 case 1:
5151 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5152 break;
5153 case 2:
5154 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5155 break;
5156 case 3:
5157 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5158 break;
5159 default:
5160 mDaltonizer.setType(ColorBlindnessType::None);
5161 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005162 }
5163 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005164 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005165 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005166 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005167 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005168
5169 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005170 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005171 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005173 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005174 // apply a color matrix
5175 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005176 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005177 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005178 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005179 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005180 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005181 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005183 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005184 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005185 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005186
5187 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5188 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005189 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005190 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5191 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5192 }
5193
Chia-I Wu28f320b2018-05-03 11:02:56 -07005194 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005195 return NO_ERROR;
5196 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005197 // This is an experimental interface
5198 // Needs to be shifted to proper binder interface when we productize
5199 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005200 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005201 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005202 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005203 return NO_ERROR;
5204 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005205 case 1017: {
5206 n = data.readInt32();
5207 mForceFullDamage = static_cast<bool>(n);
5208 return NO_ERROR;
5209 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005210 case 1018: { // Modify Choreographer's phase offset
5211 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005212 if (mUseScheduler) {
5213 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5214 } else {
5215 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5216 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005217 return NO_ERROR;
5218 }
5219 case 1019: { // Modify SurfaceFlinger's phase offset
5220 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005221 if (mUseScheduler) {
5222 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5223 } else {
5224 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5225 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005226 return NO_ERROR;
5227 }
Irvel468051e2016-06-13 16:44:44 -07005228 case 1020: { // Layer updates interceptor
5229 n = data.readInt32();
5230 if (n) {
5231 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005232 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005233 }
5234 else{
5235 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005236 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005237 }
5238 return NO_ERROR;
5239 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005240 case 1021: { // Disable HWC virtual displays
5241 n = data.readInt32();
5242 mUseHwcVirtualDisplays = !n;
5243 return NO_ERROR;
5244 }
Romain Guy0147a172017-06-01 13:53:56 -07005245 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005246 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005247 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005248
Chia-I Wu28f320b2018-05-03 11:02:56 -07005249 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005250 return NO_ERROR;
5251 }
Romain Guy54f154a2017-10-24 21:40:32 +01005252 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005253 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005254 invalidateHwcGeometry();
5255 repaintEverything();
5256 return NO_ERROR;
5257 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005258 // Deprecate, use 1030 to check whether the device is color managed.
5259 case 1024: {
5260 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005261 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005262 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005263 n = data.readInt32();
5264 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005265 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005266 mTracing.enable();
5267 doTracing("tracing.enable");
5268 reply->writeInt32(NO_ERROR);
5269 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005270 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005271 status_t err = mTracing.disable();
5272 reply->writeInt32(err);
5273 }
5274 return NO_ERROR;
5275 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005276 case 1026: { // Get layer tracing status
5277 reply->writeBool(mTracing.isEnabled());
5278 return NO_ERROR;
5279 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005280 // Is a DisplayColorSetting supported?
5281 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005282 const auto display = getDefaultDisplayDevice();
5283 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005284 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005285 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005286
5287 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5288 switch (setting) {
5289 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005290 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005291 break;
5292 case DisplayColorSetting::UNMANAGED:
5293 reply->writeBool(true);
5294 break;
5295 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005296 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005297 break;
5298 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005299 reply->writeBool(
5300 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005301 break;
5302 }
5303 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005304 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005305 // Is VrFlinger active?
5306 case 1028: {
5307 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005308 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005309 return NO_ERROR;
5310 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005311 // Is device color managed?
5312 case 1030: {
5313 reply->writeBool(useColorManagement);
5314 return NO_ERROR;
5315 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005316 // Override default composition data space
5317 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5318 // && adb shell stop zygote && adb shell start zygote
5319 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5320 // adb shell stop zygote && adb shell start zygote
5321 case 1031: {
5322 Mutex::Autolock _l(mStateLock);
5323 n = data.readInt32();
5324 if (n) {
5325 n = data.readInt32();
5326 if (n) {
5327 Dataspace dataspace = static_cast<Dataspace>(n);
5328 if (!validateCompositionDataspace(dataspace)) {
5329 return BAD_VALUE;
5330 }
5331 mDefaultCompositionDataspace = dataspace;
5332 }
5333 n = data.readInt32();
5334 if (n) {
5335 Dataspace dataspace = static_cast<Dataspace>(n);
5336 if (!validateCompositionDataspace(dataspace)) {
5337 return BAD_VALUE;
5338 }
5339 mWideColorGamutCompositionDataspace = dataspace;
5340 }
5341 } else {
5342 // restore composition data space.
5343 mDefaultCompositionDataspace = defaultCompositionDataspace;
5344 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5345 }
5346 return NO_ERROR;
5347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005348 }
5349 }
5350 return err;
5351}
5352
Steven Thomas6d8110b2017-08-31 18:24:21 -07005353void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005354 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005355 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005356}
5357
Ana Krulec7d1d6832018-12-27 11:10:09 -08005358void SurfaceFlinger::repaintEverythingForHWC() {
5359 mRepaintEverything = true;
5360 mEventQueue->invalidateForHWC();
5361}
5362
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005363// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5364class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005365public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005366 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5367 ~WindowDisconnector() {
5368 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005369 }
5370
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005371private:
5372 ANativeWindow* mWindow;
5373 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005374};
5375
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005376status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005377 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5378 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005379 uint32_t reqWidth, uint32_t reqHeight,
5380 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005381 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005382 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005383
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005384 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005385
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005386 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5387
Chia-I Wu20261cb2018-08-23 12:55:44 -07005388 sp<DisplayDevice> display;
5389 {
5390 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005391
Chia-I Wu20261cb2018-08-23 12:55:44 -07005392 display = getDisplayDeviceLocked(displayToken);
5393 if (!display) return BAD_VALUE;
5394
Chia-I Wucb023152018-08-28 12:57:23 -07005395 // set the requested width/height to the logical display viewport size
5396 // by default
5397 if (reqWidth == 0 || reqHeight == 0) {
5398 reqWidth = uint32_t(display->getViewport().width());
5399 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005400 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005401 }
5402
Peiyong Lin0e003c92018-09-17 11:09:51 -07005403 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5404 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005405
5406 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005407 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005408 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5409 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005410}
5411
5412status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005413 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5414 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005415 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005416 ATRACE_CALL();
5417
5418 class LayerRenderArea : public RenderArea {
5419 public:
Robert Carr578038f2018-03-09 12:25:24 -08005420 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005421 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5422 bool childrenOnly)
5423 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005424 mLayer(layer),
5425 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005426 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005427 mFlinger(flinger),
5428 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005429 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005430 Rect getBounds() const override {
5431 const Layer::State& layerState(mLayer->getDrawingState());
5432 return mLayer->getBufferSize(layerState);
5433 }
Marissa Wall61c58622018-07-18 10:12:20 -07005434 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005435 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005436 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005437 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005438 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005439 }
chaviwa76b2712017-09-20 12:02:26 -07005440 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005441 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005442 Rect getSourceCrop() const override {
5443 if (mCrop.isEmpty()) {
5444 return getBounds();
5445 } else {
5446 return mCrop;
5447 }
5448 }
Robert Carr578038f2018-03-09 12:25:24 -08005449 class ReparentForDrawing {
5450 public:
5451 const sp<Layer>& oldParent;
5452 const sp<Layer>& newParent;
5453
5454 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5455 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005456 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005457 }
Robert Carr15eae092018-03-23 13:43:53 -07005458 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005459 };
5460
5461 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005462 const Rect sourceCrop = getSourceCrop();
5463 // no need to check rotation because there is none
5464 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5465 sourceCrop.height() != getReqHeight();
5466
Robert Carr578038f2018-03-09 12:25:24 -08005467 if (!mChildrenOnly) {
5468 mTransform = mLayer->getTransform().inverse();
5469 drawLayers();
5470 } else {
5471 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005472 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005473 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5474 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005475
5476 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5477 drawLayers();
5478 }
5479 }
chaviwa76b2712017-09-20 12:02:26 -07005480
chaviwa76b2712017-09-20 12:02:26 -07005481 private:
chaviw7206d492017-11-10 16:16:12 -08005482 const sp<Layer> mLayer;
5483 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005484
5485 // In the "childrenOnly" case we reparent the children to a screenshot
5486 // layer which has no properties set and which does not draw.
5487 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005488 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005489 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005490
5491 SurfaceFlinger* mFlinger;
5492 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005493 };
5494
5495 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5496 auto parent = layerHandle->owner.promote();
5497
Robert Carr2e102c92018-10-23 12:11:15 -07005498 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005499 ALOGE("captureLayers called with a removed parent");
5500 return NAME_NOT_FOUND;
5501 }
5502
Robert Carr578038f2018-03-09 12:25:24 -08005503 const int uid = IPCThreadState::self()->getCallingUid();
5504 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005505 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005506 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5507 return PERMISSION_DENIED;
5508 }
5509
chaviw7206d492017-11-10 16:16:12 -08005510 Rect crop(sourceCrop);
5511 if (sourceCrop.width() <= 0) {
5512 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005513 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005514 }
5515
5516 if (sourceCrop.height() <= 0) {
5517 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005518 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005519 }
5520
5521 int32_t reqWidth = crop.width() * frameScale;
5522 int32_t reqHeight = crop.height() * frameScale;
5523
Chia-I Wu20261cb2018-08-23 12:55:44 -07005524 // really small crop or frameScale
5525 if (reqWidth <= 0) {
5526 reqWidth = 1;
5527 }
5528 if (reqHeight <= 0) {
5529 reqHeight = 1;
5530 }
5531
Peiyong Lin0e003c92018-09-17 11:09:51 -07005532 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005533
Robert Carr578038f2018-03-09 12:25:24 -08005534 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005535 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5536 if (!layer->isVisible()) {
5537 return;
Robert Carr578038f2018-03-09 12:25:24 -08005538 } else if (childrenOnly && layer == parent.get()) {
5539 return;
chaviwa76b2712017-09-20 12:02:26 -07005540 }
5541 visitor(layer);
5542 });
5543 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005544 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005545}
5546
5547status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5548 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005549 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005550 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005551 bool useIdentityTransform) {
5552 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005553
Peiyong Lin0e003c92018-09-17 11:09:51 -07005554 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005555 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5556 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005557 *outBuffer =
5558 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5559 static_cast<android_pixel_format>(reqPixelFormat), 1,
5560 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005561
5562 // This mutex protects syncFd and captureResult for communication of the return values from the
5563 // main thread back to this Binder thread
5564 std::mutex captureMutex;
5565 std::condition_variable captureCondition;
5566 std::unique_lock<std::mutex> captureLock(captureMutex);
5567 int syncFd = -1;
5568 std::optional<status_t> captureResult;
5569
Robert Carr03480e22018-01-04 16:02:06 -08005570 const int uid = IPCThreadState::self()->getCallingUid();
5571 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5572
Dominik Laskowski8c001672018-05-30 16:52:06 -07005573 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005574 // If there is a refresh pending, bug out early and tell the binder thread to try again
5575 // after the refresh.
5576 if (mRefreshPending) {
5577 ATRACE_NAME("Skipping screenshot for now");
5578 std::unique_lock<std::mutex> captureLock(captureMutex);
5579 captureResult = std::make_optional<status_t>(EAGAIN);
5580 captureCondition.notify_one();
5581 return;
5582 }
5583
5584 status_t result = NO_ERROR;
5585 int fd = -1;
5586 {
5587 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005588 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005589 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5590 useIdentityTransform, forSystem, &fd);
5591 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005592 }
5593
5594 {
5595 std::unique_lock<std::mutex> captureLock(captureMutex);
5596 syncFd = fd;
5597 captureResult = std::make_optional<status_t>(result);
5598 captureCondition.notify_one();
5599 }
5600 });
5601
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005602 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005604 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605 while (*captureResult == EAGAIN) {
5606 captureResult.reset();
5607 result = postMessageAsync(message);
5608 if (result != NO_ERROR) {
5609 return result;
5610 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005611 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 }
5613 result = *captureResult;
5614 }
5615
5616 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005617 sync_wait(syncFd, -1);
5618 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005619 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005620
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005621 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005622}
5623
chaviwa76b2712017-09-20 12:02:26 -07005624void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005625 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005626 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005627 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005628
Lloyd Pique144e1162017-12-20 16:44:52 -08005629 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005630
chaviwa76b2712017-09-20 12:02:26 -07005631 const auto reqWidth = renderArea.getReqWidth();
5632 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005633 const auto sourceCrop = renderArea.getSourceCrop();
5634 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005635
Peiyong Lin0e003c92018-09-17 11:09:51 -07005636 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005637 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005638
Mathias Agopian180f10d2013-04-10 22:55:41 -07005639 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005640 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005641
5642 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005643 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005644 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005645
chaviw50da5042018-04-09 13:49:37 -07005646 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005647 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005648 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005649
chaviwa76b2712017-09-20 12:02:26 -07005650 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005651 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005652 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005653 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005654 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005655}
5656
chaviwa76b2712017-09-20 12:02:26 -07005657status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5658 TraverseLayersFunction traverseLayers,
5659 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005660 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005661 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005662 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005663 ATRACE_CALL();
5664
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005665 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005666
5667 traverseLayers([&](Layer* layer) {
5668 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5669 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005670
Robert Carr03480e22018-01-04 16:02:06 -08005671 // We allow the system server to take screenshots of secure layers for
5672 // use in situations like the Screen-rotation animation and place
5673 // the impetus on WindowManager to not persist them.
5674 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005675 ALOGW("FB is protected: PERMISSION_DENIED");
5676 return PERMISSION_DENIED;
5677 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005678 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005679
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005680 // this binds the given EGLImage as a framebuffer for the
5681 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005682 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005683 if (bufferBond.getStatus() != NO_ERROR) {
5684 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005685 return INVALID_OPERATION;
5686 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005687
Dan Stozaabcda352017-06-01 14:37:39 -07005688 // this will in fact render into our dequeued buffer
5689 // via an FBO, which means we didn't have to create
5690 // an EGLSurface and therefore we're not
5691 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005692 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005693
Peiyong Linfb530cf2018-12-15 05:07:38 +00005694 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005695 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005696 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005697 }
Alec Mouri492bc572018-09-11 21:40:04 +00005698 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005699
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005700 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005701}
5702
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005703// ---------------------------------------------------------------------------
5704
Dan Stoza412903f2017-04-27 13:42:17 -07005705void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5706 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005707}
5708
Dan Stoza412903f2017-04-27 13:42:17 -07005709void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5710 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005711}
5712
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005713void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005714 const LayerVector::Visitor& visitor) {
5715 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005716 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005717 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005718 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005719 continue;
5720 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005721 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005722 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005723 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005724 return;
5725 }
chaviwa76b2712017-09-20 12:02:26 -07005726 if (!layer->isVisible()) {
5727 return;
5728 }
5729 visitor(layer);
5730 });
5731 }
5732}
5733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005734}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005735
Lloyd Pique074e8122018-07-26 12:57:23 -07005736
Mathias Agopian3f844832013-08-07 21:24:32 -07005737#if defined(__gl_h_)
5738#error "don't include gl/gl.h in this file"
5739#endif
5740
5741#if defined(__gl2_h_)
5742#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005743#endif