blob: c6297439b95827b4fa427b18d8ad5ace941beb73 [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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080045#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080049#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080050#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080051#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <ui/ColorSpace.h>
55#include <ui/DebugUtils.h>
56#include <ui/DisplayInfo.h>
57#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <ui/GraphicBufferAllocator.h>
59#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070060#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080061#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <utils/String16.h>
64#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070065#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080066#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070070#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Robert Carr578038f2018-03-09 12:25:24 -080072#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070073#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070074#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080079#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070082#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080083#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070084#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070085#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Steven Thomasb02664d2017-07-26 18:48:28 -070089#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070090#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070091#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070092#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070093#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070094#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070096#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/EventControlThread.h"
98#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070099#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700100#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700101#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800102#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700105
David Sodman7e4ae112018-02-09 15:02:28 -0800106#include "android-base/stringprintf.h"
107
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800109#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700110#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900112#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
chaviw1d044282017-09-27 12:19:28 -0700114#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900115#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700116
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700118
Jaesoo Lee43518572017-01-23 19:03:16 +0900119using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800122using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700123using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700124using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800125using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700126using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700127using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128
Steven Thomasb02664d2017-07-26 18:48:28 -0700129namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700130
131#pragma clang diagnostic push
132#pragma clang diagnostic error "-Wswitch-enum"
133
134bool isWideColorMode(const ColorMode colorMode) {
135 switch (colorMode) {
136 case ColorMode::DISPLAY_P3:
137 case ColorMode::ADOBE_RGB:
138 case ColorMode::DCI_P3:
139 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700140 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700141 case ColorMode::BT2100_PQ:
142 case ColorMode::BT2100_HLG:
143 return true;
144 case ColorMode::NATIVE:
145 case ColorMode::STANDARD_BT601_625:
146 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
147 case ColorMode::STANDARD_BT601_525:
148 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
149 case ColorMode::STANDARD_BT709:
150 case ColorMode::SRGB:
151 return false;
152 }
153 return false;
154}
155
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700156ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
157 switch (rotation) {
158 case ISurfaceComposer::eRotateNone:
159 return ui::Transform::ROT_0;
160 case ISurfaceComposer::eRotate90:
161 return ui::Transform::ROT_90;
162 case ISurfaceComposer::eRotate180:
163 return ui::Transform::ROT_180;
164 case ISurfaceComposer::eRotate270:
165 return ui::Transform::ROT_270;
166 }
167 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
168 return ui::Transform::ROT_0;
169}
170
Peiyong Linfca547f2018-07-09 13:03:33 -0700171#pragma clang diagnostic pop
172
Steven Thomasb02664d2017-07-26 18:48:28 -0700173class ConditionalLock {
174public:
175 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
176 if (lock) {
177 mMutex.lock();
178 }
179 }
180 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
181private:
182 Mutex& mMutex;
183 bool mLocked;
184};
Peiyong Linfca547f2018-07-09 13:03:33 -0700185
Peiyong Lin9d846a52018-11-05 13:18:20 -0800186// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
187bool validateCompositionDataspace(Dataspace dataspace) {
188 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
189}
190
Steven Thomasb02664d2017-07-26 18:48:28 -0700191} // namespace anonymous
192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193// ---------------------------------------------------------------------------
194
Mathias Agopian99b49842011-06-27 16:05:52 -0700195const String16 sHardwareTest("android.permission.HARDWARE_TEST");
196const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
197const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
198const String16 sDump("android.permission.DUMP");
199
Daniel Solomon42d04562019-01-20 21:03:19 -0800200constexpr float kSrgbRedX = 0.4123f;
201constexpr float kSrgbRedY = 0.2126f;
202constexpr float kSrgbRedZ = 0.0193f;
203constexpr float kSrgbGreenX = 0.3576f;
204constexpr float kSrgbGreenY = 0.7152f;
205constexpr float kSrgbGreenZ = 0.1192f;
206constexpr float kSrgbBlueX = 0.1805f;
207constexpr float kSrgbBlueY = 0.0722f;
208constexpr float kSrgbBlueZ = 0.9506f;
209constexpr float kSrgbWhiteX = 0.9505f;
210constexpr float kSrgbWhiteY = 1.0000f;
211constexpr float kSrgbWhiteZ = 1.0891f;
212
Mathias Agopian99b49842011-06-27 16:05:52 -0700213// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800214int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
215int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700216int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700217bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800219bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800220bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800221int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700223int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700230
Kalle Raitaa099a242017-01-11 11:17:29 -0800231std::string getHwcServiceName() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.hwc_service_name", value, "default");
234 ALOGI("Using HWComposer service: '%s'", value);
235 return std::string(value);
236}
237
238bool useTrebleTestingOverride() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.treble_testing_override", value, "false");
241 ALOGI("Treble testing override: '%s'", value);
242 return std::string(value) == "true";
243}
244
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
246 switch(displayColorSetting) {
247 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700252 return std::string("Enhanced");
253 default:
254 return std::string("Unknown ") +
255 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257}
258
David Sodmanbc815282017-11-05 18:57:52 -0800259SurfaceFlingerBE::SurfaceFlingerBE()
260 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800261 mFrameBuckets(),
262 mTotalTime(0),
263 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800264 mComposerSequenceId(0) {
265}
266
Lloyd Pique90c115d2018-09-18 21:39:42 -0700267SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
268 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800269 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700271 mTransactionPending(false),
272 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700273 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700274 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800277 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800278 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800279 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700281 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700282 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700283 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700284 mDebugInTransaction(0),
285 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700286 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800287 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700288 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700289 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800290 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800291 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700293 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700294 mMainThreadId(std::this_thread::get_id()),
295 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800296
Lloyd Pique90c115d2018-09-18 21:39:42 -0700297SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
298 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800299 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 vsyncPhaseOffsetNs = vsync_event_phase_offset_ns(1000000);
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 sfVsyncPhaseOffsetNs = vsync_sf_event_phase_offset_ns(1000000);
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800312
Steven Thomas050b2c82017-03-06 11:45:16 -0800313 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600321
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 mDefaultCompositionDataspace =
323 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
324 mWideColorGamutCompositionDataspace =
325 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
326 defaultCompositionDataspace = mDefaultCompositionDataspace;
327 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
328 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
329 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
330 wideColorGamutCompositionPixelFormat =
331 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700332
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900333 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800334
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900335 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
336 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
337 switch (tmpPrimaryDisplayOrientation) {
338 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800352
Lloyd Pique90c115d2018-09-18 21:39:42 -0700353 mPrimaryDispSync =
354 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
355 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700356
Daniel Solomon42d04562019-01-20 21:03:19 -0800357 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
358 if (surfaceFlingerConfigsServiceV1_2) {
359 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
360 [&](auto tmpPrimaries) {
361 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
362 });
363 } else {
364 initDefaultDisplayNativePrimaries();
365 }
366
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800367 // debugging stuff...
368 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700369
Mathias Agopianb4b17302013-03-20 18:36:41 -0700370 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700371 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700372
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800373 property_get("debug.sf.showupdates", value, "0");
374 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700375
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700376 property_get("debug.sf.ddms", value, "0");
377 mDebugDDMS = atoi(value);
378 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700379 if (!startDdmConnection()) {
380 // start failed, and DDMS debugging not enabled
381 mDebugDDMS = 0;
382 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700383 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700384 ALOGI_IF(mDebugRegion, "showupdates enabled");
385 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700386
387 property_get("debug.sf.disable_backpressure", value, "0");
388 mPropagateBackpressure = !atoi(value);
389 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700390
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800391 property_get("debug.sf.enable_hwc_vds", value, "0");
392 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800393 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800395 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800396 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800397 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700398
Yiwei Zhang243b3782018-05-15 17:40:04 -0700399 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700400 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
401 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
402
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200403 property_get("debug.sf.early_phase_offset_ns", value, "-1");
404 const int earlySfOffsetNs = atoi(value);
405
406 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
407 const int earlyGlSfOffsetNs = atoi(value);
408
409 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
410 const int earlyAppOffsetNs = atoi(value);
411
412 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
413 const int earlyGlAppOffsetNs = atoi(value);
414
Ana Krulec98b5b242018-08-10 15:03:23 -0700415 property_get("debug.sf.use_scheduler", value, "0");
416 mUseScheduler = atoi(value);
417
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200418 const VSyncModulator::Offsets earlyOffsets =
419 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
420 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
421 const VSyncModulator::Offsets earlyGlOffsets =
422 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
423 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
424 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
425 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700426
Romain Guy11d63f42017-07-20 12:47:14 -0700427 // We should be reading 'persist.sys.sf.color_saturation' here
428 // but since /data may be encrypted, we need to wait until after vold
429 // comes online to attempt to read the property. The property is
430 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800431
432 if (useTrebleTestingOverride()) {
433 // Without the override SurfaceFlinger cannot connect to HIDL
434 // services that are not listed in the manifests. Considered
435 // deriving the setting from the set service name, but it
436 // would be brittle if the name that's not 'default' is used
437 // for production purposes later on.
438 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
439 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440}
441
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442void SurfaceFlinger::onFirstRef()
443{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800444 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445}
446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447SurfaceFlinger::~SurfaceFlinger()
448{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449}
450
Dan Stozac7014012014-02-14 15:03:43 -0800451void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800452{
453 // the window manager died on us. prepare its eulogy.
454
Andy McFadden13a082e2012-08-24 10:16:42 -0700455 // restore initial conditions (default device unblank, etc)
456 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457
458 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700459 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800460}
461
Robert Carr1db73f62016-12-21 12:58:51 -0800462static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700463 status_t err = client->initCheck();
464 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800465 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800466 }
Robert Carr1db73f62016-12-21 12:58:51 -0800467 return nullptr;
468}
469
470sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
471 return initClient(new Client(this));
472}
473
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700474sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
475 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476{
477 class DisplayToken : public BBinder {
478 sp<SurfaceFlinger> flinger;
479 virtual ~DisplayToken() {
480 // no more references, this display must be terminated
481 Mutex::Autolock _l(flinger->mStateLock);
482 flinger->mCurrentState.displays.removeItem(this);
483 flinger->setTransactionFlags(eDisplayTransactionNeeded);
484 }
485 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700486 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487 : flinger(flinger) {
488 }
489 };
490
491 sp<BBinder> token = new DisplayToken(this);
492
493 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 // Display ID is assigned when virtual display is allocated by HWC.
495 DisplayDeviceState state;
496 state.isSecure = secure;
497 state.displayName = displayName;
498 mCurrentState.displays.add(token, state);
499 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 return token;
501}
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 Mutex::Autolock _l(mStateLock);
505
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
507 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700508 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 return;
510 }
511
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
513 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 ALOGE("destroyDisplay called for non-virtual display");
515 return;
516 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 mInterceptor->saveDisplayDeletion(state.sequenceId);
518 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 setTransactionFlags(eDisplayTransactionNeeded);
520}
521
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 std::optional<DisplayId> displayId;
524
525 if (id == HWC_DISPLAY_PRIMARY) {
526 displayId = getInternalDisplayId();
527 } else if (id == HWC_DISPLAY_EXTERNAL) {
528 displayId = getExternalDisplayId();
529 }
530
531 if (!displayId) {
532 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800533 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535
536 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700537}
538
Ady Abraham37965d42018-11-01 13:43:32 -0700539status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
540 if (!outGetColorManagement) {
541 return BAD_VALUE;
542 }
543 *outGetColorManagement = useColorManagement;
544 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700545}
546
Lloyd Pique441d5042018-10-18 16:49:51 -0700547HWComposer& SurfaceFlinger::getHwComposer() const {
548 return mCompositionEngine->getHwComposer();
549}
550
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700551renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
552 return mCompositionEngine->getRenderEngine();
553}
554
Lloyd Pique70d91362018-10-18 16:02:55 -0700555compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
556 return *mCompositionEngine.get();
557}
558
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800559void SurfaceFlinger::bootFinished()
560{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700561 if (mStartPropertySetThread->join() != NO_ERROR) {
562 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800563 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800564 const nsecs_t now = systemTime();
565 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000566 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567
568 // wait patiently for the window manager death
569 const String16 name("window");
570 sp<IBinder> window(defaultServiceManager()->getService(name));
571 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700572 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573 }
Robert Carr720e5062018-07-30 17:45:14 -0700574 sp<IBinder> input(defaultServiceManager()->getService(
575 String16("inputflinger")));
576 if (input == nullptr) {
577 ALOGE("Failed to link to input service");
578 } else {
579 mInputFlinger = interface_cast<IInputFlinger>(input);
580 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700581
Steven Thomas050b2c82017-03-06 11:45:16 -0800582 if (mVrFlinger) {
583 mVrFlinger->OnBootFinished();
584 }
585
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700586 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700587 // formerly we would just kill the process, but we now ask it to exit so it
588 // can choose where to stop the animation.
589 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700590
591 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
592 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
593 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700594
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800595 postMessageAsync(new LambdaMessage([this] {
596 readPersistentProperties();
597 mBootStage = BootStage::FINISHED;
598 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800599}
600
Dan Stoza436ccf32018-06-21 12:10:12 -0700601uint32_t SurfaceFlinger::getNewTexture() {
602 {
603 std::lock_guard lock(mTexturePoolMutex);
604 if (!mTexturePool.empty()) {
605 uint32_t name = mTexturePool.back();
606 mTexturePool.pop_back();
607 ATRACE_INT("TexturePoolSize", mTexturePool.size());
608 return name;
609 }
610
611 // The pool was too small, so increase it for the future
612 ++mTexturePoolSize;
613 }
614
615 // The pool was empty, so we need to get a new texture name directly using a
616 // blocking call to the main thread
617 uint32_t name = 0;
618 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
619 return name;
620}
621
Mathias Agopian3f844832013-08-07 21:24:32 -0700622void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700623 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700624}
625
Wei Wangf9b05ee2017-07-19 20:59:39 -0700626// Do not call property_set on main thread which will be blocked by init
627// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700629 ALOGI( "SurfaceFlinger's main thread ready to run. "
630 "Initializing graphics H/W...");
631
Thierry Strudel2924d012017-08-14 15:19:37 -0700632 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800635
Dominik Laskowski83b88212018-12-11 13:34:06 -0800636 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700640 mScheduler = getFactory().createScheduler([this](bool enabled) {
641 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
642 });
643
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700645 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800646 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 impl::EventThread::InterceptVSyncsCallback());
648 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700649 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800650 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 mInterceptor->saveVSyncEvent(timestamp);
652 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800653
Ana Krulec98b5b242018-08-10 15:03:23 -0700654 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700655 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
656 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 } else {
658 mEventThreadSource =
659 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
660 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
661 mEventThread =
662 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700663 impl::EventThread::InterceptVSyncsCallback(),
664 "appEventThread");
665 mSfEventThreadSource =
666 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
667 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
668
669 mSFEventThread =
670 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700671 [this](nsecs_t timestamp) {
672 mInterceptor->saveVSyncEvent(timestamp);
673 },
674 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800675 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700676 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
677 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678
Steven Thomasb02664d2017-07-26 18:48:28 -0700679 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700680 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700681 renderEngineFeature |= (useColorManagement ?
682 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700683 renderEngineFeature |= (useContextPriority ?
684 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700685
686 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700687 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700688 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700689 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700690
691 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
692 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700693 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
694 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800695 // Process any initial hotplug and resulting display changes.
696 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 const auto display = getDefaultDisplayDeviceLocked();
698 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700699 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700700 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800701
Steven Thomas050b2c82017-03-06 11:45:16 -0800702 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700703 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700704 // This callback is called from the vr flinger dispatch thread. We
705 // need to call signalTransaction(), which requires holding
706 // mStateLock when we're not on the main thread. Acquiring
707 // mStateLock from the vr flinger dispatch thread might trigger a
708 // deadlock in surface flinger (see b/66916578), so post a message
709 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700710 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700711 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
712 mVrFlingerRequestsDisplay = requestDisplay;
713 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700714 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800715 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700716 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
717 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700718 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700719 .value_or(0),
720 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800721 if (!mVrFlinger) {
722 ALOGE("Failed to start vrflinger");
723 }
724 }
725
Lloyd Pique90c115d2018-09-18 21:39:42 -0700726 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700727 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700728
Mathias Agopian92a979a2012-08-02 18:32:23 -0700729 // initialize our drawing state
730 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700731
Andy McFadden13a082e2012-08-24 10:16:42 -0700732 // set initial conditions (e.g. unblank default device)
733 initializeDisplays();
734
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700735 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700736
Wei Wangf9b05ee2017-07-19 20:59:39 -0700737 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700738
739 const bool presentFenceReliable =
740 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
741 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742
743 if (mStartPropertySetThread->Start() != NO_ERROR) {
744 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800746
Ana Krulec7d1d6832018-12-27 11:10:09 -0800747 if (mUseScheduler) {
748 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
749 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
Ana Krulecb43429d2019-01-09 14:28:51 -0800750 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
751 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800752 }
753
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700755}
756
Romain Guy11d63f42017-07-20 12:47:14 -0700757void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700758 Mutex::Autolock _l(mStateLock);
759
Romain Guy11d63f42017-07-20 12:47:14 -0700760 char value[PROPERTY_VALUE_MAX];
761
762 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800763 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700764 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800765 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100766
767 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700768 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700769}
770
Mathias Agopiana67e4182012-06-19 17:26:12 -0700771void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800772 // Start boot animation service by setting a property mailbox
773 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700774 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800775 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700776 if (mStartPropertySetThread->join() != NO_ERROR) {
777 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800778 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700779}
780
Mathias Agopian875d8e12013-06-07 15:35:48 -0700781size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700782 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700783}
784
Mathias Agopian875d8e12013-06-07 15:35:48 -0700785size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700786 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700787}
788
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800789// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800790
Jamie Gennis582270d2011-08-17 18:19:00 -0700791bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800792 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800793 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800794 return authenticateSurfaceTextureLocked(bufferProducer);
795}
796
797bool SurfaceFlinger::authenticateSurfaceTextureLocked(
798 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800799 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800800 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800801}
802
Brian Anderson6b376712017-04-04 10:51:39 -0700803status_t SurfaceFlinger::getSupportedFrameTimestamps(
804 std::vector<FrameEvent>* outSupported) const {
805 *outSupported = {
806 FrameEvent::REQUESTED_PRESENT,
807 FrameEvent::ACQUIRE,
808 FrameEvent::LATCH,
809 FrameEvent::FIRST_REFRESH_START,
810 FrameEvent::LAST_REFRESH_START,
811 FrameEvent::GPU_COMPOSITION_DONE,
812 FrameEvent::DEQUEUE_READY,
813 FrameEvent::RELEASE,
814 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700815 ConditionalLock _l(mStateLock,
816 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700817 if (!getHwComposer().hasCapability(
818 HWC2::Capability::PresentFenceIsNotReliable)) {
819 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
820 }
821 return NO_ERROR;
822}
823
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
825 Vector<DisplayInfo>* configs) {
826 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 return BAD_VALUE;
828 }
829
Dominik Laskowski075d3172018-05-24 15:50:06 -0700830 const auto displayId = getPhysicalDisplayId(displayToken);
831 if (!displayId) {
832 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 // TODO: Not sure if display density should handled by SF any longer
836 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700839 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843 return density;
844 }
845 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700846 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("ro.sf.lcd_density"); }
850 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Steven Thomas6d8110b2017-08-31 18:24:21 -0700854 ConditionalLock _l(mStateLock,
855 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700856 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 DisplayInfo info = DisplayInfo();
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 float xdpi = hwConfig->getDpiX();
860 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862 info.w = hwConfig->getWidth();
863 info.h = hwConfig->getHeight();
864 // Default display viewport to display width and height
865 info.viewportW = info.w;
866 info.viewportH = info.h;
867
Dominik Laskowski075d3172018-05-24 15:50:06 -0700868 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 // The density of the device is provided by a build property
870 float density = Density::getBuildDensity() / 160.0f;
871 if (density == 0) {
872 // the build doesn't provide a density -- this is wrong!
873 // use xdpi instead
874 ALOGE("ro.sf.lcd_density must be defined as a build property");
875 density = xdpi / 160.0f;
876 }
877 if (Density::getEmuDensity()) {
878 // if "qemu.sf.lcd_density" is specified, it overrides everything
879 xdpi = ydpi = density = Density::getEmuDensity();
880 density /= 160.0f;
881 }
882 info.density = density;
883
884 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885 const auto display = getDefaultDisplayDeviceLocked();
886 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700887
888 // This is for screenrecord
889 const Rect viewport = display->getViewport();
890 if (viewport.isValid()) {
891 info.viewportW = uint32_t(viewport.getWidth());
892 info.viewportH = uint32_t(viewport.getHeight());
893 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 } else {
895 // TODO: where should this value come from?
896 static const int TV_DENSITY = 213;
897 info.density = TV_DENSITY / 160.0f;
898 info.orientation = 0;
899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 info.xdpi = xdpi;
902 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900904 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905
Andy McFadden91b2ca82014-06-13 14:04:23 -0700906 // This is how far in advance a buffer must be queued for
907 // presentation at a given time. If you want a buffer to appear
908 // on the screen at time N, you must submit the buffer before
909 // (N - presentationDeadline).
910 //
911 // Normally it's one full refresh period (to give SF a chance to
912 // latch the buffer), but this can be reduced by configuring a
913 // DispSync offset. Any additional delays introduced by the hardware
914 // composer or panel must be accounted for here.
915 //
916 // We add an additional 1ms to allow for processing time and
917 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800919 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700920
921 // All non-virtual displays are currently considered secure.
922 info.secure = true;
923
Dominik Laskowski075d3172018-05-24 15:50:06 -0700924 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700925 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800926 std::swap(info.w, info.h);
927 }
928
Michael Wright28f24d02016-07-12 13:30:53 -0700929 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700930 }
931
Dan Stoza7f7da322014-05-02 15:26:25 -0700932 return NO_ERROR;
933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
936 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return BAD_VALUE;
938 }
939
Ana Krulece588e312018-09-18 12:32:24 -0700940 if (mUseScheduler) {
941 mScheduler->getDisplayStatInfo(stats);
942 } else {
943 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
944 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
945 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700946 return NO_ERROR;
947}
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
950 const auto display = getDisplayDevice(displayToken);
951 if (!display) {
952 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800953 return BAD_VALUE;
954 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700957}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700958
Ana Krulec7d1d6832018-12-27 11:10:09 -0800959status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
960 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800961 postMessageAsync(new LambdaMessage(
962 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800963 return NO_ERROR;
964}
965
966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
967 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800968 postMessageSync(new LambdaMessage(
969 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800970 return NO_ERROR;
971}
972
973void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
974 Vector<DisplayInfo> configs;
975 getDisplayConfigs(displayToken, &configs);
976 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
977 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
978 return;
979 }
980
981 const auto display = getDisplayDevice(displayToken);
982 if (!display) {
983 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
984 displayToken.get());
985 return;
986 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700987 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800988 ALOGW("Attempt to set active config %d for virtual display", mode);
989 return;
990 }
991 int currentDisplayPowerMode = display->getPowerMode();
992 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
993 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700994 return;
995 }
996
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700998 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800999 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001000 return;
1001 }
Ana Krulecb43429d2019-01-09 14:28:51 -08001002 if (mUseScheduler) {
1003 mRefreshRateStats->setConfigMode(mode);
1004 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001005
Dominik Laskowski075d3172018-05-24 15:50:06 -07001006 const auto displayId = display->getId();
1007 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001011
Ana Krulec7d1d6832018-12-27 11:10:09 -08001012 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001013 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001014}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1017 Vector<ColorMode>* outColorModes) {
1018 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001019 return BAD_VALUE;
1020 }
1021
Dominik Laskowski075d3172018-05-24 15:50:06 -07001022 const auto displayId = getPhysicalDisplayId(displayToken);
1023 if (!displayId) {
1024 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 }
1026
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001028 {
1029 ConditionalLock _l(mStateLock,
1030 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001031 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001032 }
Michael Wright28f24d02016-07-12 13:30:53 -07001033 outColorModes->clear();
1034 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1035
1036 return NO_ERROR;
1037}
1038
Daniel Solomon42d04562019-01-20 21:03:19 -08001039status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1040 ui::DisplayPrimaries &primaries) {
1041 if (!displayToken) {
1042 return BAD_VALUE;
1043 }
1044
1045 // Currently we only support this API for a single internal display.
1046 if (getInternalDisplayToken() != displayToken) {
1047 return BAD_VALUE;
1048 }
1049
1050 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1051 return NO_ERROR;
1052}
1053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1055 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001056 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001059}
1060
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001062 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 Vector<ColorMode> modes;
1064 getDisplayColorModes(displayToken, &modes);
1065 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1066 if (mode < ColorMode::NATIVE || !exists) {
1067 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1068 decodeColorMode(mode).c_str(), mode, displayToken.get());
1069 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001070 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 const auto display = getDisplayDevice(displayToken);
1072 if (!display) {
1073 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1074 decodeColorMode(mode).c_str(), mode, displayToken.get());
1075 } else if (display->isVirtual()) {
1076 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1077 decodeColorMode(mode).c_str(), mode);
1078 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001079 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1080 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081 }
1082 }));
1083
Michael Wright28f24d02016-07-12 13:30:53 -07001084 return NO_ERROR;
1085}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001086
Svetoslavd85084b2014-03-20 10:28:31 -07001087status_t SurfaceFlinger::clearAnimationFrameStats() {
1088 Mutex::Autolock _l(mStateLock);
1089 mAnimFrameTracker.clearStats();
1090 return NO_ERROR;
1091}
1092
1093status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1094 Mutex::Autolock _l(mStateLock);
1095 mAnimFrameTracker.getStats(outStats);
1096 return NO_ERROR;
1097}
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1100 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001101 Mutex::Autolock _l(mStateLock);
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 const auto display = getDisplayDeviceLocked(displayToken);
1104 if (!display) {
1105 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001106 return BAD_VALUE;
1107 }
1108
Peiyong Linfb069302018-04-25 14:34:31 -07001109 // At this point the DisplayDeivce should already be set up,
1110 // meaning the luminance information is already queried from
1111 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001113 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1114 capabilities.getDesiredMaxLuminance(),
1115 capabilities.getDesiredMaxAverageLuminance(),
1116 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001117
1118 return NO_ERROR;
1119}
1120
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001121status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1122 ui::PixelFormat* outFormat,
1123 ui::Dataspace* outDataspace,
1124 uint8_t* outComponentMask) const {
1125 if (!outFormat || !outDataspace || !outComponentMask) {
1126 return BAD_VALUE;
1127 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001128 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001129 if (!display || !display->getId()) {
1130 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1131 return BAD_VALUE;
1132 }
1133 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1134 outDataspace, outComponentMask);
1135}
1136
Kevin DuBois74e53772018-11-19 10:52:38 -08001137status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1138 bool enable, uint8_t componentMask,
1139 uint64_t maxFrames) const {
1140 const auto display = getDisplayDevice(displayToken);
1141 if (!display || !display->getId()) {
1142 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1143 return BAD_VALUE;
1144 }
1145
1146 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1147 componentMask, maxFrames);
1148}
1149
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001150status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1151 uint64_t maxFrames, uint64_t timestamp,
1152 DisplayedFrameStats* outStats) const {
1153 const auto display = getDisplayDevice(displayToken);
1154 if (!display || !display->getId()) {
1155 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1156 return BAD_VALUE;
1157 }
1158
1159 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1160 outStats);
1161}
1162
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001163status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1164 if (!outSupported) {
1165 return BAD_VALUE;
1166 }
1167 *outSupported = getRenderEngine().supportsProtectedContent();
1168 return NO_ERROR;
1169}
1170
Marissa Wallebc2c052019-01-16 19:16:55 -08001171status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1172 int32_t* outBufferId) {
1173 if (!outBufferId) {
1174 return BAD_VALUE;
1175 }
1176 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1177 return NO_ERROR;
1178}
1179
1180status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1181 mBufferStateLayerCache.release(token, bufferId);
1182 return NO_ERROR;
1183}
1184
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001185status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1186 bool* outIsWideColorDisplay) const {
1187 if (!displayToken || !outIsWideColorDisplay) {
1188 return BAD_VALUE;
1189 }
1190 Mutex::Autolock _l(mStateLock);
1191 const auto display = getDisplayDeviceLocked(displayToken);
1192 if (!display) {
1193 return BAD_VALUE;
1194 }
1195 *outIsWideColorDisplay = display->hasWideColorGamut();
1196 return NO_ERROR;
1197}
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001200 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001201 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203 if (mInjectVSyncs == enable) {
1204 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001206
Dominik Laskowski83b88212018-12-11 13:34:06 -08001207 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001208
Ana Krulec98b5b242018-08-10 15:03:23 -07001209 // TODO(akrulec): Part of the Injector should be refactored, so that it
1210 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001211 if (enable) {
1212 ALOGV("VSync Injections enabled");
1213 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001214 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001215 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001216 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001217 impl::EventThread::InterceptVSyncsCallback(),
1218 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001219 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001220 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 } else {
1222 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001223 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001224 }
1225
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001227 }));
1228
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229 return NO_ERROR;
1230}
1231
1232status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 Mutex::Autolock _l(mStateLock);
1234
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235 if (!mInjectVSyncs) {
1236 ALOGE("VSync Injections not enabled");
1237 return BAD_VALUE;
1238 }
1239 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1240 ALOGV("Injecting VSync inside SurfaceFlinger");
1241 mVSyncInjector->onInjectSyncEvent(when);
1242 }
1243 return NO_ERROR;
1244}
1245
Lloyd Pique755e3192018-01-31 16:46:15 -08001246status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1247 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001248 // Try to acquire a lock for 1s, fail gracefully
1249 const status_t err = mStateLock.timedLock(s2ns(1));
1250 const bool locked = (err == NO_ERROR);
1251 if (!locked) {
1252 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1253 return TIMED_OUT;
1254 }
1255
1256 outLayers->clear();
1257 mCurrentState.traverseInZOrder([&](Layer* layer) {
1258 outLayers->push_back(layer->getLayerDebugInfo());
1259 });
1260
1261 mStateLock.unlock();
1262 return NO_ERROR;
1263}
1264
Peiyong Linc6780972018-10-28 15:24:08 -07001265status_t SurfaceFlinger::getCompositionPreference(
1266 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1267 Dataspace* outWideColorGamutDataspace,
1268 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001269 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001270 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001271 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001272 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001273 return NO_ERROR;
1274}
1275
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001276// ----------------------------------------------------------------------------
1277
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001278sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1279 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001280 auto resyncCallback = makeResyncCallback([this] {
1281 Mutex::Autolock lock(mStateLock);
1282 return getVsyncPeriod();
1283 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001284
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 if (mUseScheduler) {
1286 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001287 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001288 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001289 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001290 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001291 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001292 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001293 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001294 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001295 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001296 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001297 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001298}
1299
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001300// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001301
1302void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001303 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001304}
1305
1306void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001307 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001308}
1309
1310void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001311 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001312}
1313
1314void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001315 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001316 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001317}
1318
1319status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001320 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001321 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001322}
1323
1324status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001325 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001326 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001327 if (res == NO_ERROR) {
1328 msg->wait();
1329 }
1330 return res;
1331}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001332
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001333void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001334 do {
1335 waitForEvent();
1336 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001337}
1338
Dominik Laskowski83b88212018-12-11 13:34:06 -08001339nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1340 const auto displayId = getInternalDisplayId();
1341 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1342 return 0;
1343 }
1344
1345 const auto config = getHwComposer().getActiveConfig(*displayId);
1346 return config ? config->getVsyncPeriod() : 0;
1347}
1348
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349void SurfaceFlinger::enableHardwareVsync() {
1350 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001351 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001352 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001353 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001354 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001355 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356}
1357
Dominik Laskowski83b88212018-12-11 13:34:06 -08001358void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001359 Mutex::Autolock _l(mHWVsyncLock);
1360
Jesse Hall948fe0c2013-10-14 12:56:09 -07001361 if (makeAvailable) {
1362 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001363 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1364 if (mUseScheduler) {
1365 mScheduler->makeHWSyncAvailable(true);
1366 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001367 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001368 // Hardware vsync is not currently available, so abort the resync
1369 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001370 return;
1371 }
1372
Dominik Laskowski83b88212018-12-11 13:34:06 -08001373 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001374 return;
1375 }
1376
Ana Krulece588e312018-09-18 12:32:24 -07001377 if (mUseScheduler) {
1378 mScheduler->setVsyncPeriod(period);
1379 } else {
1380 mPrimaryDispSync->reset();
1381 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382
Ana Krulece588e312018-09-18 12:32:24 -07001383 if (!mPrimaryHWVsyncEnabled) {
1384 mPrimaryDispSync->beginResync();
1385 mEventControlThread->setVsyncEnabled(true);
1386 mPrimaryHWVsyncEnabled = true;
1387 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001388 }
1389}
1390
Jesse Hall948fe0c2013-10-14 12:56:09 -07001391void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392 Mutex::Autolock _l(mHWVsyncLock);
1393 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001394 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001395 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396 mPrimaryHWVsyncEnabled = false;
1397 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001398 if (makeUnavailable) {
1399 mHWVsyncAvailable = false;
1400 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401}
1402
Dominik Laskowski83b88212018-12-11 13:34:06 -08001403void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001404 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001405
Dan Stoza57164302017-05-08 14:03:54 -07001406 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001407 const nsecs_t last = lastResyncTime.exchange(now);
1408
1409 if (now - last > kIgnoreDelay) {
1410 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001411 }
1412}
1413
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001414void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1415 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001416 ATRACE_NAME("SF onVsync");
1417
Steven Thomas3cfac282017-02-06 12:29:30 -08001418 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 return;
1422 }
1423
Dominik Laskowski075d3172018-05-24 15:50:06 -07001424 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001425 return;
1426 }
1427
Dominik Laskowski075d3172018-05-24 15:50:06 -07001428 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001429 // For now, we don't do anything with external display vsyncs.
1430 return;
1431 }
1432
Ana Krulece588e312018-09-18 12:32:24 -07001433 if (mUseScheduler) {
1434 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001435 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001436 bool needsHwVsync = false;
1437 { // Scope for the lock
1438 Mutex::Autolock _l(mHWVsyncLock);
1439 if (mPrimaryHWVsyncEnabled) {
1440 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1441 }
1442 }
1443
1444 if (needsHwVsync) {
1445 enableHardwareVsync();
1446 } else {
1447 disableHardwareVsync(false);
1448 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001449 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001450}
1451
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001452void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001453 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1454 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001455}
1456
Ana Krulec7d1d6832018-12-27 11:10:09 -08001457void SurfaceFlinger::setRefreshRateTo(float newFps) {
1458 const auto displayId = getInternalDisplayId();
1459 if (!displayId || mBootStage != BootStage::FINISHED) {
1460 return;
1461 }
1462 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1463 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1464 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1465 // refresh cycle.
1466
1467 // Don't do any updating if the current fps is the same as the new one.
1468 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1469 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1470 if (currentVsyncPeriod == 0) {
1471 return;
1472 }
1473 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1474 // floating numbers.
1475 const float currentFps = 1e9 / currentVsyncPeriod;
1476 if (std::abs(currentFps - newFps) <= 1) {
1477 return;
1478 }
1479
1480 auto configs = getHwComposer().getConfigs(*displayId);
1481 for (int i = 0; i < configs.size(); i++) {
1482 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1483 if (vsyncPeriod == 0) {
1484 continue;
1485 }
1486 const float fps = 1e9 / vsyncPeriod;
1487 // TODO(b/113612090): There should be a better way at determining which config
1488 // has the right refresh rate.
1489 if (std::abs(fps - newFps) <= 1) {
1490 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1491 if (!display) return;
1492 // This is posted in async function to avoid deadlock when getDisplayDevice
1493 // requires mStateLock.
1494 setActiveConfigAsync(display, i);
1495 ATRACE_INT("FPS", newFps);
1496 }
1497 }
1498}
1499
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001500void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001501 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001502 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001503 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504
Lloyd Piqueba04e622017-12-14 17:11:26 -08001505 // Ignore events that do not have the right sequenceId.
1506 if (sequenceId != getBE().mComposerSequenceId) {
1507 return;
1508 }
1509
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 // Only lock if we're not on the main thread. This function is normally
1511 // called on a hwbinder thread, but for the primary display it's called on
1512 // the main thread with the state lock already held, so don't attempt to
1513 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001514 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001515
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001516 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001517
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001518 if (std::this_thread::get_id() == mMainThreadId) {
1519 // Process all pending hot plug events immediately if we are on the main thread.
1520 processDisplayHotplugEventsLocked();
1521 }
1522
Lloyd Piqueba04e622017-12-14 17:11:26 -08001523 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001524}
1525
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001526void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001527 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001528 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001530 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001531 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001532}
1533
Dominik Laskowski075d3172018-05-24 15:50:06 -07001534void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001535 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001536 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001537 if (const auto displayId = getInternalDisplayId()) {
1538 getHwComposer().setVsyncEnabled(*displayId,
1539 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1540 }
Mathias Agopian86303202012-07-24 22:46:10 -07001541}
1542
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001543// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001544void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001545 if (mUseScheduler) {
1546 mScheduler->disableHardwareVsync(true);
1547 } else {
1548 disableHardwareVsync(true);
1549 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001550 // Clear the drawing state so that the logic inside of
1551 // handleTransactionLocked will fire. It will determine the delta between
1552 // mCurrentState and mDrawingState and re-apply all changes when we make the
1553 // transition.
1554 mDrawingState.displays.clear();
1555 mDisplays.clear();
1556}
1557
Steven Thomas050b2c82017-03-06 11:45:16 -08001558void SurfaceFlinger::updateVrFlinger() {
1559 if (!mVrFlinger)
1560 return;
1561 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001562 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001563 return;
1564 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565
Lloyd Pique441d5042018-10-18 16:49:51 -07001566 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 ALOGE("Vr flinger is only supported for remote hardware composer"
1568 " service connections. Ignoring request to transition to vr"
1569 " flinger.");
1570 mVrFlingerRequestsDisplay = false;
1571 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001572 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001573
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001574 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001575
Steven Thomas0123ac62018-07-12 11:32:34 -07001576 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001577 LOG_ALWAYS_FATAL_IF(!display);
1578 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001579 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1580 // called below. Clear the reference now so we don't accidentally use it
1581 // later.
1582 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001583
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001585 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001587
Steven Thomasb02664d2017-07-26 18:48:28 -07001588 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001589 // Delete the current instance before creating the new one
1590 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1591 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1592 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1593 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594
Lloyd Pique441d5042018-10-18 16:49:51 -07001595 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001596 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001597
1598 if (vrFlingerRequestsDisplay) {
1599 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001600 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001601
1602 mVisibleRegionsDirty = true;
1603 invalidateHwcGeometry();
1604
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001605 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001606 display = getDefaultDisplayDeviceLocked();
1607 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001608 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001609
Steven Thomasb02664d2017-07-26 18:48:28 -07001610 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001611 const nsecs_t vsyncPeriod = getVsyncPeriod();
1612 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001613
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001614 // The present fences returned from vr_hwc are not an accurate
1615 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001616 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001617 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1618 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001619 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001620 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001621 !hasSyncFramework);
1622 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001623
Steven Thomasb02664d2017-07-26 18:48:28 -07001624 // Use phase of 0 since phase is not known.
1625 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001626 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001627 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001628
Dominik Laskowski83b88212018-12-11 13:34:06 -08001629 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001630
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001631 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001632 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001633}
1634
Mathias Agopian4fec8732012-06-29 14:12:52 -07001635void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001636 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001637 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001638 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001639 if (mUseScheduler) {
1640 // This call is made each time SF wakes up and creates a new frame.
1641 mScheduler->incrementFrameCounter();
1642 }
Dan Stoza50182882016-07-08 12:02:20 -07001643 bool frameMissed = !mHadClientComposition &&
1644 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645 (mPreviousPresentFence->getSignalTime() ==
1646 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001647 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001648 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001649 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001650 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001651 if (mPropagateBackpressure) {
1652 signalLayerUpdate();
1653 break;
1654 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001655 }
Dan Stoza50182882016-07-08 12:02:20 -07001656
Steven Thomas050b2c82017-03-06 11:45:16 -08001657 // Now that we're going to make it to the handleMessageTransaction()
1658 // call below it's safe to call updateVrFlinger(), which will
1659 // potentially trigger a display handoff.
1660 updateVrFlinger();
1661
Dan Stoza6b9454d2014-11-07 16:00:59 -08001662 bool refreshNeeded = handleMessageTransaction();
1663 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001664 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001665 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001666 // Signal a refresh if a transaction modified the window state,
1667 // a new buffer was latched, or if HWC has requested a full
1668 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001669 signalRefresh();
1670 }
1671 break;
1672 }
1673 case MessageQueue::REFRESH: {
1674 handleMessageRefresh();
1675 break;
1676 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001677 }
1678}
1679
Dan Stoza6b9454d2014-11-07 16:00:59 -08001680bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001681 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001682
1683 // Apply any ready transactions in the queues if there are still transactions that have not been
1684 // applied, wake up during the next vsync period and check again
1685 bool transactionNeeded = false;
1686 if (!flushTransactionQueues()) {
1687 transactionNeeded = true;
1688 }
1689
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001691 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001693
1694 if (transactionNeeded) {
1695 setTransactionFlags(eTransactionNeeded);
1696 }
1697
1698 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001699}
1700
Mathias Agopian4fec8732012-06-29 14:12:52 -07001701void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001703
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001704 mRefreshPending = false;
1705
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001706 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001707 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001708 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001709 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710 for (const auto& [token, display] : mDisplays) {
1711 beginFrame(display);
1712 prepareFrame(display);
1713 doDebugFlashRegions(display, repaintEverything);
1714 doComposition(display, repaintEverything);
1715 }
1716
Adrian Roos1e1a1282017-11-01 19:05:31 +01001717 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001718 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001719
1720 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001721 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001722
Dan Stozabfbffeb2016-07-21 14:49:33 -07001723 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001724 for (const auto& [token, displayDevice] : mDisplays) {
1725 auto display = displayDevice->getCompositionDisplay();
1726 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001727 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001728 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001729 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001730
Alec Mouri86770e52018-09-24 22:40:58 +00001731 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001732 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001733 if (mHadClientComposition) {
1734 base::unique_fd flushFence(getRenderEngine().flush());
1735 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1736 getBE().flushFence = new Fence(std::move(flushFence));
1737 } else {
1738 // Cleanup for hygiene.
1739 getBE().flushFence = Fence::NO_FENCE;
1740 }
1741 }
1742
Jorim Jaggi90535212018-05-23 23:44:06 +02001743 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001744
David Sodman7e4ae112018-02-09 15:02:28 -08001745 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001746 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001747 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001748 compositionInfo.hwc.hwcLayer = nullptr;
1749 }
David Sodmanba340492018-08-05 21:51:33 -07001750 }
David Sodman7e4ae112018-02-09 15:02:28 -08001751
1752 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001754
David Sodmanfa9b2af2017-12-24 13:28:59 -08001755
1756bool SurfaceFlinger::handleMessageInvalidate() {
1757 ATRACE_CALL();
1758 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001759}
1760
David Sodman79bba0e2018-08-05 18:07:49 -07001761void SurfaceFlinger::calculateWorkingSet() {
1762 ATRACE_CALL();
1763 ALOGV(__FUNCTION__);
1764
David Sodman79bba0e2018-08-05 18:07:49 -07001765 // build the h/w work list
1766 if (CC_UNLIKELY(mGeometryInvalid)) {
1767 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001768 for (const auto& [token, displayDevice] : mDisplays) {
1769 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001770 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771 if (!displayId) {
1772 continue;
1773 }
David Sodman79bba0e2018-08-05 18:07:49 -07001774
Lloyd Pique32cbe282018-10-19 13:09:22 -07001775 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776 for (size_t i = 0; i < currentLayers.size(); i++) {
1777 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001778
Dominik Laskowski075d3172018-05-24 15:50:06 -07001779 if (!layer->hasHwcLayer(*displayId)) {
1780 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1781 layer->forceClientComposition(*displayId);
1782 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001783 }
1784 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785
Lloyd Pique32cbe282018-10-19 13:09:22 -07001786 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001787 if (mDebugDisableHWC || mDebugRegion) {
1788 layer->forceClientComposition(*displayId);
1789 }
David Sodman79bba0e2018-08-05 18:07:49 -07001790 }
1791 }
1792 }
1793
1794 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001795 for (const auto& [token, displayDevice] : mDisplays) {
1796 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001797 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001798 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001799 continue;
1800 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001801 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001802
1803 if (mDrawingState.colorMatrixChanged) {
1804 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001805 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001806 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001807 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001808 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001809 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1810 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001811 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001812 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001813 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1814 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001815 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001816 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001817 }
1818
Peiyong Lind3788632018-09-18 16:01:31 -07001819 // TODO(b/111562338) remove when composer 2.3 is shipped.
1820 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001821 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001822 }
1823
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001824 if (layer->getRoundedCornerState().radius > 0.0f) {
1825 layer->forceClientComposition(*displayId);
1826 }
1827
Dominik Laskowski075d3172018-05-24 15:50:06 -07001828 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001829 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001830 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001831 continue;
1832 }
1833
Lloyd Pique32cbe282018-10-19 13:09:22 -07001834 const auto& displayState = display->getState();
1835 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1836 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001837 }
1838
Peiyong Lin13effd12018-07-24 17:01:47 -07001839 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001840 ColorMode colorMode;
1841 Dataspace dataSpace;
1842 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001844 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001845 }
1846 }
1847
1848 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001849
1850 for (const auto& [token, display] : mDisplays) {
1851 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001852 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001853 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001854
1855 if (displayId) {
1856 if (!layer->setHwcLayer(*displayId)) {
1857 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1858 }
1859 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001860 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001861
Dominik Laskowski05275f12018-11-01 15:03:24 -07001862 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001863 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1864 }
1865 }
David Sodman79bba0e2018-08-05 18:07:49 -07001866}
1867
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1869 bool repaintEverything) {
1870 auto display = displayDevice->getCompositionDisplay();
1871 const auto& displayState = display->getState();
1872
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 // is debugging enabled
1874 if (CC_LIKELY(!mDebugRegion))
1875 return;
1876
Lloyd Pique32cbe282018-10-19 13:09:22 -07001877 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001878 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001879 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001880 if (!dirtyRegion.isEmpty()) {
1881 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001882 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883
David Sodmanfa9b2af2017-12-24 13:28:59 -08001884 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001885 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001886 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001887
Lloyd Pique31cb2942018-10-19 17:23:03 -07001888 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889 }
1890 }
1891
Lloyd Pique32cbe282018-10-19 13:09:22 -07001892 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893
1894 if (mDebugRegion > 1) {
1895 usleep(mDebugRegion * 1000);
1896 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001897
Lloyd Pique32cbe282018-10-19 13:09:22 -07001898 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899}
1900
Adrian Roos1e1a1282017-11-01 19:05:31 +01001901void SurfaceFlinger::doTracing(const char* where) {
1902 ATRACE_CALL();
1903 ATRACE_NAME(where);
1904 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001905 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001906 }
1907}
1908
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001909void SurfaceFlinger::logLayerStats() {
1910 ATRACE_CALL();
1911 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001912 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001913 if (display->isPrimary()) {
1914 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001916 }
1917 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001918
1919 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001920 }
1921}
1922
David Sodman2b406362017-12-15 13:33:47 -08001923void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001924{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 ATRACE_CALL();
1926 ALOGV("preComposition");
1927
David Sodman2b406362017-12-15 13:33:47 -08001928 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1929
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001931 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001932 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001933 needExtraInvalidate = true;
1934 }
Robert Carr2047fae2016-11-28 14:09:09 -08001935 });
1936
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 if (needExtraInvalidate) {
1938 signalLayerUpdate();
1939 }
1940}
1941
Ana Krulece588e312018-09-18 12:32:24 -07001942void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1943 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // Update queue of past composite+present times and determine the
1945 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001946 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001948 while (!getBE().mCompositePresentTimes.empty()) {
1949 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950 // Cached values should have been updated before calling this method,
1951 // which helps avoid duplicate syscalls.
1952 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1953 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1954 break;
1955 }
1956 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001957 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 }
1959
1960 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001961 while (getBE().mCompositePresentTimes.size() > 16) {
1962 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963 }
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001966}
1967
Ana Krulece588e312018-09-18 12:32:24 -07001968void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1969 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970 // Integer division and modulo round toward 0 not -inf, so we need to
1971 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001972 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1973 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1974 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
Brian Andersond0010582017-03-07 13:20:31 -08001976 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1977 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001978 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001979 }
1980
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 // Snap the latency to a value that removes scheduling jitter from the
1982 // composition and present times, which often have >1ms of jitter.
1983 // Reducing jitter is important if an app attempts to extrapolate
1984 // something (such as user input) to an accurate diasplay time.
1985 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1986 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001987 nsecs_t bias = stats.vsyncPeriod / 2;
1988 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1989 nsecs_t snappedCompositeToPresentLatency =
1990 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991
David Sodman99974d22017-11-28 12:04:33 -08001992 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001993 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1994 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001995 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001996}
1997
Ady Abraham8164d482019-01-11 14:47:59 -08001998// debug patch for b/119477596 - add stack guards to catch stack
1999// corruptions and disable clang optimizations.
2000// The code below is temporary and planned to be removed once stack
2001// corruptions are found.
2002#pragma clang optimize off
2003class StackGuard {
2004public:
2005 StackGuard(const char* name, const char* func, int line) {
2006 guarders.reserve(MIN_CAPACITY);
2007 guarders.push_back({this, name, func, line});
2008 validate();
2009 }
2010 ~StackGuard() {
2011 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2012 if (i->guard == this) {
2013 guarders.erase(i);
2014 break;
2015 }
2016 }
2017 }
2018
2019 static void validate() {
2020 for (const auto& guard : guarders) {
2021 if (guard.guard->cookie != COOKIE_VALUE) {
2022 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2023 CallStack stack(LOG_TAG);
2024 abort();
2025 }
2026 }
2027 }
2028
2029private:
2030 uint64_t cookie = COOKIE_VALUE;
2031 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2032 static constexpr size_t MIN_CAPACITY = 16;
2033
2034 struct GuarderElement {
2035 StackGuard* guard;
2036 const char* name;
2037 const char* func;
2038 int line;
2039 };
2040
2041 static std::vector<GuarderElement> guarders;
2042};
2043std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2044
2045#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2046
2047#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002048void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002049{
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 ATRACE_CALL();
2052 ALOGV("postComposition");
2053
Brian Anderson3546a3f2016-07-14 11:51:14 -07002054 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002055 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002056 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002057 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002058 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002059 }
Ady Abraham8164d482019-01-11 14:47:59 -08002060 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002061
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002062 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002063 const auto displayDevice = getDefaultDisplayDeviceLocked();
2064 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002065
David Sodman73beded2017-11-15 11:56:06 -08002066 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002067 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002068 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2069
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002071 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002072 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2073 ->getRenderSurface()
2074 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002075 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002076 } else {
2077 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2078 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079
Ady Abraham8164d482019-01-11 14:47:59 -08002080 ASSERT_ON_STACK_GUARD();
2081
David Sodman73beded2017-11-15 11:56:06 -08002082 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002083 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2084 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002085 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002086 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002087 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002088
Ana Krulece588e312018-09-18 12:32:24 -07002089 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002090 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002091 if (mUseScheduler) {
2092 mScheduler->getDisplayStatInfo(&stats);
2093 } else {
2094 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2095 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2096 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002097
Ady Abraham8164d482019-01-11 14:47:59 -08002098 ASSERT_ON_STACK_GUARD();
2099
David Sodman2b406362017-12-15 13:33:47 -08002100 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101 // when we started doing work for this frame, but that should be okay
2102 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002103 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002104 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002105 DEFINE_STACK_GUARD(compositorTiming);
2106
Brian Andersond0010582017-03-07 13:20:31 -08002107 {
David Sodman99974d22017-11-28 12:04:33 -08002108 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002109 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002110 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002111
2112 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002113 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002114
Robert Carr2047fae2016-11-28 14:09:09 -08002115 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002116 bool frameLatched =
2117 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2118 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002119 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002120 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002121 recordBufferingStats(layer->getName().string(),
2122 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002123 }
Ady Abraham8164d482019-01-11 14:47:59 -08002124 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002125 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002126
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002127 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002129 if (mUseScheduler) {
2130 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002131 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002132 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002133 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2134 enableHardwareVsync();
2135 } else {
2136 disableHardwareVsync(false);
2137 }
Ady Abraham8164d482019-01-11 14:47:59 -08002138 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002139 }
2140 }
2141
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002142 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002143 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2144 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002145 if (mUseScheduler) {
2146 mScheduler->enableHardwareVsync();
2147 } else {
2148 enableHardwareVsync();
2149 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002150 }
2151 }
2152
Ady Abraham8164d482019-01-11 14:47:59 -08002153 ASSERT_ON_STACK_GUARD();
2154
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002155 if (mAnimCompositionPending) {
2156 mAnimCompositionPending = false;
2157
Brian Anderson4e606e32017-03-16 15:34:57 -07002158 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002159 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002160 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002161
2162 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002164 // The HWC doesn't support present fences, so use the refresh
2165 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002166 const nsecs_t presentTime =
2167 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002168 DEFINE_STACK_GUARD(presentTime);
2169
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002170 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002172 }
2173 mAnimFrameTracker.advanceFrame();
2174 }
Dan Stozab90cf072015-03-05 11:05:59 -08002175
Ady Abraham8164d482019-01-11 14:47:59 -08002176 ASSERT_ON_STACK_GUARD();
2177
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002178 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002179 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002180 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002181 }
2182
Ady Abraham8164d482019-01-11 14:47:59 -08002183 ASSERT_ON_STACK_GUARD();
2184
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002185 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002186
Ady Abraham8164d482019-01-11 14:47:59 -08002187 ASSERT_ON_STACK_GUARD();
2188
Lloyd Pique32cbe282018-10-19 13:09:22 -07002189 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2190 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002191 return;
2192 }
2193
2194 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002195 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002196 if (mHasPoweredOff) {
2197 mHasPoweredOff = false;
2198 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002199 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002200 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002201 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002202 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002203 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2204 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002205 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002206 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002207 }
David Sodman4a36e932017-11-07 14:29:47 -08002208 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002209
2210 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002211 }
David Sodman4a36e932017-11-07 14:29:47 -08002212 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002213 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002214
2215 {
2216 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002217 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002218 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002219 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002220 if (refillCount > 0) {
2221 const size_t offset = mTexturePool.size();
2222 mTexturePool.resize(mTexturePoolSize);
2223 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2224 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2225 }
Ady Abraham8164d482019-01-11 14:47:59 -08002226 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002227 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002228
Marissa Wallfda30bb2018-10-12 11:34:28 -07002229 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002230 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002231
2232 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002233}
Ady Abraham8164d482019-01-11 14:47:59 -08002234#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002235
2236void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 ATRACE_CALL();
2238 ALOGV("rebuildLayerStacks");
2239
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002240 // We need to clear these out now as these may be holding on to a
2241 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2242 // also holds a reference. When the set of visible layers is recomputed,
2243 // some layers may be destroyed if the only thing keeping them alive was
2244 // that list of visible layers associated with each display. The layer
2245 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2246 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2247 for (const auto& [token, display] : mDisplays) {
2248 getBE().mCompositionInfo[token].clear();
2249 }
2250
Mathias Agopiancd60f992012-08-16 16:28:27 -07002251 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002252 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002253 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002254 mVisibleRegionsDirty = false;
2255 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002256
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002257 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const auto& displayDevice = pair.second;
2259 auto display = displayDevice->getCompositionDisplay();
2260 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002261 Region opaqueRegion;
2262 Region dirtyRegion;
2263 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002264 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002265 const ui::Transform& tr = displayState.transform;
2266 const Rect bounds = displayState.bounds;
2267 if (displayState.isEnabled) {
2268 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269
Jeff Sharkey76488112017-02-27 14:15:18 -07002270 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002271 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002272 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002273 if (display->belongsInOutput(layer->getLayerStack(),
2274 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002275 Region drawRegion(tr.transform(
2276 layer->visibleNonTransparentRegion));
2277 drawRegion.andSelf(bounds);
2278 if (!drawRegion.isEmpty()) {
2279 layersSortedByZ.add(layer);
2280 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002281 // Clear out the HWC layer if this layer was
2282 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002284 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002285 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002286 // WM changes display->layerStack upon sleep/awake.
2287 // Here we make sure we delete the HWC layers even if
2288 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002289 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002290 }
2291
2292 // If a layer is not going to get a release fence because
2293 // it is invisible, but it is also going to release its
2294 // old buffer, add it to the list of layers needing
2295 // fences.
2296 if (hwcLayerDestroyed) {
2297 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2298 mLayersWithQueuedFrames.cend(), layer);
2299 if (found != mLayersWithQueuedFrames.cend()) {
2300 layersNeedingFences.add(layer);
2301 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002302 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002303 });
2304 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002305 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2306 displayDevice->setLayersNeedingFences(layersNeedingFences);
2307
2308 Region undefinedRegion{bounds};
2309 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2310
2311 display->editState().undefinedRegion = undefinedRegion;
2312 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002313 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002314 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002315}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002316
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002319// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002321// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322// The returned HDR data space is one of
2323// - Dataspace::UNKNOWN
2324// - Dataspace::BT2020_HLG
2325// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2327 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002328 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329 *outHdrDataSpace = Dataspace::UNKNOWN;
2330
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002332 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 case Dataspace::V0_SCRGB:
2334 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002335 case Dataspace::BT2020:
2336 case Dataspace::BT2020_ITU:
2337 case Dataspace::BT2020_LINEAR:
2338 case Dataspace::DISPLAY_BT2020:
2339 bestDataSpace = Dataspace::DISPLAY_BT2020;
2340 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002341 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002342 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 case Dataspace::BT2020_PQ:
2345 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002347 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002348 case Dataspace::BT2020_HLG:
2349 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002350 // When there's mixed PQ content and HLG content, we set the HDR
2351 // data space to be BT2020_PQ and convert HLG to PQ.
2352 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2353 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002354 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355 break;
2356 default:
2357 break;
2358 }
Romain Guy54f154a2017-10-24 21:40:32 +01002359 }
2360
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002361 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002362}
2363
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002364// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2366 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002367 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2368 *outMode = ColorMode::NATIVE;
2369 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002370 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002372 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002373
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002374 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002375 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002377 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2378
Peiyong Lindfde5112018-06-05 10:58:41 -07002379 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002380 const bool isHdr =
2381 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002382 if (isHdr) {
2383 bestDataSpace = hdrDataSpace;
2384 }
2385
Chia-I Wu0d711262018-05-21 15:19:35 -07002386 RenderIntent intent;
2387 switch (mDisplayColorSetting) {
2388 case DisplayColorSetting::MANAGED:
2389 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002390 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002391 break;
2392 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002393 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002394 break;
2395 default: // vendor display color setting
2396 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2397 break;
2398 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002399
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002400 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002401}
2402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2404 auto display = displayDevice->getCompositionDisplay();
2405 const auto& displayState = display->getState();
2406
2407 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2408 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2409 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002410
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 // If nothing has changed (!dirty), don't recompose.
2412 // If something changed, but we don't currently have any visible layers,
2413 // and didn't when we last did a composition, then skip it this time.
2414 // The second rule does two things:
2415 // - When all layers are removed from a display, we'll emit one black
2416 // frame, then nothing more until we get new layers.
2417 // - When a display is created with a private layer stack, we won't
2418 // emit any black frames until a layer is added to the layer stack.
2419 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002420
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 const char flagPrefix[] = {'-', '+'};
2422 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2424 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2425 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2426 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002427
Lloyd Pique31cb2942018-10-19 17:23:03 -07002428 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002429
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002432 }
2433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2436 auto display = displayDevice->getCompositionDisplay();
2437 const auto& displayState = display->getState();
2438
2439 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 return;
David Sodman2b406362017-12-15 13:33:47 -08002441 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002442
Lloyd Pique31cb2942018-10-19 17:23:03 -07002443 status_t result = display->getRenderSurface()->prepareFrame(
2444 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002447}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002450 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 ALOGV("doComposition");
2452
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 auto display = displayDevice->getCompositionDisplay();
2454 const auto& displayState = display->getState();
2455
2456 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002459
David Sodmanfa9b2af2017-12-24 13:28:59 -08002460 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002462
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002464 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002465 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002466 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002467}
2468
David Sodmanfa9b2af2017-12-24 13:28:59 -08002469void SurfaceFlinger::postFrame()
2470{
2471 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 const auto display = getDefaultDisplayDeviceLocked();
2473 if (display && getHwComposer().isConnected(*display->getId())) {
2474 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2476 logFrameStats();
2477 }
2478 }
2479}
2480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002482 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002484
Lloyd Pique32cbe282018-10-19 13:09:22 -07002485 auto display = displayDevice->getCompositionDisplay();
2486 const auto& displayState = display->getState();
2487 const auto displayId = display->getId();
2488
David Sodmanfa9b2af2017-12-24 13:28:59 -08002489 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002490
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 if (displayId) {
2493 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002494 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002495 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002496 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002497 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002498
Chia-I Wu7b549592017-11-15 09:14:57 -08002499 // The layer buffer from the previous frame (if any) is released
2500 // by HWC only when the release fence from this frame (if any) is
2501 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 if (displayId && layer->hasHwcLayer(*displayId)) {
2503 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2504 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002505 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002506
2507 // If the layer was client composited in the previous frame, we
2508 // need to merge with the previous client target acquire fence.
2509 // Since we do not track that, always merge with the current
2510 // client target acquire fence when it is available, even though
2511 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002512 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002513 releaseFence =
2514 Fence::merge("LayerRelease", releaseFence,
2515 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002516 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002517
David Sodman15094112018-10-11 09:39:37 -07002518 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 }
Chia-I Wu83806892017-11-16 10:50:20 -08002520
2521 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002523 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002524 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002526 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002527 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002528 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002529 }
2530 }
2531
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 if (displayId) {
2533 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002534 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536}
2537
Mathias Agopian87baae12012-07-31 12:38:26 -07002538void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539{
Mathias Agopian841cde52012-03-01 15:44:37 -08002540 ATRACE_CALL();
2541
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002542 // here we keep a copy of the drawing state (that is the state that's
2543 // going to be overwritten by handleTransactionLocked()) outside of
2544 // mStateLock so that the side-effects of the State assignment
2545 // don't happen with mStateLock held (which can cause deadlocks).
2546 State drawingState(mDrawingState);
2547
Mathias Agopianca4d3602011-05-19 15:38:14 -07002548 Mutex::Autolock _l(mStateLock);
2549 const nsecs_t now = systemTime();
2550 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551
Mathias Agopianca4d3602011-05-19 15:38:14 -07002552 // Here we're guaranteed that some transaction flags are set
2553 // so we can call handleTransactionLocked() unconditionally.
2554 // We call getTransactionFlags(), which will also clear the flags,
2555 // with mStateLock held to guarantee that mCurrentState won't change
2556 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002557
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002558 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002559 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002560 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002561
Mathias Agopianca4d3602011-05-19 15:38:14 -07002562 mLastTransactionTime = systemTime() - now;
2563 mDebugInTransaction = 0;
2564 invalidateHwcGeometry();
2565 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002566}
2567
Lloyd Piqueba04e622017-12-14 17:11:26 -08002568void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2569 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570 const std::optional<DisplayIdentificationInfo> info =
2571 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002574 continue;
2575 }
2576
Lloyd Piqueba04e622017-12-14 17:11:26 -08002577 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002579 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 mPhysicalDisplayTokens[info->id] = new BBinder();
2581 DisplayDeviceState state;
2582 state.displayId = info->id;
2583 state.isSecure = true; // All physical displays are currently considered secure.
2584 state.displayName = info->name;
2585 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2586 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002587 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002589 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2592 if (index >= 0) {
2593 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2594 mInterceptor->saveDisplayDeletion(state.sequenceId);
2595 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002596 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598 }
2599
2600 processDisplayChangesLocked();
2601 }
2602
2603 mPendingHotplugEvents.clear();
2604}
2605
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002606void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2607 bool connected) {
2608 if (mUseScheduler) {
2609 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2610 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2611 } else {
2612 mEventThread->onHotplugReceived(displayType, connected);
2613 mSFEventThread->onHotplugReceived(displayType, connected);
2614 }
2615}
2616
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002619 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 const sp<IGraphicBufferProducer>& producer) {
2621 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002622 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002624 creationArgs.isSecure = state.isSecure;
2625 creationArgs.displaySurface = dispSurface;
2626 creationArgs.hasWideColorGamut = false;
2627 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002628
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2630 creationArgs.isPrimary = isInternalDisplay;
2631
2632 if (useColorManagement && displayId) {
2633 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002635 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002636 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002638
Dominik Laskowski7e045462018-05-30 13:02:02 -07002639 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002641 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 }
tangrobin6753a022018-08-10 10:58:54 +08002643 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645 if (displayId) {
2646 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002647 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002648 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002649 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650
Lloyd Pique90c115d2018-09-18 21:39:42 -07002651 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002653 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655 // Make sure that composition can never be stalled by a virtual display
2656 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002657 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002658 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2660 }
2661
Dominik Laskowski075d3172018-05-24 15:50:06 -07002662 creationArgs.displayInstallOrientation =
2663 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002664
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002666 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667
Lloyd Pique90c115d2018-09-18 21:39:42 -07002668 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669
2670 if (maxFrameBufferAcquiredBuffers >= 3) {
2671 nativeWindowSurface->preallocateBuffers();
2672 }
2673
2674 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002675 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002676 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002678 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002680 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2681 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002682 if (!state.isVirtual()) {
2683 LOG_ALWAYS_FATAL_IF(!displayId);
2684 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002685 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002686
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002687 display->setLayerStack(state.layerStack);
2688 display->setProjection(state.orientation, state.viewport, state.frame);
2689 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002691 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002692}
2693
Lloyd Pique347200f2017-12-14 17:00:15 -08002694void SurfaceFlinger::processDisplayChangesLocked() {
2695 // here we take advantage of Vector's copy-on-write semantics to
2696 // improve performance by skipping the transaction entirely when
2697 // know that the lists are identical
2698 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2699 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2700 if (!curr.isIdenticalTo(draw)) {
2701 mVisibleRegionsDirty = true;
2702 const size_t cc = curr.size();
2703 size_t dc = draw.size();
2704
2705 // find the displays that were removed
2706 // (ie: in drawing state but not in current state)
2707 // also handle displays that changed
2708 // (ie: displays that are in both lists)
2709 for (size_t i = 0; i < dc;) {
2710 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2711 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002712 // Save display IDs before disconnecting.
2713 const auto internalDisplayId = getInternalDisplayId();
2714 const auto externalDisplayId = getExternalDisplayId();
2715
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002717 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002718 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002719 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002720 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002721 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002723 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002724 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002725 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 } else {
2727 // this display is in both lists. see if something changed.
2728 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2731 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2732 if (state_binder != draw_binder) {
2733 // changing the surface is like destroying and
2734 // recreating the DisplayDevice, so we just remove it
2735 // from the drawing state, so that it get re-added
2736 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002738 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 mDrawingState.displays.removeItemsAt(i);
2742 dc--;
2743 // at this point we must loop to the next item
2744 continue;
2745 }
2746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 }
2751 if ((state.orientation != draw[i].orientation) ||
2752 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002753 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 }
2755 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002756 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 }
2758 }
2759 }
2760 ++i;
2761 }
2762
2763 // find displays that were added
2764 // (ie: in current state but not in drawing state)
2765 for (size_t i = 0; i < cc; i++) {
2766 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2767 const DisplayDeviceState& state(curr[i]);
2768
Lloyd Pique542307f2018-10-19 13:24:08 -07002769 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002770 sp<IGraphicBufferProducer> producer;
2771 sp<IGraphicBufferProducer> bqProducer;
2772 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002773 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002776 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 // Virtual displays without a surface are dormant:
2778 // they have external state (layer stack, projection,
2779 // etc.) but no internal state (i.e. a DisplayDevice).
2780 if (state.surface != nullptr) {
2781 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 int width = 0;
2784 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2785 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2786 int height = 0;
2787 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2788 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2789 int intFormat = 0;
2790 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2791 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002792 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002793
Dominik Laskowski075d3172018-05-24 15:50:06 -07002794 displayId =
2795 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002796 }
2797
2798 // TODO: Plumb requested format back up to consumer
2799
2800 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002801 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002802 bqProducer, bqConsumer,
2803 state.displayName);
2804
2805 dispSurface = vds;
2806 producer = vds;
2807 }
2808 } else {
2809 ALOGE_IF(state.surface != nullptr,
2810 "adding a supported display, but rendering "
2811 "surface is provided (%p), ignoring it",
2812 state.surface.get());
2813
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814 displayId = state.displayId;
2815 LOG_ALWAYS_FATAL_IF(!displayId);
2816 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 producer = bqProducer;
2818 }
2819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002821 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002823 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002825 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002826 LOG_ALWAYS_FATAL_IF(!displayId);
2827
2828 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002829 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002830 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002831 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002832 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002833 }
2834 }
2835 }
2836 }
2837 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002838
2839 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002840}
2841
Mathias Agopian87baae12012-07-31 12:38:26 -07002842void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002843{
Dan Stoza7dde5992015-05-22 09:51:44 -07002844 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002845 mCurrentState.traverseInZOrder([](Layer* layer) {
2846 layer->notifyAvailableFrames();
2847 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002848
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 /*
2850 * Traversal of the children
2851 * (perform the transaction for each of them if needed)
2852 */
2853
Robert Carr720e5062018-07-30 17:45:14 -07002854 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002855 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002856 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002858 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859
2860 const uint32_t flags = layer->doTransaction(0);
2861 if (flags & Layer::eVisibleRegion)
2862 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002863
2864 if (flags & Layer::eInputInfoChanged) {
2865 inputChanged = true;
2866 }
Robert Carr2047fae2016-11-28 14:09:09 -08002867 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 }
2869
2870 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002871 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 */
2873
Mathias Agopiane57f2922012-08-09 16:29:12 -07002874 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002875 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002876 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002877 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002879 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002880 // The transform hint might have changed for some layers
2881 // (either because a display has changed, or because a layer
2882 // as changed).
2883 //
2884 // Walk through all the layers in currentLayers,
2885 // and update their transform hint.
2886 //
2887 // If a layer is visible only on a single display, then that
2888 // display is used to calculate the hint, otherwise we use the
2889 // default display.
2890 //
2891 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2892 // the hint is set before we acquire a buffer from the surface texture.
2893 //
2894 // NOTE: layer transactions have taken place already, so we use their
2895 // drawing state. However, SurfaceFlinger's own transaction has not
2896 // happened yet, so we must use the current state layer list
2897 // (soon to become the drawing state list).
2898 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002899 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002900 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002901 bool first = true;
2902 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002903 // NOTE: we rely on the fact that layers are sorted by
2904 // layerStack first (so we don't have to traverse the list
2905 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002907 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002908 currentlayerStack = layerStack;
2909 // figure out if this layerstack is mirrored
2910 // (more than one display) if so, pick the default display,
2911 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 hintDisplay = nullptr;
2913 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002914 if (display->getCompositionDisplay()
2915 ->belongsInOutput(layer->getLayerStack(),
2916 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002917 if (hintDisplay) {
2918 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002919 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002920 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002921 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002922 }
2923 }
2924 }
2925 }
Chet Haase91d25932013-04-11 15:24:55 -07002926
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002928 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2929 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002930
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002931 // could be null when this layer is using a layerStack
2932 // that is not visible on any display. Also can occur at
2933 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002935 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002936
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002937 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002938 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002939 if (hintDisplay) {
2940 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002941 }
Robert Carr2047fae2016-11-28 14:09:09 -08002942
2943 first = false;
2944 });
Mathias Agopian84300952012-11-21 16:02:13 -08002945 }
2946
2947
Mathias Agopian3559b072012-08-15 13:46:03 -07002948 /*
2949 * Perform our own transaction if needed
2950 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951
2952 if (mLayersAdded) {
2953 mLayersAdded = false;
2954 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002955 mVisibleRegionsDirty = true;
2956 }
2957
2958 // some layers might have been removed, so
2959 // we need to update the regions they're exposing.
2960 if (mLayersRemoved) {
2961 mLayersRemoved = false;
2962 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002963 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002965 // this layer is not visible anymore
2966 // TODO: we could traverse the tree from front to back and
2967 // compute the actual visible region
2968 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002969 Region visibleReg;
2970 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002971 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002972 }
Robert Carr2047fae2016-11-28 14:09:09 -08002973 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 }
2975
2976 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002977
Vishnu Nairde19f852018-12-18 16:11:53 -08002978 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002979 updateInputWindows();
2980 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002981 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002982
Riley Andrews03414a12014-07-01 14:22:59 -07002983 updateCursorAsync();
2984}
2985
Robert Carr720e5062018-07-30 17:45:14 -07002986void SurfaceFlinger::updateInputWindows() {
2987 ATRACE_CALL();
2988
Vishnu Nairde19f852018-12-18 16:11:53 -08002989 if (mInputFlinger == nullptr) {
2990 return;
2991 }
2992
Robert Carr720e5062018-07-30 17:45:14 -07002993 Vector<InputWindowInfo> inputHandles;
2994
2995 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2996 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002997 // When calculating the screen bounds we ignore the transparent region since it may
2998 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002999 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003000 }
3001 });
3002 mInputFlinger->setInputWindows(inputHandles);
3003}
3004
chaviwfbe5d9c2018-12-26 12:23:37 -08003005void SurfaceFlinger::executeInputWindowCommands() {
3006 if (!mInputFlinger) {
3007 return;
3008 }
3009
3010 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3011 if (transferTouchFocusCommand.fromToken != nullptr &&
3012 transferTouchFocusCommand.toToken != nullptr &&
3013 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3014 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3015 transferTouchFocusCommand.toToken);
3016 }
3017 }
3018
3019 mInputWindowCommands.clear();
3020}
3021
Riley Andrews03414a12014-07-01 14:22:59 -07003022void SurfaceFlinger::updateCursorAsync()
3023{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003024 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003025 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003026 continue;
3027 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003029 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3030 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003031 }
3032 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003033}
3034
chaviw61626f22018-11-15 16:26:27 -08003035void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3036 if (layer->hasReadyFrame()) {
3037 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3038 if (layer->shouldPresentNow(expectedPresentTime)) {
3039 bool ignored = false;
3040 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3041 }
3042 }
3043 layer->releasePendingBuffer(systemTime());
3044}
3045
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046void SurfaceFlinger::commitTransaction()
3047{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003048 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003049 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 for (const auto& l : mLayersPendingRemoval) {
3051 recordBufferingStats(l->getName().string(),
3052 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003053
3054 // We need to release the HWC layers when the Layer is removed
3055 // from the current state otherwise the HWC layer just continues
3056 // showing at its last configured state until we eventually
3057 // abandon the buffer queue.
3058 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003059 l->destroyHwcLayersForAllDisplays();
3060 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003061 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003062 }
3063 mLayersPendingRemoval.clear();
3064 }
3065
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003066 // If this transaction is part of a window animation then the next frame
3067 // we composite should be considered an animation as well.
3068 mAnimCompositionPending = mAnimTransactionPending;
3069
Mathias Agopian4fec8732012-06-29 14:12:52 -07003070 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003071 // clear the "changed" flags in current state
3072 mCurrentState.colorMatrixChanged = false;
3073
Robert Carr1f0a16a2016-10-24 16:27:39 -07003074 mDrawingState.traverseInZOrder([](Layer* layer) {
3075 layer->commitChildList();
3076 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003077 mTransactionPending = false;
3078 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003079 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080}
3081
Lloyd Pique32cbe282018-10-19 13:09:22 -07003082void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003083 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003084 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003085 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003086
Lloyd Pique32cbe282018-10-19 13:09:22 -07003087 auto display = displayDevice->getCompositionDisplay();
3088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089 Region aboveOpaqueLayers;
3090 Region aboveCoveredLayers;
3091 Region dirty;
3092
Mathias Agopian87baae12012-07-31 12:38:26 -07003093 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094
Robert Carr2047fae2016-11-28 14:09:09 -08003095 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003096 // start with the whole surface at its current location
3097 const Layer::State& s(layer->getDrawingState());
3098
Jesse Hall01e29052013-02-19 16:13:35 -08003099 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003100 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003101 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003102 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003103
Mathias Agopianab028732010-03-16 16:41:46 -07003104 /*
3105 * opaqueRegion: area of a surface that is fully opaque.
3106 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003108
3109 /*
3110 * visibleRegion: area of a surface that is visible on screen
3111 * and not fully transparent. This is essentially the layer's
3112 * footprint minus the opaque regions above it.
3113 * Areas covered by a translucent surface are considered visible.
3114 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003116
3117 /*
3118 * coveredRegion: area of a surface that is covered by all
3119 * visible regions above it (which includes the translucent areas).
3120 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003122
Jesse Halla8026d22012-09-25 13:25:04 -07003123 /*
3124 * transparentRegion: area of a surface that is hinted to be completely
3125 * transparent. This is only used to tell when the layer has no visible
3126 * non-transparent regions and can be removed from the layer list. It
3127 * does not affect the visibleRegion of this layer or any layers
3128 * beneath it. The hint may not be correct if apps don't respect the
3129 * SurfaceView restrictions (which, sadly, some don't).
3130 */
3131 Region transparentRegion;
3132
Mathias Agopianab028732010-03-16 16:41:46 -07003133
3134 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003135 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003136 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003140 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003141 if (!visibleRegion.isEmpty()) {
3142 // Remove the transparent area from the visible region
3143 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003144 if (tr.preserveRects()) {
3145 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003146 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003147 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003148 // transformation too complex, can't do the
3149 // transparent region optimization.
3150 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003151 }
Mathias Agopianab028732010-03-16 16:41:46 -07003152 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153
Mathias Agopianab028732010-03-16 16:41:46 -07003154 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003156 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003157 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003158 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003159 // the opaque region is the layer's footprint
3160 opaqueRegion = visibleRegion;
3161 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
3163 }
3164
Robert Carre5f4f692018-01-12 13:12:28 -08003165 if (visibleRegion.isEmpty()) {
3166 layer->clearVisibilityRegions();
3167 return;
3168 }
3169
Mathias Agopianab028732010-03-16 16:41:46 -07003170 // Clip the covered region to the visible region
3171 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3172
3173 // Update aboveCoveredLayers for next (lower) layer
3174 aboveCoveredLayers.orSelf(visibleRegion);
3175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176 // subtract the opaque region covered by the layers above us
3177 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178
3179 // compute this layer's dirty region
3180 if (layer->contentDirty) {
3181 // we need to invalidate the whole region
3182 dirty = visibleRegion;
3183 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003184 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 layer->contentDirty = false;
3186 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003187 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003188 * the exposed region consists of two components:
3189 * 1) what's VISIBLE now and was COVERED before
3190 * 2) what's EXPOSED now less what was EXPOSED before
3191 *
3192 * note that (1) is conservative, we start with the whole
3193 * visible region but only keep what used to be covered by
3194 * something -- which mean it may have been exposed.
3195 *
3196 * (2) handles areas that were not covered by anything but got
3197 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003198 */
Mathias Agopianab028732010-03-16 16:41:46 -07003199 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003200 const Region oldVisibleRegion = layer->visibleRegion;
3201 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003202 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3203 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 }
3205 dirty.subtractSelf(aboveOpaqueLayers);
3206
3207 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003208 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209
Mathias Agopianab028732010-03-16 16:41:46 -07003210 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003212
Jesse Halla8026d22012-09-25 13:25:04 -07003213 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 layer->setVisibleRegion(visibleRegion);
3215 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003216 layer->setVisibleNonTransparentRegion(
3217 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003218 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219
Mathias Agopian87baae12012-07-31 12:38:26 -07003220 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221}
3222
Chia-I Wuab0c3192017-08-01 11:29:00 -07003223void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003224 for (const auto& [token, displayDevice] : mDisplays) {
3225 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003226 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003227 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003228 }
3229 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003230}
3231
Daniel Solomon42d04562019-01-20 21:03:19 -08003232void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3233 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3234 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3235 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3236 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3237 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3238 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3239 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3240 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3241 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3242 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3243 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3244 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3245}
3246
Dan Stoza6b9454d2014-11-07 16:00:59 -08003247bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003249 ALOGV("handlePageFlip");
3250
Brian Andersond6927fb2016-07-23 23:37:30 -07003251 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252
Mathias Agopian4fec8732012-06-29 14:12:52 -07003253 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003255 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003256
3257 // Store the set of layers that need updates. This set must not change as
3258 // buffers are being latched, as this could result in a deadlock.
3259 // Example: Two producers share the same command stream and:
3260 // 1.) Layer 0 is latched
3261 // 2.) Layer 0 gets a new frame
3262 // 2.) Layer 1 gets a new frame
3263 // 3.) Layer 1 is latched.
3264 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3265 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003266 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003267 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003268 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003269 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3270 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003271 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003272 } else {
3273 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003274 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003275 } else {
3276 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003277 }
Robert Carr2047fae2016-11-28 14:09:09 -08003278 });
3279
Lloyd Piquef2c79392018-12-20 16:23:33 -08003280 if (!mLayersWithQueuedFrames.empty()) {
3281 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3282 // writes to Layer current state. See also b/119481871
3283 Mutex::Autolock lock(mStateLock);
3284
3285 for (auto& layer : mLayersWithQueuedFrames) {
3286 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3287 layer->useSurfaceDamage();
3288 invalidateLayerStack(layer, dirty);
3289 if (layer->isBufferLatched()) {
3290 newDataLatched = true;
3291 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003292 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003293 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003294
Alec Mouri86770e52018-09-24 22:40:58 +00003295 // Clear the renderengine fence here...
3296 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3297 // clear instead of sp::clear.
3298 getBE().flushFence = Fence::NO_FENCE;
3299
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003300 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003301
Vishnu Nairde19f852018-12-18 16:11:53 -08003302 if (visibleRegions) {
3303 // Update input window info if the layer receives its first buffer.
3304 updateInputWindows();
3305 }
3306
Dan Stoza6b9454d2014-11-07 16:00:59 -08003307 // If we will need to wake up at some time in the future to deal with a
3308 // queued frame that shouldn't be displayed during this vsync period, wake
3309 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003310 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003311 signalLayerUpdate();
3312 }
3313
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003314 // enter boot animation on first buffer latch
3315 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3316 ALOGI("Enter boot animation");
3317 mBootStage = BootStage::BOOTANIMATION;
3318 }
3319
Dan Stoza6b9454d2014-11-07 16:00:59 -08003320 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003321 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003322}
3323
Mathias Agopianad456f92011-01-13 17:53:01 -08003324void SurfaceFlinger::invalidateHwcGeometry()
3325{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003326 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003327}
3328
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003330 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003331 auto display = displayDevice->getCompositionDisplay();
3332
Dan Stoza71433162014-02-04 16:22:36 -08003333 // We only need to actually compose the display if:
3334 // 1) It is being handled by hardware composer, which may need this to
3335 // keep its virtual display state machine in sync, or
3336 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003337 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003338 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003339 return;
3340 }
3341
Dan Stoza9e56aa02015-11-02 13:00:03 -08003342 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003343 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003344
3345 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003346 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347}
3348
Lloyd Pique32cbe282018-10-19 13:09:22 -07003349bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003350 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003351
Lloyd Pique32cbe282018-10-19 13:09:22 -07003352 auto display = displayDevice->getCompositionDisplay();
3353 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003354 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003355
3356 const Region bounds(displayState.bounds);
3357 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003358 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003359 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003360
Peiyong Lind3788632018-09-18 16:01:31 -07003361 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003362 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003363
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003364 // Framebuffer will live in this scope for GPU composition.
3365 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3366
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 if (hasClientComposition) {
3368 ALOGV("hasClientComposition");
3369
Lloyd Pique31cb2942018-10-19 17:23:03 -07003370 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003371
3372 if (buf == nullptr) {
3373 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3374 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003375 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003376 return false;
3377 }
3378
3379 // Bind the framebuffer in this scope.
3380 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3381 buf->getNativeBuffer());
3382
3383 if (fbo->getStatus() != NO_ERROR) {
3384 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003385 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003386 return false;
3387 }
3388
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003389 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003390 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003391 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003392 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003393 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003394 getRenderEngine().setOutputDataSpace(outputDataspace);
3395 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003396 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003397
Lloyd Pique441d5042018-10-18 16:49:51 -07003398 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003399 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003400 getHwComposer()
3401 .hasDisplayCapability(displayId,
3402 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003403
Peiyong Lind3788632018-09-18 16:01:31 -07003404 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003405 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3406 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003407 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003408 }
3409
Lloyd Pique31cb2942018-10-19 17:23:03 -07003410 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003411
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003412 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003413 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003414 // when using overlays, we assume a fully transparent framebuffer
3415 // NOTE: we could reduce how much we need to clear, for instance
3416 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003417 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003418 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003419 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003420 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003421 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003422 // we're left with the letterbox region
3423 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003424 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003425
3426 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003427 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003428
Mathias Agopianb9494d52012-04-18 02:28:45 -07003429 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003430 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003431 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003432 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003433 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003434 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003435
Lloyd Pique32cbe282018-10-19 13:09:22 -07003436 const Rect& bounds = displayState.bounds;
3437 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003438 if (scissor != bounds) {
3439 // scissor doesn't match the screen's dimensions, so we
3440 // need to clear everything outside of it and enable
3441 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003442
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003443 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003444 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003445 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003446 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003447
Mathias Agopian85d751c2012-08-29 16:59:24 -07003448 /*
3449 * and then, render the layers targeted at the framebuffer
3450 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003451
Dan Stoza9e56aa02015-11-02 13:00:03 -08003452 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003453 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003454 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003455 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003456 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003457 displayTransform.transform(layer->visibleRegion)));
3458 ALOGV("Layer: %s", layer->getName().string());
3459 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003460 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003461 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003462 case HWC2::Composition::Cursor:
3463 case HWC2::Composition::Device:
3464 case HWC2::Composition::Sideband:
3465 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003466 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003467 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003468 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003469 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003470 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003471 // never clear the very first layer since we're
3472 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003473 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003474 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003475 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003476 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003477 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003478 if (layer->hasColorTransform()) {
3479 mat4 tmpMatrix;
3480 if (applyColorMatrix) {
3481 tmpMatrix = mDrawingState.colorMatrix;
3482 }
3483 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003484 getRenderEngine().setColorTransform(tmpMatrix);
3485 } else {
3486 getRenderEngine().setColorTransform(colorMatrix);
3487 }
David Sodmanc1498e62018-09-12 14:36:26 -07003488 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003489 break;
3490 }
3491 default:
3492 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003493 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003494 } else {
3495 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003496 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003497 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003498 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003499
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003500 // Perform some cleanup steps if we used client composition.
3501 if (hasClientComposition) {
3502 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003503 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003504 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003505 // Clear out error flags here so that we don't wait until next
3506 // composition to log.
3507 getRenderEngine().checkErrors();
3508 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003509 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510}
3511
Chia-I Wu28e3a252018-09-07 12:05:02 -07003512void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003513 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003514 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515}
3516
Dan Stoza7d89d062015-04-30 13:29:25 -07003517status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003518 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003519 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003520 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003521 const sp<Layer>& parent,
3522 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003523{
Dan Stoza7d89d062015-04-30 13:29:25 -07003524 // add this layer to the current state list
3525 {
3526 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003527 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003528 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3529 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003530 return NO_MEMORY;
3531 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003532 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003533 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003534 } else if (parent == nullptr) {
3535 lbc->onRemovedFromCurrentState();
3536 } else if (parent->isRemovedFromCurrentState()) {
3537 parent->addChild(lbc);
3538 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003539 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003540 parent->addChild(lbc);
3541 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003542
Yiwei Zhang243b3782018-05-15 17:40:04 -07003543 if (gbc != nullptr) {
3544 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3545 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3546 mMaxGraphicBufferProducerListSize,
3547 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3548 mGraphicBufferProducerList.size(),
3549 mMaxGraphicBufferProducerListSize, mNumLayers);
3550 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003551 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003552 }
3553
Mathias Agopian96f08192010-06-02 23:28:45 -07003554 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003555 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003556
Dan Stoza7d89d062015-04-30 13:29:25 -07003557 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003558}
3559
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003560uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003561 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003562}
3563
Mathias Agopian3f844832013-08-07 21:24:32 -07003564uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003565 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566}
3567
Mathias Agopian3f844832013-08-07 21:24:32 -07003568uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003569 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003570}
3571
3572uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003573 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003574 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003575 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003577 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578 }
3579 return old;
3580}
3581
Marissa Wall713b63f2018-10-17 15:42:43 -07003582bool SurfaceFlinger::flushTransactionQueues() {
3583 Mutex::Autolock _l(mStateLock);
3584 auto it = mTransactionQueues.begin();
3585 while (it != mTransactionQueues.end()) {
3586 auto& [applyToken, transactionQueue] = *it;
3587
3588 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003589 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3590 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003591 break;
3592 }
chaviw273171b2018-12-26 11:46:30 -08003593 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003594 transactionQueue.pop();
3595 }
3596
3597 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3598 }
3599 return mTransactionQueues.empty();
3600}
3601
chaviwca27f252018-02-06 16:46:39 -08003602bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3603 for (const ComposerState& state : states) {
3604 // Here we need to check that the interface we're given is indeed
3605 // one of our own. A malicious client could give us a nullptr
3606 // IInterface, or one of its own or even one of our own but a
3607 // different type. All these situations would cause us to crash.
3608 if (state.client == nullptr) {
3609 return true;
3610 }
3611
3612 sp<IBinder> binder = IInterface::asBinder(state.client);
3613 if (binder == nullptr) {
3614 return true;
3615 }
3616
3617 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3618 return true;
3619 }
3620 }
3621 return false;
3622}
3623
Marissa Wall17b4e452018-12-26 16:32:34 -08003624bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3625 const Vector<ComposerState>& states) {
3626 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3627 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3628 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3629 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3630 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3631 return false;
3632 }
3633
Marissa Wall713b63f2018-10-17 15:42:43 -07003634 for (const ComposerState& state : states) {
3635 const layer_state_t& s = state.state;
3636 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3637 continue;
3638 }
3639 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003640 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003641 }
3642 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003643 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003644}
3645
3646void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3647 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003648 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003649 const InputWindowCommands& inputWindowCommands,
3650 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003651 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003652 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003653
chaviwca27f252018-02-06 16:46:39 -08003654 if (containsAnyInvalidClientState(states)) {
3655 return;
3656 }
3657
Marissa Wall713b63f2018-10-17 15:42:43 -07003658 // If its TransactionQueue already has a pending TransactionState or if it is pending
3659 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003660 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3661 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003662 setTransactionFlags(eTransactionNeeded);
3663 return;
3664 }
3665
chaviw273171b2018-12-26 11:46:30 -08003666 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003667}
3668
3669void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003670 const Vector<DisplayState>& displays, uint32_t flags,
3671 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003672 uint32_t transactionFlags = 0;
3673
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003674 if (flags & eAnimation) {
3675 // For window updates that are part of an animation we must wait for
3676 // previous animation "frames" to be handled.
3677 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003678 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 if (CC_UNLIKELY(err != NO_ERROR)) {
3680 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003681 // caller after a few seconds.
3682 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3683 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 mAnimTransactionPending = false;
3685 break;
3686 }
3687 }
3688 }
3689
chaviwca27f252018-02-06 16:46:39 -08003690 for (const DisplayState& display : displays) {
3691 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003692 }
3693
Marissa Walle2ffb422018-10-12 11:33:52 -07003694 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003695 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003696 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003697 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003698 // If the state doesn't require a traversal and there are callbacks, send them now
3699 if (!(clientStateFlags & eTraversalNeeded)) {
3700 mTransactionCompletedThread.sendCallbacks();
3701 }
3702 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003703
chaviw273171b2018-12-26 11:46:30 -08003704 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3705
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003706 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3707 // anyway. This can be used as a flush mechanism for previous async transactions.
3708 // Empty animation transaction can be used to simulate back-pressure, so also force a
3709 // transaction for empty animation transactions.
3710 if (transactionFlags == 0 &&
3711 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003712 transactionFlags = eTransactionNeeded;
3713 }
3714
Mathias Agopian386aa982011-11-07 21:58:03 -08003715 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003716 if (mInterceptor->isEnabled()) {
3717 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003718 }
Irvel468051e2016-06-13 16:44:44 -07003719
Mathias Agopian386aa982011-11-07 21:58:03 -08003720 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003721 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3722 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003723 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003724
3725 // if this is a synchronous transaction, wait for it to take effect
3726 // before returning.
3727 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003728 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003729 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003730 if (flags & eAnimation) {
3731 mAnimTransactionPending = true;
3732 }
3733 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003734 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3735 if (CC_UNLIKELY(err != NO_ERROR)) {
3736 // just in case something goes wrong in SF, return to the
3737 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003738 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3739 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003740 break;
3741 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003742 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743 }
3744}
3745
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003746uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3747 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3748 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003749
Mathias Agopiane57f2922012-08-09 16:29:12 -07003750 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003751 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3752
3753 const uint32_t what = s.what;
3754 if (what & DisplayState::eSurfaceChanged) {
3755 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3756 state.surface = s.surface;
3757 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003758 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003760 if (what & DisplayState::eLayerStackChanged) {
3761 if (state.layerStack != s.layerStack) {
3762 state.layerStack = s.layerStack;
3763 flags |= eDisplayTransactionNeeded;
3764 }
3765 }
3766 if (what & DisplayState::eDisplayProjectionChanged) {
3767 if (state.orientation != s.orientation) {
3768 state.orientation = s.orientation;
3769 flags |= eDisplayTransactionNeeded;
3770 }
3771 if (state.frame != s.frame) {
3772 state.frame = s.frame;
3773 flags |= eDisplayTransactionNeeded;
3774 }
3775 if (state.viewport != s.viewport) {
3776 state.viewport = s.viewport;
3777 flags |= eDisplayTransactionNeeded;
3778 }
3779 }
3780 if (what & DisplayState::eDisplaySizeChanged) {
3781 if (state.width != s.width) {
3782 state.width = s.width;
3783 flags |= eDisplayTransactionNeeded;
3784 }
3785 if (state.height != s.height) {
3786 state.height = s.height;
3787 flags |= eDisplayTransactionNeeded;
3788 }
3789 }
3790
Mathias Agopiane57f2922012-08-09 16:29:12 -07003791 return flags;
3792}
3793
Robert Carrd4ae7f32018-06-07 16:10:57 -07003794bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3795 IPCThreadState* ipc = IPCThreadState::self();
3796 const int pid = ipc->getCallingPid();
3797 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003798 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003799 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003800 return false;
3801 }
3802 return true;
3803}
3804
chaviwca27f252018-02-06 16:46:39 -08003805uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3806 const layer_state_t& s = composerState.state;
3807 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3808
Mathias Agopian13127d82013-03-05 17:47:11 -08003809 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003810 if (layer == nullptr) {
3811 return 0;
3812 }
3813
chaviw8b3871a2017-11-01 17:41:01 -07003814 uint32_t flags = 0;
3815
Garfield Tan8a3083e2018-12-03 13:21:07 -08003816 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003817 bool geometryAppliesWithResize =
3818 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003819
3820 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3821 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003822 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003823 layer->pushPendingState();
3824 }
3825
chaviw8b3871a2017-11-01 17:41:01 -07003826 if (what & layer_state_t::ePositionChanged) {
3827 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3828 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003829 }
chaviw8b3871a2017-11-01 17:41:01 -07003830 }
3831 if (what & layer_state_t::eLayerChanged) {
3832 // NOTE: index needs to be calculated before we update the state
3833 const auto& p = layer->getParent();
3834 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003835 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003836 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003837 mCurrentState.layersSortedByZ.removeAt(idx);
3838 mCurrentState.layersSortedByZ.add(layer);
3839 // we need traversal (state changed)
3840 // AND transaction (list changed)
3841 flags |= eTransactionNeeded|eTraversalNeeded;
3842 }
chaviw8b3871a2017-11-01 17:41:01 -07003843 } else {
3844 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003845 flags |= eTransactionNeeded|eTraversalNeeded;
3846 }
3847 }
chaviw8b3871a2017-11-01 17:41:01 -07003848 }
3849 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003850 // NOTE: index needs to be calculated before we update the state
3851 const auto& p = layer->getParent();
3852 if (p == nullptr) {
3853 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3854 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3855 mCurrentState.layersSortedByZ.removeAt(idx);
3856 mCurrentState.layersSortedByZ.add(layer);
3857 // we need traversal (state changed)
3858 // AND transaction (list changed)
3859 flags |= eTransactionNeeded|eTraversalNeeded;
3860 }
3861 } else {
3862 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3863 flags |= eTransactionNeeded|eTraversalNeeded;
3864 }
chaviw8b3871a2017-11-01 17:41:01 -07003865 }
3866 }
3867 if (what & layer_state_t::eSizeChanged) {
3868 if (layer->setSize(s.w, s.h)) {
3869 flags |= eTraversalNeeded;
3870 }
3871 }
3872 if (what & layer_state_t::eAlphaChanged) {
3873 if (layer->setAlpha(s.alpha))
3874 flags |= eTraversalNeeded;
3875 }
3876 if (what & layer_state_t::eColorChanged) {
3877 if (layer->setColor(s.color))
3878 flags |= eTraversalNeeded;
3879 }
Valerie Haued54efa2019-01-11 20:03:14 -08003880 if (what & layer_state_t::eColorAlphaChanged) {
3881 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3882 }
3883 if (what & layer_state_t::eColorDataspaceChanged) {
3884 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3885 }
Peiyong Lind3788632018-09-18 16:01:31 -07003886 if (what & layer_state_t::eColorTransformChanged) {
3887 if (layer->setColorTransform(s.colorTransform)) {
3888 flags |= eTraversalNeeded;
3889 }
3890 }
chaviw8b3871a2017-11-01 17:41:01 -07003891 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003892 // TODO: b/109894387
3893 //
3894 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3895 // rotation. To see the problem observe that if we have a square parent, and a child
3896 // of the same size, then we rotate the child 45 degrees around it's center, the child
3897 // must now be cropped to a non rectangular 8 sided region.
3898 //
3899 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3900 // private API, and the WindowManager only uses rotation in one case, which is on a top
3901 // level layer in which cropping is not an issue.
3902 //
3903 // However given that abuse of rotation matrices could lead to surfaces extending outside
3904 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3905 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3906 // transformations.
3907 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003908 flags |= eTraversalNeeded;
3909 }
3910 if (what & layer_state_t::eTransparentRegionChanged) {
3911 if (layer->setTransparentRegionHint(s.transparentRegion))
3912 flags |= eTraversalNeeded;
3913 }
3914 if (what & layer_state_t::eFlagsChanged) {
3915 if (layer->setFlags(s.flags, s.mask))
3916 flags |= eTraversalNeeded;
3917 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003918 if (what & layer_state_t::eCropChanged_legacy) {
3919 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003920 flags |= eTraversalNeeded;
3921 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003922 if (what & layer_state_t::eCornerRadiusChanged) {
3923 if (layer->setCornerRadius(s.cornerRadius))
3924 flags |= eTraversalNeeded;
3925 }
chaviw8b3871a2017-11-01 17:41:01 -07003926 if (what & layer_state_t::eLayerStackChanged) {
3927 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3928 // We only allow setting layer stacks for top level layers,
3929 // everything else inherits layer stack from its parent.
3930 if (layer->hasParent()) {
3931 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3932 layer->getName().string());
3933 } else if (idx < 0) {
3934 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3935 "that also does not appear in the top level layer list. Something"
3936 " has gone wrong.", layer->getName().string());
3937 } else if (layer->setLayerStack(s.layerStack)) {
3938 mCurrentState.layersSortedByZ.removeAt(idx);
3939 mCurrentState.layersSortedByZ.add(layer);
3940 // we need traversal (state changed)
3941 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003942 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003943 }
3944 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003945 if (what & layer_state_t::eDeferTransaction_legacy) {
3946 if (s.barrierHandle_legacy != nullptr) {
3947 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3948 } else if (s.barrierGbp_legacy != nullptr) {
3949 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003950 if (authenticateSurfaceTextureLocked(gbp)) {
3951 const auto& otherLayer =
3952 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003953 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003954 } else {
3955 ALOGE("Attempt to defer transaction to to an"
3956 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003957 }
3958 }
chaviw8b3871a2017-11-01 17:41:01 -07003959 // We don't trigger a traversal here because if no other state is
3960 // changed, we don't want this to cause any more work
3961 }
3962 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003963 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003964 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003965 if (!hadParent) {
3966 mCurrentState.layersSortedByZ.remove(layer);
3967 }
chaviw8b3871a2017-11-01 17:41:01 -07003968 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 }
3971 if (what & layer_state_t::eReparentChildren) {
3972 if (layer->reparentChildren(s.reparentHandle)) {
3973 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003974 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003975 }
chaviw8b3871a2017-11-01 17:41:01 -07003976 if (what & layer_state_t::eDetachChildren) {
3977 layer->detachChildren();
3978 }
3979 if (what & layer_state_t::eOverrideScalingModeChanged) {
3980 layer->setOverrideScalingMode(s.overrideScalingMode);
3981 // We don't trigger a traversal here because if no other state is
3982 // changed, we don't want this to cause any more work
3983 }
Marissa Wall61c58622018-07-18 10:12:20 -07003984 if (what & layer_state_t::eTransformChanged) {
3985 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3986 }
3987 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3988 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3989 flags |= eTraversalNeeded;
3990 }
3991 if (what & layer_state_t::eCropChanged) {
3992 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3993 }
Marissa Wall861616d2018-10-22 12:52:23 -07003994 if (what & layer_state_t::eFrameChanged) {
3995 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3996 }
Marissa Wall61c58622018-07-18 10:12:20 -07003997 if (what & layer_state_t::eBufferChanged) {
3998 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3999 }
4000 if (what & layer_state_t::eAcquireFenceChanged) {
4001 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4002 }
4003 if (what & layer_state_t::eDataspaceChanged) {
4004 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4005 }
4006 if (what & layer_state_t::eHdrMetadataChanged) {
4007 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4008 }
4009 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4010 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4011 }
4012 if (what & layer_state_t::eApiChanged) {
4013 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4014 }
4015 if (what & layer_state_t::eSidebandStreamChanged) {
4016 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4017 }
Robert Carr720e5062018-07-30 17:45:14 -07004018 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004019 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4020 layer->setInputInfo(s.inputInfo);
4021 flags |= eTraversalNeeded;
4022 } else {
4023 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4024 }
Robert Carr720e5062018-07-30 17:45:14 -07004025 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004026 if (what & layer_state_t::eMetadataChanged) {
4027 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4028 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004029 std::vector<sp<CallbackHandle>> callbackHandles;
4030 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4031 mTransactionCompletedThread.run();
4032 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4033 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4034 }
4035 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004036 if (what & layer_state_t::eCachedBufferChanged) {
4037 sp<GraphicBuffer> buffer =
4038 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4039 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4040 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004041 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4042 // Do not put anything that updates layer state or modifies flags after
4043 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004044 return flags;
4045}
4046
chaviw273171b2018-12-26 11:46:30 -08004047uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4048 uint32_t flags = 0;
4049 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4050 flags |= eTraversalNeeded;
4051 }
4052
4053 mInputWindowCommands.merge(inputWindowCommands);
4054 return flags;
4055}
4056
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004057status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4058 uint32_t h, PixelFormat format, uint32_t flags,
4059 LayerMetadata metadata, sp<IBinder>* handle,
4060 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004061 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004062 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004063 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004064 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004065 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004066
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004067 status_t result = NO_ERROR;
4068
4069 sp<Layer> layer;
4070
Cody Northropbc755282017-03-31 12:00:08 -06004071 String8 uniqueName = getUniqueLayerName(name);
4072
Mathias Agopian3165cc22012-08-08 19:42:09 -07004073 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004074 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004075 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4076 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004077
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004079 case ISurfaceComposerClient::eFXSurfaceBufferState:
4080 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4081 break;
chaviw13fdc492017-06-27 12:40:18 -07004082 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004083 // check if buffer size is set for color layer.
4084 if (w > 0 || h > 0) {
4085 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4086 int(w), int(h));
4087 return BAD_VALUE;
4088 }
4089
chaviw13fdc492017-06-27 12:40:18 -07004090 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004091 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004092 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004093 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004094 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004095 // check if buffer size is set for container layer.
4096 if (w > 0 || h > 0) {
4097 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4098 int(w), int(h));
4099 return BAD_VALUE;
4100 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004101 result = createContainerLayer(client,
4102 uniqueName, w, h, flags,
4103 handle, &layer);
4104 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004105 default:
4106 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107 break;
4108 }
4109
Dan Stoza7d89d062015-04-30 13:29:25 -07004110 if (result != NO_ERROR) {
4111 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004113
Chia-I Wuab0c3192017-08-01 11:29:00 -07004114 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4115 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004116 if (metadata.has(METADATA_WINDOW_TYPE)) {
4117 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4118 if (windowType == 441731) {
4119 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4120 layer->setPrimaryDisplayOnly();
4121 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004122 }
4123
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004124 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004125
Robert Carrb89ea9d2018-12-10 13:01:14 -08004126 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4127 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4128 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004129 if (result != NO_ERROR) {
4130 return result;
4131 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004132 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004133
4134 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004135 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136}
4137
Cody Northropbc755282017-03-31 12:00:08 -06004138String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4139{
4140 bool matchFound = true;
4141 uint32_t dupeCounter = 0;
4142
4143 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4144 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4145
Dan Stoza436ccf32018-06-21 12:10:12 -07004146 // Grab the state lock since we're accessing mCurrentState
4147 Mutex::Autolock lock(mStateLock);
4148
Cody Northropbc755282017-03-31 12:00:08 -06004149 // Loop over layers until we're sure there is no matching name
4150 while (matchFound) {
4151 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004152 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004153 if (layer->getName() == uniqueName) {
4154 matchFound = true;
4155 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4156 }
4157 });
4158 }
4159
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004160 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4161 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004162
4163 return uniqueName;
4164}
4165
Marissa Wallfd668622018-05-10 10:21:13 -07004166status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4167 uint32_t w, uint32_t h, uint32_t flags,
4168 PixelFormat& format, sp<IBinder>* handle,
4169 sp<IGraphicBufferProducer>* gbp,
4170 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004171 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004172 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173 case PIXEL_FORMAT_TRANSPARENT:
4174 case PIXEL_FORMAT_TRANSLUCENT:
4175 format = PIXEL_FORMAT_RGBA_8888;
4176 break;
4177 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004178 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179 break;
4180 }
4181
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004182 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004183 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004184 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004185 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004186 *handle = layer->getHandle();
4187 *gbp = layer->getProducer();
4188 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004190
Marissa Wallfd668622018-05-10 10:21:13 -07004191 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004192 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193}
4194
Marissa Wall61c58622018-07-18 10:12:20 -07004195status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4196 uint32_t w, uint32_t h, uint32_t flags,
4197 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004198 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004199 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004200 *handle = layer->getHandle();
4201 *outLayer = layer;
4202
4203 return NO_ERROR;
4204}
4205
chaviw13fdc492017-06-27 12:40:18 -07004206status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004207 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004208 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004210 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004211 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004212 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004213}
4214
Robert Carr6b3f6c52018-08-13 13:05:17 -07004215status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4216 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4217 sp<IBinder>* handle, sp<Layer>* outLayer)
4218{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004219 *outLayer =
4220 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004221 *handle = (*outLayer)->getHandle();
4222 return NO_ERROR;
4223}
4224
4225
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004226void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004227 mLayersPendingRemoval.add(layer);
4228 mLayersRemoved = true;
4229 setTransactionFlags(eTransactionNeeded);
4230}
4231
Robert Carr695d5282018-12-18 15:27:58 -08004232void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004233{
Robert Carr2e102c92018-10-23 12:11:15 -07004234 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004235 // If a layer has a parent, we allow it to out-live it's handle
4236 // with the idea that the parent holds a reference and will eventually
4237 // be cleaned up. However no one cleans up the top-level so we do so
4238 // here.
4239 if (layer->getParent() == nullptr) {
4240 mCurrentState.layersSortedByZ.remove(layer);
4241 }
4242 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004243 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004244}
4245
Mathias Agopianb60314a2012-04-10 22:09:54 -07004246// ---------------------------------------------------------------------------
4247
Andy McFadden13a082e2012-08-24 10:16:42 -07004248void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 const auto display = getDefaultDisplayDeviceLocked();
4250 if (!display) return;
4251
4252 const sp<IBinder> token = display->getDisplayToken().promote();
4253 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004254
Jesse Hall01e29052013-02-19 16:13:35 -08004255 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004256 Vector<ComposerState> state;
4257 Vector<DisplayState> displays;
4258 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004259 d.what = DisplayState::eDisplayProjectionChanged |
4260 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004261 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004262 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004263 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004264 d.frame.makeInvalid();
4265 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004266 d.width = 0;
4267 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004268 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004269 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004270
Dominik Laskowskie9774092018-12-11 10:04:24 -08004271 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004272
Dominik Laskowski83b88212018-12-11 13:34:06 -08004273 const nsecs_t vsyncPeriod = getVsyncPeriod();
4274 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004275
Brian Andersond0010582017-03-07 13:20:31 -08004276 // Use phase of 0 since phase is not known.
4277 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004278 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004279 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004280}
4281
4282void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004283 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004284 postMessageAsync(
4285 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004286}
4287
Dominik Laskowskie9774092018-12-11 10:04:24 -08004288void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004289 if (display->isVirtual()) {
4290 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004291 return;
4292 }
4293
Dominik Laskowski075d3172018-05-24 15:50:06 -07004294 const auto displayId = display->getId();
4295 LOG_ALWAYS_FATAL_IF(!displayId);
4296
Dominik Laskowski34157762018-10-31 13:07:19 -07004297 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298
4299 int currentMode = display->getPowerMode();
4300 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004301 return;
4302 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004303
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004304 display->setPowerMode(mode);
4305
Lloyd Pique4dccc412018-01-22 17:21:36 -08004306 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004307 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004308 }
4309
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004310 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004311 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004312 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004313 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004314 if (mUseScheduler) {
4315 mScheduler->onScreenAcquired(mAppConnectionHandle);
4316 } else {
4317 mEventThread->onScreenAcquired();
4318 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004319 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004320 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004321
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004322 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004323 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004324 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004325
4326 struct sched_param param = {0};
4327 param.sched_priority = 1;
4328 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4329 ALOGW("Couldn't set SCHED_FIFO on display on");
4330 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004331 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004332 // Turn off the display
4333 struct sched_param param = {0};
4334 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4335 ALOGW("Couldn't set SCHED_OTHER on display off");
4336 }
4337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004339 if (mUseScheduler) {
4340 mScheduler->disableHardwareVsync(true);
4341 } else {
4342 disableHardwareVsync(true); // also cancels any in-progress resync
4343 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004344 if (mUseScheduler) {
4345 mScheduler->onScreenReleased(mAppConnectionHandle);
4346 } else {
4347 mEventThread->onScreenReleased();
4348 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004349 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004350
Dominik Laskowski075d3172018-05-24 15:50:06 -07004351 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004352 mVisibleRegionsDirty = true;
4353 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004354 } else if (mode == HWC_POWER_MODE_DOZE ||
4355 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004356 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004357 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004358 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004359 if (mUseScheduler) {
4360 mScheduler->onScreenAcquired(mAppConnectionHandle);
4361 } else {
4362 mEventThread->onScreenAcquired();
4363 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004364 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004365 }
4366 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4367 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004368 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004369 if (mUseScheduler) {
4370 mScheduler->disableHardwareVsync(true);
4371 } else {
4372 disableHardwareVsync(true); // also cancels any in-progress resync
4373 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004374 if (mUseScheduler) {
4375 mScheduler->onScreenReleased(mAppConnectionHandle);
4376 } else {
4377 mEventThread->onScreenReleased();
4378 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004379 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004380 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004381 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004382 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004383 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004384 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004386 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004387 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004388 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004389 // Update refresh rate stats.
4390 mRefreshRateStats->setPowerMode(mode);
4391 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004392 }
4393
Dominik Laskowski34157762018-10-31 13:07:19 -07004394 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004395}
4396
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004397void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004398 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004399 const auto display = getDisplayDevice(displayToken);
4400 if (!display) {
4401 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4402 displayToken.get());
4403 } else if (display->isVirtual()) {
4404 ALOGW("Attempt to set power mode %d for virtual display", mode);
4405 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004406 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004407 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004408 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004409}
4410
4411// ---------------------------------------------------------------------------
4412
Dominik Laskowskic2867142019-01-21 11:33:38 -08004413status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4414 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004415 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004416
Mathias Agopianbd115332013-04-18 16:41:04 -07004417 IPCThreadState* ipc = IPCThreadState::self();
4418 const int pid = ipc->getCallingPid();
4419 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004420
Mathias Agopianbd115332013-04-18 16:41:04 -07004421 if ((uid != AID_SHELL) &&
4422 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4424 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004425 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004426 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004427 // (this would indicate SF is stuck, but we want to be able to
4428 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004429 status_t err = mStateLock.timedLock(s2ns(1));
4430 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004431 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004432 StringAppendF(&result,
4433 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4434 "(no locks held)\n",
4435 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004436 }
4437
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004439
Dominik Laskowskic2867142019-01-21 11:33:38 -08004440 static const std::unordered_map<std::string, Dumper> dumpers = {
4441 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4442 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4443 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4444 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4445 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4446 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4447 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4448 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4449 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4450 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4451 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4452 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4453 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004454 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4456 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004459
Dominik Laskowskic2867142019-01-21 11:33:38 -08004460 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4461 (it->second)(args, asProto, result);
4462 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004463 if (asProto) {
4464 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4465 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4466 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004467 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004468 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004469 }
4470
Mathias Agopian9795c422009-08-26 16:36:26 -07004471 if (locked) {
4472 mStateLock.unlock();
4473 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 return NO_ERROR;
4477}
4478
Dominik Laskowskic2867142019-01-21 11:33:38 -08004479void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 mCurrentState.traverseInZOrder(
4481 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004482}
4483
Dominik Laskowskic2867142019-01-21 11:33:38 -08004484void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004485 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004486
Dominik Laskowskic2867142019-01-21 11:33:38 -08004487 if (args.size() > 1) {
4488 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004489 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004490 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004491 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004492 }
Robert Carr2047fae2016-11-28 14:09:09 -08004493 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004494 } else {
4495 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004496 }
4497}
4498
Dominik Laskowskic2867142019-01-21 11:33:38 -08004499void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004500 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004501 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004502 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004503 }
Robert Carr2047fae2016-11-28 14:09:09 -08004504 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004505
Svetoslavd85084b2014-03-20 10:28:31 -07004506 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004507}
4508
Dominik Laskowskic2867142019-01-21 11:33:38 -08004509void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4510 mTimeStats->parseArgs(asProto, args, result);
4511}
4512
Jamie Gennis6547ff42013-07-16 20:12:42 -07004513// This should only be called from the main thread. Otherwise it would need
4514// the lock and should use mCurrentState rather than mDrawingState.
4515void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004516 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004517 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004518 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004519
4520 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4521}
4522
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004524 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004525
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004526 if (isLayerTripleBufferingDisabled())
4527 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004528
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4530 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4531 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4532 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4533 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4534 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004535 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004536}
4537
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004538void SurfaceFlinger::dumpVSync(std::string& result) const {
4539 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4540 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4541 StringAppendF(&result,
4542 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4543 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4544 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4545 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4546 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4547 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4548
4549 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4550
4551 if (mUseScheduler) {
4552 mScheduler->dump(mAppConnectionHandle, result);
4553 } else {
4554 mEventThread->dump(result);
4555 }
4556}
4557
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4559 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004560 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4561 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004562 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004563 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004565 }
David Sodman4a36e932017-11-07 14:29:47 -08004566 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004567 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004568 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4570 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004571}
4572
Dan Stozae77c7662016-05-13 11:37:28 -07004573void SurfaceFlinger::recordBufferingStats(const char* layerName,
4574 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004575 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4576 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004577 for (const auto& segment : history) {
4578 if (!segment.usedThirdBuffer) {
4579 stats.twoBufferTime += segment.totalTime;
4580 }
4581 if (segment.occupancyAverage < 1.0f) {
4582 stats.doubleBufferedTime += segment.totalTime;
4583 } else if (segment.occupancyAverage < 2.0f) {
4584 stats.tripleBufferedTime += segment.totalTime;
4585 }
4586 ++stats.numSegments;
4587 stats.totalTime += segment.totalTime;
4588 }
4589}
4590
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4592 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004593
4594 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4595 const size_t count = currentLayers.size();
4596 for (size_t i=0 ; i<count ; i++) {
4597 currentLayers[i]->dumpFrameEvents(result);
4598 }
4599}
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004602 result.append("Buffering stats:\n");
4603 result.append(" [Layer name] <Active time> <Two buffer> "
4604 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004605 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004606 typedef std::tuple<std::string, float, float, float> BufferTuple;
4607 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004608 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004609 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004610 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004611 if (stats.numSegments == 0) {
4612 continue;
4613 }
4614 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4615 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4616 stats.totalTime;
4617 float doubleBufferRatio = static_cast<float>(
4618 stats.doubleBufferedTime) / stats.totalTime;
4619 float tripleBufferRatio = static_cast<float>(
4620 stats.tripleBufferedTime) / stats.totalTime;
4621 sorted.insert({activeTime, {name, twoBufferRatio,
4622 doubleBufferRatio, tripleBufferRatio}});
4623 }
4624 for (const auto& sortedPair : sorted) {
4625 float activeTime = sortedPair.first;
4626 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4628 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004629 }
4630 result.append("\n");
4631}
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004634 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004635 const auto displayId = display->getId();
4636 if (!displayId) {
4637 continue;
4638 }
4639 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004640 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result,
4645 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4646 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 uint8_t port;
4648 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004649 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004650 result.append("no identification data\n");
4651 continue;
4652 }
4653
4654 if (!isEdid(data)) {
4655 result.append("unknown identification data: ");
4656 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 }
4659 result.append("\n");
4660 continue;
4661 }
4662
4663 const auto edid = parseEdid(data);
4664 if (!edid) {
4665 result.append("invalid EDID: ");
4666 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004668 }
4669 result.append("\n");
4670 continue;
4671 }
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004674 result.append(edid->displayName.data(), edid->displayName.length());
4675 result.append("\"\n");
4676 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004677}
4678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4680 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4681 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4682 StringAppendF(&result, "DisplayColorSetting: %s\n",
4683 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684
4685 // TODO: print out if wide-color mode is active or not
4686
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004687 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 const auto displayId = display->getId();
4689 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004690 continue;
4691 }
4692
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004695 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004697 }
4698
Lloyd Pique32cbe282018-10-19 13:09:22 -07004699 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, " Current color mode: %s (%d)\n",
4701 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004702 }
4703 result.append("\n");
4704}
4705
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004707 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004708 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4709 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004710 continue;
4711 }
4712
Dominik Laskowski05275f12018-11-01 15:03:24 -07004713 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4715 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004716 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 compositionInfo.dump(result, nullptr);
4718 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004719 }
4720 }
David Sodman7e4ae112018-02-09 15:02:28 -08004721}
4722
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004723LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004724 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004725 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4726 const State& state = useDrawing ? mDrawingState : mCurrentState;
4727 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004728 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004729 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004730 });
4731
4732 return layersProto;
4733}
4734
Lloyd Pique32cbe282018-10-19 13:09:22 -07004735LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004736 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004737
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004738 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004739 resolution->set_w(displayDevice.getWidth());
4740 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004741
Lloyd Pique32cbe282018-10-19 13:09:22 -07004742 auto display = displayDevice.getCompositionDisplay();
4743 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004744
Lloyd Pique32cbe282018-10-19 13:09:22 -07004745 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4746 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4747 layersProto.set_global_transform(displayState.orientation);
4748
4749 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004750 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004752 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004753 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004754 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004755 }
4756 });
4757
4758 return layersProto;
4759}
4760
Dominik Laskowskic2867142019-01-21 11:33:38 -08004761void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4762 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 Colorizer colorizer(colorize);
4764
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765 // figure out if we're stuck somewhere
4766 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004767 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4769
4770 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004771 * Dump library configuration.
4772 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773
4774 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004775 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004777 appendSfConfigString(result);
4778 appendUiConfigString(result);
4779 appendGuiConfigString(result);
4780 result.append("\n");
4781
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004782 result.append("\nDisplay identification data:\n");
4783 dumpDisplayIdentificationData(result);
4784
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004785 result.append("\nWide-Color information:\n");
4786 dumpWideColorInfo(result);
4787
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004788 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004789 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004790 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004791 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004792 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004793
Andy McFadden41d67d72014-04-25 16:58:34 -07004794 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004795 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004796 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004797 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004798 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004799
Dan Stozab90cf072015-03-05 11:05:59 -08004800 dumpStaticScreenStats(result);
4801 result.append("\n");
4802
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004804
Dan Stozae77c7662016-05-13 11:37:28 -07004805 dumpBufferingStats(result);
4806
Andy McFadden4803b742012-09-24 19:07:20 -07004807 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808 * Dump the visible layer list
4809 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004810 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4812 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4813 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004815
Chia-I Wu2f884132018-09-13 15:17:58 -07004816 {
4817 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4818 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004820 result.append("\n");
4821 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822
David Sodman7e4ae112018-02-09 15:02:28 -08004823 result.append("\nFrame-Composition information:\n");
4824 dumpFrameCompositionInfo(result);
4825 result.append("\n");
4826
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004827 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004828 * Dump Display state
4829 */
4830
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004831 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004833 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004834 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004835 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004836 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004837 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004838
4839 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004840 * Dump SurfaceFlinger global state
4841 */
4842
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004843 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004844 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004847 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848
Dominik Laskowski075d3172018-05-24 15:50:06 -07004849 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004850 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4851 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004852 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4853 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004854 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result,
4856 " transaction-flags : %08x\n"
4857 " gpu_to_cpu_unsupported : %d\n",
4858 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004859
Dominik Laskowski075d3172018-05-24 15:50:06 -07004860 if (const auto displayId = getInternalDisplayId();
4861 displayId && getHwComposer().isConnected(*displayId)) {
4862 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result,
4864 " refresh-rate : %f fps\n"
4865 " x-dpi : %f\n"
4866 " y-dpi : %f\n",
4867 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4868 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004869 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004870
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004872
Dan Stozae22aec72016-08-01 13:20:59 -07004873 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004874 * Tracing state
4875 */
4876 mTracing.dump(result);
4877 result.append("\n");
4878
4879 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004880 * HWC layer minidump
4881 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004882 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004883 const auto displayId = display->getId();
4884 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004885 continue;
4886 }
4887
Yiwei Zhang5434a782018-12-05 18:06:32 -08004888 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004889 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004890 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004891 result.append("\n");
4892 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004893
4894 /*
4895 * Dump HWComposer state
4896 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004897 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004898 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004899 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004900 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004901 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004902 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903
4904 /*
4905 * Dump gralloc state
4906 */
4907 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4908 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004909
4910 /*
4911 * Dump VrFlinger state if in use.
4912 */
4913 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4914 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004915 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004916 result.append("\n");
4917 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004918
4919 /**
4920 * Scheduler dump state.
4921 */
4922 if (mUseScheduler) {
4923 result.append("\nScheduler state:\n");
4924 result.append(mScheduler->doDump() + "\n");
4925 result.append(mRefreshRateStats->doDump() + "\n");
4926 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004927}
4928
Dominik Laskowski075d3172018-05-24 15:50:06 -07004929const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004930 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004931 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004932 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004933 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004934 }
4935 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004936
Dominik Laskowski34157762018-10-31 13:07:19 -07004937 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004938 static const Vector<sp<Layer>> empty;
4939 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004940}
4941
Keun young Park63f165f2012-08-31 10:53:36 -07004942bool SurfaceFlinger::startDdmConnection()
4943{
4944 void* libddmconnection_dso =
4945 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4946 if (!libddmconnection_dso) {
4947 return false;
4948 }
4949 void (*DdmConnection_start)(const char* name);
4950 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004951 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004952 if (!DdmConnection_start) {
4953 dlclose(libddmconnection_dso);
4954 return false;
4955 }
4956 (*DdmConnection_start)(getServiceName());
4957 return true;
4958}
4959
Chia-I Wu28f320b2018-05-03 11:02:56 -07004960void SurfaceFlinger::updateColorMatrixLocked() {
4961 mat4 colorMatrix;
4962 if (mGlobalSaturationFactor != 1.0f) {
4963 // Rec.709 luma coefficients
4964 float3 luminance{0.213f, 0.715f, 0.072f};
4965 luminance *= 1.0f - mGlobalSaturationFactor;
4966 mat4 saturationMatrix = mat4(
4967 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4968 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4969 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4970 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4971 );
4972 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4973 } else {
4974 colorMatrix = mClientColorMatrix * mDaltonizer();
4975 }
4976
4977 if (mCurrentState.colorMatrix != colorMatrix) {
4978 mCurrentState.colorMatrix = colorMatrix;
4979 mCurrentState.colorMatrixChanged = true;
4980 setTransactionFlags(eTransactionNeeded);
4981 }
4982}
4983
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004984status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004985#pragma clang diagnostic push
4986#pragma clang diagnostic error "-Wswitch-enum"
4987 switch (static_cast<ISurfaceComposerTag>(code)) {
4988 // These methods should at minimum make sure that the client requested
4989 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004990 case BOOT_FINISHED:
4991 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 case CREATE_DISPLAY:
4993 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004994 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004995 case GET_ACTIVE_COLOR_MODE:
4996 case GET_ANIMATION_FRAME_STATS:
4997 case GET_HDR_CAPABILITIES:
4998 case SET_ACTIVE_CONFIG:
4999 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005000 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005001 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005002 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005003 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5004 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005005 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5006 IPCThreadState* ipc = IPCThreadState::self();
5007 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5008 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005009 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005010 }
Robert Carr1db73f62016-12-21 12:58:51 -08005011 return OK;
5012 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005014 IPCThreadState* ipc = IPCThreadState::self();
5015 const int pid = ipc->getCallingPid();
5016 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5018 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005019 return PERMISSION_DENIED;
5020 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005021 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005022 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 // Used by apps to hook Choreographer to SurfaceFlinger.
5024 case CREATE_DISPLAY_EVENT_CONNECTION:
5025 // The following calls are currently used by clients that do not
5026 // request necessary permissions. However, they do not expose any secret
5027 // information, so it is OK to pass them.
5028 case AUTHENTICATE_SURFACE:
5029 case GET_ACTIVE_CONFIG:
5030 case GET_BUILT_IN_DISPLAY:
5031 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005032 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005033 case GET_DISPLAY_CONFIGS:
5034 case GET_DISPLAY_STATS:
5035 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5036 // Calling setTransactionState is safe, because you need to have been
5037 // granted a reference to Client* and Handle* to do anything with it.
5038 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005039 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005040 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005041 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005042 case GET_PROTECTED_CONTENT_SUPPORT:
5043 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005044 case UNCACHE_BUFFER:
5045 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005046 return OK;
5047 }
5048 case CAPTURE_LAYERS:
5049 case CAPTURE_SCREEN: {
5050 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005051 IPCThreadState* ipc = IPCThreadState::self();
5052 const int pid = ipc->getCallingPid();
5053 const int uid = ipc->getCallingUid();
5054 if ((uid != AID_GRAPHICS) &&
5055 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5056 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5057 return PERMISSION_DENIED;
5058 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059 return OK;
5060 }
5061 // The following codes are deprecated and should never be allowed to access SF.
5062 case CONNECT_DISPLAY_UNUSED:
5063 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5064 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5065 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005066 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005067 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005068
5069 // These codes are used for the IBinder protocol to either interrogate the recipient
5070 // side of the transaction for its canonical interface descriptor or to dump its state.
5071 // We let them pass by default.
5072 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5073 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5074 code == IBinder::SYSPROPS_TRANSACTION) {
5075 return OK;
5076 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005077 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005078 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005079 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005080 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5081 return OK;
5082 }
5083 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5084 return PERMISSION_DENIED;
5085#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005086}
5087
Ana Krulec13be8ad2018-08-21 02:43:56 +00005088status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5089 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005090 status_t credentialCheck = CheckTransactCodeCredentials(code);
5091 if (credentialCheck != OK) {
5092 return credentialCheck;
5093 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005094
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5096 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005097 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005098 IPCThreadState* ipc = IPCThreadState::self();
5099 const int uid = ipc->getCallingUid();
5100 if (CC_UNLIKELY(uid != AID_SYSTEM
5101 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005102 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005103 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005104 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005105 return PERMISSION_DENIED;
5106 }
5107 int n;
5108 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005109 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005110 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005111 return NO_ERROR;
5112 case 1002: // SHOW_UPDATES
5113 n = data.readInt32();
5114 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005115 invalidateHwcGeometry();
5116 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005118 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005119 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005120 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005122 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005123 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005124 setTransactionFlags(
5125 eTransactionNeeded|
5126 eDisplayTransactionNeeded|
5127 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005128 return NO_ERROR;
5129 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005130 case 1006:{ // send empty update
5131 signalRefresh();
5132 return NO_ERROR;
5133 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005134 case 1008: // toggle use of hw composer
5135 n = data.readInt32();
5136 mDebugDisableHWC = n ? 1 : 0;
5137 invalidateHwcGeometry();
5138 repaintEverything();
5139 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005140 case 1009: // toggle use of transform hint
5141 n = data.readInt32();
5142 mDebugDisableTransformHint = n ? 1 : 0;
5143 invalidateHwcGeometry();
5144 repaintEverything();
5145 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005146 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005147 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005148 reply->writeInt32(0);
5149 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005150 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005151 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 return NO_ERROR;
5153 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005154 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005155 if (!display) {
5156 return NAME_NOT_FOUND;
5157 }
5158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005160 return NO_ERROR;
5161 }
5162 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005163 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005164 // daltonize
5165 n = data.readInt32();
5166 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005167 case 1:
5168 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5169 break;
5170 case 2:
5171 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5172 break;
5173 case 3:
5174 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5175 break;
5176 default:
5177 mDaltonizer.setType(ColorBlindnessType::None);
5178 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005179 }
5180 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005181 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005182 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005183 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005184 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185
5186 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005187 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005188 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005189 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 // apply a color matrix
5192 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005193 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005194 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005195 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005196 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005197 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005198 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005199 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005200 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005201 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005202 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005203
5204 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5205 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005206 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005207 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5208 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5209 }
5210
Chia-I Wu28f320b2018-05-03 11:02:56 -07005211 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005212 return NO_ERROR;
5213 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005214 // This is an experimental interface
5215 // Needs to be shifted to proper binder interface when we productize
5216 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005217 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005218 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005219 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005220 return NO_ERROR;
5221 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005222 case 1017: {
5223 n = data.readInt32();
5224 mForceFullDamage = static_cast<bool>(n);
5225 return NO_ERROR;
5226 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005227 case 1018: { // Modify Choreographer's phase offset
5228 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005229 if (mUseScheduler) {
5230 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5231 } else {
5232 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5233 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005234 return NO_ERROR;
5235 }
5236 case 1019: { // Modify SurfaceFlinger's phase offset
5237 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005238 if (mUseScheduler) {
5239 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5240 } else {
5241 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5242 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005243 return NO_ERROR;
5244 }
Irvel468051e2016-06-13 16:44:44 -07005245 case 1020: { // Layer updates interceptor
5246 n = data.readInt32();
5247 if (n) {
5248 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005249 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005250 }
5251 else{
5252 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005253 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005254 }
5255 return NO_ERROR;
5256 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005257 case 1021: { // Disable HWC virtual displays
5258 n = data.readInt32();
5259 mUseHwcVirtualDisplays = !n;
5260 return NO_ERROR;
5261 }
Romain Guy0147a172017-06-01 13:53:56 -07005262 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005263 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005264 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005265
Chia-I Wu28f320b2018-05-03 11:02:56 -07005266 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005267 return NO_ERROR;
5268 }
Romain Guy54f154a2017-10-24 21:40:32 +01005269 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005270 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005271 invalidateHwcGeometry();
5272 repaintEverything();
5273 return NO_ERROR;
5274 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005275 // Deprecate, use 1030 to check whether the device is color managed.
5276 case 1024: {
5277 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005278 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005279 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005280 n = data.readInt32();
5281 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005282 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005283 mTracing.enable();
5284 doTracing("tracing.enable");
5285 reply->writeInt32(NO_ERROR);
5286 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005287 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005288 status_t err = mTracing.disable();
5289 reply->writeInt32(err);
5290 }
5291 return NO_ERROR;
5292 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005293 case 1026: { // Get layer tracing status
5294 reply->writeBool(mTracing.isEnabled());
5295 return NO_ERROR;
5296 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005297 // Is a DisplayColorSetting supported?
5298 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005299 const auto display = getDefaultDisplayDevice();
5300 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005301 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005302 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005303
5304 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5305 switch (setting) {
5306 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005307 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005308 break;
5309 case DisplayColorSetting::UNMANAGED:
5310 reply->writeBool(true);
5311 break;
5312 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005313 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005314 break;
5315 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005316 reply->writeBool(
5317 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005318 break;
5319 }
5320 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005321 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005322 // Is VrFlinger active?
5323 case 1028: {
5324 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005325 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005326 return NO_ERROR;
5327 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005328 // Is device color managed?
5329 case 1030: {
5330 reply->writeBool(useColorManagement);
5331 return NO_ERROR;
5332 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005333 // Override default composition data space
5334 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5335 // && adb shell stop zygote && adb shell start zygote
5336 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5337 // adb shell stop zygote && adb shell start zygote
5338 case 1031: {
5339 Mutex::Autolock _l(mStateLock);
5340 n = data.readInt32();
5341 if (n) {
5342 n = data.readInt32();
5343 if (n) {
5344 Dataspace dataspace = static_cast<Dataspace>(n);
5345 if (!validateCompositionDataspace(dataspace)) {
5346 return BAD_VALUE;
5347 }
5348 mDefaultCompositionDataspace = dataspace;
5349 }
5350 n = data.readInt32();
5351 if (n) {
5352 Dataspace dataspace = static_cast<Dataspace>(n);
5353 if (!validateCompositionDataspace(dataspace)) {
5354 return BAD_VALUE;
5355 }
5356 mWideColorGamutCompositionDataspace = dataspace;
5357 }
5358 } else {
5359 // restore composition data space.
5360 mDefaultCompositionDataspace = defaultCompositionDataspace;
5361 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5362 }
5363 return NO_ERROR;
5364 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005365 }
5366 }
5367 return err;
5368}
5369
Steven Thomas6d8110b2017-08-31 18:24:21 -07005370void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005371 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005372 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005373}
5374
Ana Krulec7d1d6832018-12-27 11:10:09 -08005375void SurfaceFlinger::repaintEverythingForHWC() {
5376 mRepaintEverything = true;
5377 mEventQueue->invalidateForHWC();
5378}
5379
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005380// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5381class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005382public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005383 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5384 ~WindowDisconnector() {
5385 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005386 }
5387
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388private:
5389 ANativeWindow* mWindow;
5390 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005391};
5392
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005393status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005394 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5395 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005396 uint32_t reqWidth, uint32_t reqHeight,
5397 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005398 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005399 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005401 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005402
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005403 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5404
Chia-I Wu20261cb2018-08-23 12:55:44 -07005405 sp<DisplayDevice> display;
5406 {
5407 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005408
Chia-I Wu20261cb2018-08-23 12:55:44 -07005409 display = getDisplayDeviceLocked(displayToken);
5410 if (!display) return BAD_VALUE;
5411
Chia-I Wucb023152018-08-28 12:57:23 -07005412 // set the requested width/height to the logical display viewport size
5413 // by default
5414 if (reqWidth == 0 || reqHeight == 0) {
5415 reqWidth = uint32_t(display->getViewport().width());
5416 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005417 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005418 }
5419
Peiyong Lin0e003c92018-09-17 11:09:51 -07005420 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5421 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005422
5423 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005424 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005425 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5426 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005427}
5428
5429status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005430 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5431 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005432 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005433 ATRACE_CALL();
5434
5435 class LayerRenderArea : public RenderArea {
5436 public:
Robert Carr578038f2018-03-09 12:25:24 -08005437 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005438 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5439 bool childrenOnly)
5440 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005441 mLayer(layer),
5442 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005443 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005444 mFlinger(flinger),
5445 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005446 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005447 Rect getBounds() const override {
5448 const Layer::State& layerState(mLayer->getDrawingState());
5449 return mLayer->getBufferSize(layerState);
5450 }
Marissa Wall61c58622018-07-18 10:12:20 -07005451 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005452 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005453 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005454 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005455 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005456 }
chaviwa76b2712017-09-20 12:02:26 -07005457 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005458 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005459 Rect getSourceCrop() const override {
5460 if (mCrop.isEmpty()) {
5461 return getBounds();
5462 } else {
5463 return mCrop;
5464 }
5465 }
Robert Carr578038f2018-03-09 12:25:24 -08005466 class ReparentForDrawing {
5467 public:
5468 const sp<Layer>& oldParent;
5469 const sp<Layer>& newParent;
5470
5471 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5472 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005473 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005474 }
Robert Carr15eae092018-03-23 13:43:53 -07005475 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005476 };
5477
5478 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005479 const Rect sourceCrop = getSourceCrop();
5480 // no need to check rotation because there is none
5481 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5482 sourceCrop.height() != getReqHeight();
5483
Robert Carr578038f2018-03-09 12:25:24 -08005484 if (!mChildrenOnly) {
5485 mTransform = mLayer->getTransform().inverse();
5486 drawLayers();
5487 } else {
5488 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005489 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005490 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5491 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005492
5493 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5494 drawLayers();
5495 }
5496 }
chaviwa76b2712017-09-20 12:02:26 -07005497
chaviwa76b2712017-09-20 12:02:26 -07005498 private:
chaviw7206d492017-11-10 16:16:12 -08005499 const sp<Layer> mLayer;
5500 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005501
5502 // In the "childrenOnly" case we reparent the children to a screenshot
5503 // layer which has no properties set and which does not draw.
5504 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005505 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005506 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005507
5508 SurfaceFlinger* mFlinger;
5509 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005510 };
5511
5512 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5513 auto parent = layerHandle->owner.promote();
5514
Robert Carr2e102c92018-10-23 12:11:15 -07005515 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005516 ALOGE("captureLayers called with a removed parent");
5517 return NAME_NOT_FOUND;
5518 }
5519
Robert Carr578038f2018-03-09 12:25:24 -08005520 const int uid = IPCThreadState::self()->getCallingUid();
5521 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005522 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005523 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5524 return PERMISSION_DENIED;
5525 }
5526
chaviw7206d492017-11-10 16:16:12 -08005527 Rect crop(sourceCrop);
5528 if (sourceCrop.width() <= 0) {
5529 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005530 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005531 }
5532
5533 if (sourceCrop.height() <= 0) {
5534 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005535 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005536 }
5537
5538 int32_t reqWidth = crop.width() * frameScale;
5539 int32_t reqHeight = crop.height() * frameScale;
5540
Chia-I Wu20261cb2018-08-23 12:55:44 -07005541 // really small crop or frameScale
5542 if (reqWidth <= 0) {
5543 reqWidth = 1;
5544 }
5545 if (reqHeight <= 0) {
5546 reqHeight = 1;
5547 }
5548
Peiyong Lin0e003c92018-09-17 11:09:51 -07005549 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005550
Robert Carr578038f2018-03-09 12:25:24 -08005551 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005552 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5553 if (!layer->isVisible()) {
5554 return;
Robert Carr578038f2018-03-09 12:25:24 -08005555 } else if (childrenOnly && layer == parent.get()) {
5556 return;
chaviwa76b2712017-09-20 12:02:26 -07005557 }
5558 visitor(layer);
5559 });
5560 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005561 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005562}
5563
5564status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5565 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005566 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005567 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005568 bool useIdentityTransform) {
5569 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005570
Peiyong Lin0e003c92018-09-17 11:09:51 -07005571 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005572 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5573 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005574 *outBuffer =
5575 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5576 static_cast<android_pixel_format>(reqPixelFormat), 1,
5577 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005578
5579 // This mutex protects syncFd and captureResult for communication of the return values from the
5580 // main thread back to this Binder thread
5581 std::mutex captureMutex;
5582 std::condition_variable captureCondition;
5583 std::unique_lock<std::mutex> captureLock(captureMutex);
5584 int syncFd = -1;
5585 std::optional<status_t> captureResult;
5586
Robert Carr03480e22018-01-04 16:02:06 -08005587 const int uid = IPCThreadState::self()->getCallingUid();
5588 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5589
Dominik Laskowski8c001672018-05-30 16:52:06 -07005590 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005591 // If there is a refresh pending, bug out early and tell the binder thread to try again
5592 // after the refresh.
5593 if (mRefreshPending) {
5594 ATRACE_NAME("Skipping screenshot for now");
5595 std::unique_lock<std::mutex> captureLock(captureMutex);
5596 captureResult = std::make_optional<status_t>(EAGAIN);
5597 captureCondition.notify_one();
5598 return;
5599 }
5600
5601 status_t result = NO_ERROR;
5602 int fd = -1;
5603 {
5604 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005605 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005606 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5607 useIdentityTransform, forSystem, &fd);
5608 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 }
5610
5611 {
5612 std::unique_lock<std::mutex> captureLock(captureMutex);
5613 syncFd = fd;
5614 captureResult = std::make_optional<status_t>(result);
5615 captureCondition.notify_one();
5616 }
5617 });
5618
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005621 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005622 while (*captureResult == EAGAIN) {
5623 captureResult.reset();
5624 result = postMessageAsync(message);
5625 if (result != NO_ERROR) {
5626 return result;
5627 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005628 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005629 }
5630 result = *captureResult;
5631 }
5632
5633 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005634 sync_wait(syncFd, -1);
5635 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005637
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005639}
5640
chaviwa76b2712017-09-20 12:02:26 -07005641void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005642 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005643 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005644 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005645
Lloyd Pique144e1162017-12-20 16:44:52 -08005646 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005647
chaviwa76b2712017-09-20 12:02:26 -07005648 const auto reqWidth = renderArea.getReqWidth();
5649 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005650 const auto sourceCrop = renderArea.getSourceCrop();
5651 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005652
Peiyong Lin0e003c92018-09-17 11:09:51 -07005653 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005654 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005655
Mathias Agopian180f10d2013-04-10 22:55:41 -07005656 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005657 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005658
5659 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005660 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005661 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005662
chaviw50da5042018-04-09 13:49:37 -07005663 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005664 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005665 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005666
chaviwa76b2712017-09-20 12:02:26 -07005667 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005668 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005669 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005670 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005671 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005672}
5673
chaviwa76b2712017-09-20 12:02:26 -07005674status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5675 TraverseLayersFunction traverseLayers,
5676 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005677 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005678 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005679 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005680 ATRACE_CALL();
5681
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005682 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005683
5684 traverseLayers([&](Layer* layer) {
5685 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5686 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005687
Robert Carr03480e22018-01-04 16:02:06 -08005688 // We allow the system server to take screenshots of secure layers for
5689 // use in situations like the Screen-rotation animation and place
5690 // the impetus on WindowManager to not persist them.
5691 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005692 ALOGW("FB is protected: PERMISSION_DENIED");
5693 return PERMISSION_DENIED;
5694 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005695 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005696
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005697 // this binds the given EGLImage as a framebuffer for the
5698 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005699 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005700 if (bufferBond.getStatus() != NO_ERROR) {
5701 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005702 return INVALID_OPERATION;
5703 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005704
Dan Stozaabcda352017-06-01 14:37:39 -07005705 // this will in fact render into our dequeued buffer
5706 // via an FBO, which means we didn't have to create
5707 // an EGLSurface and therefore we're not
5708 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005709 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005710
Peiyong Linfb530cf2018-12-15 05:07:38 +00005711 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005712 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005713 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005714 }
Alec Mouri492bc572018-09-11 21:40:04 +00005715 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005716
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005717 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005718}
5719
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005720// ---------------------------------------------------------------------------
5721
Dan Stoza412903f2017-04-27 13:42:17 -07005722void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5723 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005724}
5725
Dan Stoza412903f2017-04-27 13:42:17 -07005726void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5727 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005728}
5729
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005730void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005731 const LayerVector::Visitor& visitor) {
5732 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005733 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005734 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005735 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005736 continue;
5737 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005738 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005739 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005740 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005741 return;
5742 }
chaviwa76b2712017-09-20 12:02:26 -07005743 if (!layer->isVisible()) {
5744 return;
5745 }
5746 visitor(layer);
5747 });
5748 }
5749}
5750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005751}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005752
Lloyd Pique074e8122018-07-26 12:57:23 -07005753
Mathias Agopian3f844832013-08-07 21:24:32 -07005754#if defined(__gl_h_)
5755#error "don't include gl/gl.h in this file"
5756#endif
5757
5758#if defined(__gl2_h_)
5759#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005760#endif