blob: ee202a31a4e51b20f39c8cb7484c07689ad12f86 [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
Alec Mouri0f714832018-11-12 15:31:06 -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
Alec Mouri0f714832018-11-12 15:31:06 -08001879 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001880 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001881 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001882 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001883 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884
Alec Mouri0f714832018-11-12 15:31:06 -08001885 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 }
1887 }
1888
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890
1891 if (mDebugRegion > 1) {
1892 usleep(mDebugRegion * 1000);
1893 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001894
Lloyd Pique32cbe282018-10-19 13:09:22 -07001895 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896}
1897
Adrian Roos1e1a1282017-11-01 19:05:31 +01001898void SurfaceFlinger::doTracing(const char* where) {
1899 ATRACE_CALL();
1900 ATRACE_NAME(where);
1901 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001902 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001903 }
1904}
1905
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001906void SurfaceFlinger::logLayerStats() {
1907 ATRACE_CALL();
1908 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001909 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001910 if (display->isPrimary()) {
1911 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001912 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001913 }
1914 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915
1916 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001917 }
1918}
1919
David Sodman2b406362017-12-15 13:33:47 -08001920void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 ATRACE_CALL();
1923 ALOGV("preComposition");
1924
David Sodman2b406362017-12-15 13:33:47 -08001925 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1926
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001928 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001929 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 needExtraInvalidate = true;
1931 }
Robert Carr2047fae2016-11-28 14:09:09 -08001932 });
1933
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 if (needExtraInvalidate) {
1935 signalLayerUpdate();
1936 }
1937}
1938
Ana Krulece588e312018-09-18 12:32:24 -07001939void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1940 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // Update queue of past composite+present times and determine the
1942 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001943 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001945 while (!getBE().mCompositePresentTimes.empty()) {
1946 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Cached values should have been updated before calling this method,
1948 // which helps avoid duplicate syscalls.
1949 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1950 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1951 break;
1952 }
1953 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 }
1956
1957 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001958 while (getBE().mCompositePresentTimes.size() > 16) {
1959 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 }
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001963}
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1966 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 // Integer division and modulo round toward 0 not -inf, so we need to
1968 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001969 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1970 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1971 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972
Brian Andersond0010582017-03-07 13:20:31 -08001973 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1974 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001975 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001976 }
1977
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Snap the latency to a value that removes scheduling jitter from the
1979 // composition and present times, which often have >1ms of jitter.
1980 // Reducing jitter is important if an app attempts to extrapolate
1981 // something (such as user input) to an accurate diasplay time.
1982 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1983 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001984 nsecs_t bias = stats.vsyncPeriod / 2;
1985 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1986 nsecs_t snappedCompositeToPresentLatency =
1987 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988
David Sodman99974d22017-11-28 12:04:33 -08001989 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001990 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1991 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001992 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001993}
1994
Ady Abraham8164d482019-01-11 14:47:59 -08001995// debug patch for b/119477596 - add stack guards to catch stack
1996// corruptions and disable clang optimizations.
1997// The code below is temporary and planned to be removed once stack
1998// corruptions are found.
1999#pragma clang optimize off
2000class StackGuard {
2001public:
2002 StackGuard(const char* name, const char* func, int line) {
2003 guarders.reserve(MIN_CAPACITY);
2004 guarders.push_back({this, name, func, line});
2005 validate();
2006 }
2007 ~StackGuard() {
2008 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2009 if (i->guard == this) {
2010 guarders.erase(i);
2011 break;
2012 }
2013 }
2014 }
2015
2016 static void validate() {
2017 for (const auto& guard : guarders) {
2018 if (guard.guard->cookie != COOKIE_VALUE) {
2019 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2020 CallStack stack(LOG_TAG);
2021 abort();
2022 }
2023 }
2024 }
2025
2026private:
2027 uint64_t cookie = COOKIE_VALUE;
2028 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2029 static constexpr size_t MIN_CAPACITY = 16;
2030
2031 struct GuarderElement {
2032 StackGuard* guard;
2033 const char* name;
2034 const char* func;
2035 int line;
2036 };
2037
2038 static std::vector<GuarderElement> guarders;
2039};
2040std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2041
2042#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2043
2044#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002045void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002046{
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 ATRACE_CALL();
2049 ALOGV("postComposition");
2050
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002052 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002054 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002055 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002056 }
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002059 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002060 const auto displayDevice = getDefaultDisplayDeviceLocked();
2061 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062
David Sodman73beded2017-11-15 11:56:06 -08002063 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2066
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002069 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2070 ->getRenderSurface()
2071 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002072 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002073 } else {
2074 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2075 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002076
Ady Abraham8164d482019-01-11 14:47:59 -08002077 ASSERT_ON_STACK_GUARD();
2078
David Sodman73beded2017-11-15 11:56:06 -08002079 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2081 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002082 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002083 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002084 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085
Ana Krulece588e312018-09-18 12:32:24 -07002086 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002087 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002088 if (mUseScheduler) {
2089 mScheduler->getDisplayStatInfo(&stats);
2090 } else {
2091 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2092 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2093 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002094
Ady Abraham8164d482019-01-11 14:47:59 -08002095 ASSERT_ON_STACK_GUARD();
2096
David Sodman2b406362017-12-15 13:33:47 -08002097 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098 // when we started doing work for this frame, but that should be okay
2099 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002100 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002101 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002102 DEFINE_STACK_GUARD(compositorTiming);
2103
Brian Andersond0010582017-03-07 13:20:31 -08002104 {
David Sodman99974d22017-11-28 12:04:33 -08002105 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002106 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002107 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002108
2109 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002110 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111
Robert Carr2047fae2016-11-28 14:09:09 -08002112 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002113 bool frameLatched =
2114 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2115 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002116 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002117 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002118 recordBufferingStats(layer->getName().string(),
2119 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002120 }
Ady Abraham8164d482019-01-11 14:47:59 -08002121 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002122 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002123
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002124 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002126 if (mUseScheduler) {
2127 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002130 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2131 enableHardwareVsync();
2132 } else {
2133 disableHardwareVsync(false);
2134 }
Ady Abraham8164d482019-01-11 14:47:59 -08002135 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002136 }
2137 }
2138
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002139 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2141 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002142 if (mUseScheduler) {
2143 mScheduler->enableHardwareVsync();
2144 } else {
2145 enableHardwareVsync();
2146 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002147 }
2148 }
2149
Ady Abraham8164d482019-01-11 14:47:59 -08002150 ASSERT_ON_STACK_GUARD();
2151
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002152 if (mAnimCompositionPending) {
2153 mAnimCompositionPending = false;
2154
Brian Anderson4e606e32017-03-16 15:34:57 -07002155 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002157 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002158
2159 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002160 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161 // The HWC doesn't support present fences, so use the refresh
2162 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 const nsecs_t presentTime =
2164 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002165 DEFINE_STACK_GUARD(presentTime);
2166
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002167 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002168 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002169 }
2170 mAnimFrameTracker.advanceFrame();
2171 }
Dan Stozab90cf072015-03-05 11:05:59 -08002172
Ady Abraham8164d482019-01-11 14:47:59 -08002173 ASSERT_ON_STACK_GUARD();
2174
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002176 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002177 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002178 }
2179
Ady Abraham8164d482019-01-11 14:47:59 -08002180 ASSERT_ON_STACK_GUARD();
2181
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002183
Ady Abraham8164d482019-01-11 14:47:59 -08002184 ASSERT_ON_STACK_GUARD();
2185
Lloyd Pique32cbe282018-10-19 13:09:22 -07002186 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2187 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002188 return;
2189 }
2190
2191 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002192 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002193 if (mHasPoweredOff) {
2194 mHasPoweredOff = false;
2195 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002196 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002197 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002198 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002199 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002200 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2201 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002202 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002203 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002204 }
David Sodman4a36e932017-11-07 14:29:47 -08002205 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002206
2207 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002208 }
David Sodman4a36e932017-11-07 14:29:47 -08002209 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002210 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002211
2212 {
2213 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002214 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002215 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002216 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002217 if (refillCount > 0) {
2218 const size_t offset = mTexturePool.size();
2219 mTexturePool.resize(mTexturePoolSize);
2220 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2221 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2222 }
Ady Abraham8164d482019-01-11 14:47:59 -08002223 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002224 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002225
Marissa Wallfda30bb2018-10-12 11:34:28 -07002226 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002227 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002228
2229 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002230}
Ady Abraham8164d482019-01-11 14:47:59 -08002231#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002232
2233void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 ATRACE_CALL();
2235 ALOGV("rebuildLayerStacks");
2236
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002237 // We need to clear these out now as these may be holding on to a
2238 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2239 // also holds a reference. When the set of visible layers is recomputed,
2240 // some layers may be destroyed if the only thing keeping them alive was
2241 // that list of visible layers associated with each display. The layer
2242 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2243 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2244 for (const auto& [token, display] : mDisplays) {
2245 getBE().mCompositionInfo[token].clear();
2246 }
2247
Mathias Agopiancd60f992012-08-16 16:28:27 -07002248 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002249 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002250 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 mVisibleRegionsDirty = false;
2252 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002254 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const auto& displayDevice = pair.second;
2256 auto display = displayDevice->getCompositionDisplay();
2257 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 Region opaqueRegion;
2259 Region dirtyRegion;
2260 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002261 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002262 const ui::Transform& tr = displayState.transform;
2263 const Rect bounds = displayState.bounds;
2264 if (displayState.isEnabled) {
2265 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002266
Jeff Sharkey76488112017-02-27 14:15:18 -07002267 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002268 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002269 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002270 if (display->belongsInOutput(layer->getLayerStack(),
2271 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002272 Region drawRegion(tr.transform(
2273 layer->visibleNonTransparentRegion));
2274 drawRegion.andSelf(bounds);
2275 if (!drawRegion.isEmpty()) {
2276 layersSortedByZ.add(layer);
2277 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002278 // Clear out the HWC layer if this layer was
2279 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002281 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002282 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002283 // WM changes display->layerStack upon sleep/awake.
2284 // Here we make sure we delete the HWC layers even if
2285 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002286 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002287 }
2288
2289 // If a layer is not going to get a release fence because
2290 // it is invisible, but it is also going to release its
2291 // old buffer, add it to the list of layers needing
2292 // fences.
2293 if (hwcLayerDestroyed) {
2294 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2295 mLayersWithQueuedFrames.cend(), layer);
2296 if (found != mLayersWithQueuedFrames.cend()) {
2297 layersNeedingFences.add(layer);
2298 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002299 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002300 });
2301 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002302 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2303 displayDevice->setLayersNeedingFences(layersNeedingFences);
2304
2305 Region undefinedRegion{bounds};
2306 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2307
2308 display->editState().undefinedRegion = undefinedRegion;
2309 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002310 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002311 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002312}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002313
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002316// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002318// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319// The returned HDR data space is one of
2320// - Dataspace::UNKNOWN
2321// - Dataspace::BT2020_HLG
2322// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2324 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002325 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326 *outHdrDataSpace = Dataspace::UNKNOWN;
2327
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002328 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002329 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330 case Dataspace::V0_SCRGB:
2331 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002332 case Dataspace::BT2020:
2333 case Dataspace::BT2020_ITU:
2334 case Dataspace::BT2020_LINEAR:
2335 case Dataspace::DISPLAY_BT2020:
2336 bestDataSpace = Dataspace::DISPLAY_BT2020;
2337 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002339 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002340 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 case Dataspace::BT2020_PQ:
2342 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002345 case Dataspace::BT2020_HLG:
2346 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002347 // When there's mixed PQ content and HLG content, we set the HDR
2348 // data space to be BT2020_PQ and convert HLG to PQ.
2349 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2350 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002351 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002352 break;
2353 default:
2354 break;
2355 }
Romain Guy54f154a2017-10-24 21:40:32 +01002356 }
2357
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002358 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002359}
2360
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2363 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002364 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2365 *outMode = ColorMode::NATIVE;
2366 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002367 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002368 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002369 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002370
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002371 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002373
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002374 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2375
Peiyong Lindfde5112018-06-05 10:58:41 -07002376 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002377 const bool isHdr =
2378 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002379 if (isHdr) {
2380 bestDataSpace = hdrDataSpace;
2381 }
2382
Chia-I Wu0d711262018-05-21 15:19:35 -07002383 RenderIntent intent;
2384 switch (mDisplayColorSetting) {
2385 case DisplayColorSetting::MANAGED:
2386 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002387 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002388 break;
2389 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002390 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002391 break;
2392 default: // vendor display color setting
2393 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2394 break;
2395 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002396
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002397 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002398}
2399
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2401 auto display = displayDevice->getCompositionDisplay();
2402 const auto& displayState = display->getState();
2403
Alec Mouri0f714832018-11-12 15:31:06 -08002404 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002405 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2406 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002407
David Sodmanfa9b2af2017-12-24 13:28:59 -08002408 // If nothing has changed (!dirty), don't recompose.
2409 // If something changed, but we don't currently have any visible layers,
2410 // and didn't when we last did a composition, then skip it this time.
2411 // The second rule does two things:
2412 // - When all layers are removed from a display, we'll emit one black
2413 // frame, then nothing more until we get new layers.
2414 // - When a display is created with a private layer stack, we won't
2415 // emit any black frames until a layer is added to the layer stack.
2416 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002417
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 const char flagPrefix[] = {'-', '+'};
2419 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2421 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2422 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2423 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002424
Lloyd Pique31cb2942018-10-19 17:23:03 -07002425 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002426
David Sodmanfa9b2af2017-12-24 13:28:59 -08002427 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002428 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002429 }
2430}
2431
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2433 auto display = displayDevice->getCompositionDisplay();
2434 const auto& displayState = display->getState();
2435
2436 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 return;
David Sodman2b406362017-12-15 13:33:47 -08002438 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002439
Lloyd Pique31cb2942018-10-19 17:23:03 -07002440 status_t result = display->getRenderSurface()->prepareFrame(
2441 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002444}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002447 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 ALOGV("doComposition");
2449
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 auto display = displayDevice->getCompositionDisplay();
2451 const auto& displayState = display->getState();
2452
2453 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002454 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002455 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002456
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002459
Lloyd Pique32cbe282018-10-19 13:09:22 -07002460 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002461 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002464}
2465
David Sodmanfa9b2af2017-12-24 13:28:59 -08002466void SurfaceFlinger::postFrame()
2467{
2468 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 const auto display = getDefaultDisplayDeviceLocked();
2470 if (display && getHwComposer().isConnected(*display->getId())) {
2471 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002472 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2473 logFrameStats();
2474 }
2475 }
2476}
2477
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002479 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002481
Lloyd Pique32cbe282018-10-19 13:09:22 -07002482 auto display = displayDevice->getCompositionDisplay();
2483 const auto& displayState = display->getState();
2484 const auto displayId = display->getId();
2485
David Sodmanfa9b2af2017-12-24 13:28:59 -08002486 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002487
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (displayId) {
2490 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002491 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002492 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002493 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002494 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002495
Chia-I Wu7b549592017-11-15 09:14:57 -08002496 // The layer buffer from the previous frame (if any) is released
2497 // by HWC only when the release fence from this frame (if any) is
2498 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (displayId && layer->hasHwcLayer(*displayId)) {
2500 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2501 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002502 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002503
2504 // If the layer was client composited in the previous frame, we
2505 // need to merge with the previous client target acquire fence.
2506 // Since we do not track that, always merge with the current
2507 // client target acquire fence when it is available, even though
2508 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002509 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002510 releaseFence =
2511 Fence::merge("LayerRelease", releaseFence,
2512 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002513 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002514
David Sodman15094112018-10-11 09:39:37 -07002515 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002516 }
Chia-I Wu83806892017-11-16 10:50:20 -08002517
2518 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002519 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002520 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002521 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002523 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002524 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002525 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002526 }
2527 }
2528
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 if (displayId) {
2530 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002531 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002532 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533}
2534
Mathias Agopian87baae12012-07-31 12:38:26 -07002535void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536{
Mathias Agopian841cde52012-03-01 15:44:37 -08002537 ATRACE_CALL();
2538
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002539 // here we keep a copy of the drawing state (that is the state that's
2540 // going to be overwritten by handleTransactionLocked()) outside of
2541 // mStateLock so that the side-effects of the State assignment
2542 // don't happen with mStateLock held (which can cause deadlocks).
2543 State drawingState(mDrawingState);
2544
Mathias Agopianca4d3602011-05-19 15:38:14 -07002545 Mutex::Autolock _l(mStateLock);
2546 const nsecs_t now = systemTime();
2547 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548
Mathias Agopianca4d3602011-05-19 15:38:14 -07002549 // Here we're guaranteed that some transaction flags are set
2550 // so we can call handleTransactionLocked() unconditionally.
2551 // We call getTransactionFlags(), which will also clear the flags,
2552 // with mStateLock held to guarantee that mCurrentState won't change
2553 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002554
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002555 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002556 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002557 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002558
Mathias Agopianca4d3602011-05-19 15:38:14 -07002559 mLastTransactionTime = systemTime() - now;
2560 mDebugInTransaction = 0;
2561 invalidateHwcGeometry();
2562 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002563}
2564
Lloyd Piqueba04e622017-12-14 17:11:26 -08002565void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2566 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 const std::optional<DisplayIdentificationInfo> info =
2568 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002569
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002571 continue;
2572 }
2573
Lloyd Piqueba04e622017-12-14 17:11:26 -08002574 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002576 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 mPhysicalDisplayTokens[info->id] = new BBinder();
2578 DisplayDeviceState state;
2579 state.displayId = info->id;
2580 state.isSecure = true; // All physical displays are currently considered secure.
2581 state.displayName = info->name;
2582 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2583 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002584 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002586 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2589 if (index >= 0) {
2590 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2591 mInterceptor->saveDisplayDeletion(state.sequenceId);
2592 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002593 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595 }
2596
2597 processDisplayChangesLocked();
2598 }
2599
2600 mPendingHotplugEvents.clear();
2601}
2602
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002603void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2604 bool connected) {
2605 if (mUseScheduler) {
2606 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2607 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2608 } else {
2609 mEventThread->onHotplugReceived(displayType, connected);
2610 mSFEventThread->onHotplugReceived(displayType, connected);
2611 }
2612}
2613
Lloyd Pique99d3da52018-01-22 17:48:03 -08002614sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002616 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002617 const sp<IGraphicBufferProducer>& producer) {
2618 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002619 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002621 creationArgs.isSecure = state.isSecure;
2622 creationArgs.displaySurface = dispSurface;
2623 creationArgs.hasWideColorGamut = false;
2624 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002625
Dominik Laskowski075d3172018-05-24 15:50:06 -07002626 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2627 creationArgs.isPrimary = isInternalDisplay;
2628
2629 if (useColorManagement && displayId) {
2630 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002631 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002632 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002633 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002635
Dominik Laskowski7e045462018-05-30 13:02:02 -07002636 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002637 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002638 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639 }
tangrobin6753a022018-08-10 10:58:54 +08002640 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 if (displayId) {
2643 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002644 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002646 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647
Lloyd Pique90c115d2018-09-18 21:39:42 -07002648 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002650 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 // Make sure that composition can never be stalled by a virtual display
2653 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002654 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002655 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2657 }
2658
Dominik Laskowski075d3172018-05-24 15:50:06 -07002659 creationArgs.displayInstallOrientation =
2660 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002661
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002663 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664
Lloyd Pique90c115d2018-09-18 21:39:42 -07002665 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
2667 if (maxFrameBufferAcquiredBuffers >= 3) {
2668 nativeWindowSurface->preallocateBuffers();
2669 }
2670
2671 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002672 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002673 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002675 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002677 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2678 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002679 if (!state.isVirtual()) {
2680 LOG_ALWAYS_FATAL_IF(!displayId);
2681 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002682 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 display->setLayerStack(state.layerStack);
2685 display->setProjection(state.orientation, state.viewport, state.frame);
2686 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002687
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002688 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689}
2690
Lloyd Pique347200f2017-12-14 17:00:15 -08002691void SurfaceFlinger::processDisplayChangesLocked() {
2692 // here we take advantage of Vector's copy-on-write semantics to
2693 // improve performance by skipping the transaction entirely when
2694 // know that the lists are identical
2695 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2696 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2697 if (!curr.isIdenticalTo(draw)) {
2698 mVisibleRegionsDirty = true;
2699 const size_t cc = curr.size();
2700 size_t dc = draw.size();
2701
2702 // find the displays that were removed
2703 // (ie: in drawing state but not in current state)
2704 // also handle displays that changed
2705 // (ie: displays that are in both lists)
2706 for (size_t i = 0; i < dc;) {
2707 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2708 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 // Save display IDs before disconnecting.
2710 const auto internalDisplayId = getInternalDisplayId();
2711 const auto externalDisplayId = getExternalDisplayId();
2712
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002715 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002716 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002718 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002719 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002720 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002721 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002722 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 } else {
2724 // this display is in both lists. see if something changed.
2725 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002726 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2728 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2729 if (state_binder != draw_binder) {
2730 // changing the surface is like destroying and
2731 // recreating the DisplayDevice, so we just remove it
2732 // from the drawing state, so that it get re-added
2733 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002735 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002736 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002737 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 mDrawingState.displays.removeItemsAt(i);
2739 dc--;
2740 // at this point we must loop to the next item
2741 continue;
2742 }
2743
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002746 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002747 }
2748 if ((state.orientation != draw[i].orientation) ||
2749 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 }
2752 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002753 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 }
2755 }
2756 }
2757 ++i;
2758 }
2759
2760 // find displays that were added
2761 // (ie: in current state but not in drawing state)
2762 for (size_t i = 0; i < cc; i++) {
2763 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2764 const DisplayDeviceState& state(curr[i]);
2765
Lloyd Pique542307f2018-10-19 13:24:08 -07002766 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 sp<IGraphicBufferProducer> producer;
2768 sp<IGraphicBufferProducer> bqProducer;
2769 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002770 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771
Dominik Laskowski075d3172018-05-24 15:50:06 -07002772 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002773 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 // Virtual displays without a surface are dormant:
2775 // they have external state (layer stack, projection,
2776 // etc.) but no internal state (i.e. a DisplayDevice).
2777 if (state.surface != nullptr) {
2778 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002779 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 int width = 0;
2781 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2782 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2783 int height = 0;
2784 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2785 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2786 int intFormat = 0;
2787 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2788 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002789 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002790
Dominik Laskowski075d3172018-05-24 15:50:06 -07002791 displayId =
2792 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 }
2794
2795 // TODO: Plumb requested format back up to consumer
2796
2797 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002798 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002799 bqProducer, bqConsumer,
2800 state.displayName);
2801
2802 dispSurface = vds;
2803 producer = vds;
2804 }
2805 } else {
2806 ALOGE_IF(state.surface != nullptr,
2807 "adding a supported display, but rendering "
2808 "surface is provided (%p), ignoring it",
2809 state.surface.get());
2810
Dominik Laskowski075d3172018-05-24 15:50:06 -07002811 displayId = state.displayId;
2812 LOG_ALWAYS_FATAL_IF(!displayId);
2813 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002814 producer = bqProducer;
2815 }
2816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002817 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002818 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002820 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002822 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002823 LOG_ALWAYS_FATAL_IF(!displayId);
2824
2825 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002826 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002827 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002828 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002829 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002830 }
2831 }
2832 }
2833 }
2834 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002835
2836 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002837}
2838
Mathias Agopian87baae12012-07-31 12:38:26 -07002839void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002840{
Dan Stoza7dde5992015-05-22 09:51:44 -07002841 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002842 mCurrentState.traverseInZOrder([](Layer* layer) {
2843 layer->notifyAvailableFrames();
2844 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002845
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846 /*
2847 * Traversal of the children
2848 * (perform the transaction for each of them if needed)
2849 */
2850
Robert Carr720e5062018-07-30 17:45:14 -07002851 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002852 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002853 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002855 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856
2857 const uint32_t flags = layer->doTransaction(0);
2858 if (flags & Layer::eVisibleRegion)
2859 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002860
2861 if (flags & Layer::eInputInfoChanged) {
2862 inputChanged = true;
2863 }
Robert Carr2047fae2016-11-28 14:09:09 -08002864 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 }
2866
2867 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002868 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 */
2870
Mathias Agopiane57f2922012-08-09 16:29:12 -07002871 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002872 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002873 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002874 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002876 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002877 // The transform hint might have changed for some layers
2878 // (either because a display has changed, or because a layer
2879 // as changed).
2880 //
2881 // Walk through all the layers in currentLayers,
2882 // and update their transform hint.
2883 //
2884 // If a layer is visible only on a single display, then that
2885 // display is used to calculate the hint, otherwise we use the
2886 // default display.
2887 //
2888 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2889 // the hint is set before we acquire a buffer from the surface texture.
2890 //
2891 // NOTE: layer transactions have taken place already, so we use their
2892 // drawing state. However, SurfaceFlinger's own transaction has not
2893 // happened yet, so we must use the current state layer list
2894 // (soon to become the drawing state list).
2895 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002897 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002898 bool first = true;
2899 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002900 // NOTE: we rely on the fact that layers are sorted by
2901 // layerStack first (so we don't have to traverse the list
2902 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002904 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002905 currentlayerStack = layerStack;
2906 // figure out if this layerstack is mirrored
2907 // (more than one display) if so, pick the default display,
2908 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002909 hintDisplay = nullptr;
2910 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002911 if (display->getCompositionDisplay()
2912 ->belongsInOutput(layer->getLayerStack(),
2913 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 if (hintDisplay) {
2915 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002916 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002918 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002919 }
2920 }
2921 }
2922 }
Chet Haase91d25932013-04-11 15:24:55 -07002923
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002924 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002925 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2926 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002927
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002928 // could be null when this layer is using a layerStack
2929 // that is not visible on any display. Also can occur at
2930 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002931 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002932 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002933
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002935 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 if (hintDisplay) {
2937 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002938 }
Robert Carr2047fae2016-11-28 14:09:09 -08002939
2940 first = false;
2941 });
Mathias Agopian84300952012-11-21 16:02:13 -08002942 }
2943
2944
Mathias Agopian3559b072012-08-15 13:46:03 -07002945 /*
2946 * Perform our own transaction if needed
2947 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002948
2949 if (mLayersAdded) {
2950 mLayersAdded = false;
2951 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002952 mVisibleRegionsDirty = true;
2953 }
2954
2955 // some layers might have been removed, so
2956 // we need to update the regions they're exposing.
2957 if (mLayersRemoved) {
2958 mLayersRemoved = false;
2959 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002960 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002961 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002962 // this layer is not visible anymore
2963 // TODO: we could traverse the tree from front to back and
2964 // compute the actual visible region
2965 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002966 Region visibleReg;
2967 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002968 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002969 }
Robert Carr2047fae2016-11-28 14:09:09 -08002970 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971 }
2972
2973 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002974
Vishnu Nairde19f852018-12-18 16:11:53 -08002975 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002976 updateInputWindows();
2977 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002978 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002979
Riley Andrews03414a12014-07-01 14:22:59 -07002980 updateCursorAsync();
2981}
2982
Robert Carr720e5062018-07-30 17:45:14 -07002983void SurfaceFlinger::updateInputWindows() {
2984 ATRACE_CALL();
2985
Vishnu Nairde19f852018-12-18 16:11:53 -08002986 if (mInputFlinger == nullptr) {
2987 return;
2988 }
2989
Robert Carr720e5062018-07-30 17:45:14 -07002990 Vector<InputWindowInfo> inputHandles;
2991
2992 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2993 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002994 // When calculating the screen bounds we ignore the transparent region since it may
2995 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002996 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002997 }
2998 });
2999 mInputFlinger->setInputWindows(inputHandles);
3000}
3001
chaviwfbe5d9c2018-12-26 12:23:37 -08003002void SurfaceFlinger::executeInputWindowCommands() {
3003 if (!mInputFlinger) {
3004 return;
3005 }
3006
3007 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3008 if (transferTouchFocusCommand.fromToken != nullptr &&
3009 transferTouchFocusCommand.toToken != nullptr &&
3010 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3011 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3012 transferTouchFocusCommand.toToken);
3013 }
3014 }
3015
3016 mInputWindowCommands.clear();
3017}
3018
Riley Andrews03414a12014-07-01 14:22:59 -07003019void SurfaceFlinger::updateCursorAsync()
3020{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003021 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003022 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003023 continue;
3024 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3027 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003028 }
3029 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003030}
3031
chaviw61626f22018-11-15 16:26:27 -08003032void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3033 if (layer->hasReadyFrame()) {
3034 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3035 if (layer->shouldPresentNow(expectedPresentTime)) {
3036 bool ignored = false;
3037 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3038 }
3039 }
3040 layer->releasePendingBuffer(systemTime());
3041}
3042
Mathias Agopian4fec8732012-06-29 14:12:52 -07003043void SurfaceFlinger::commitTransaction()
3044{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003045 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003047 for (const auto& l : mLayersPendingRemoval) {
3048 recordBufferingStats(l->getName().string(),
3049 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003050
3051 // We need to release the HWC layers when the Layer is removed
3052 // from the current state otherwise the HWC layer just continues
3053 // showing at its last configured state until we eventually
3054 // abandon the buffer queue.
3055 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003056 l->destroyHwcLayersForAllDisplays();
3057 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003058 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059 }
3060 mLayersPendingRemoval.clear();
3061 }
3062
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003063 // If this transaction is part of a window animation then the next frame
3064 // we composite should be considered an animation as well.
3065 mAnimCompositionPending = mAnimTransactionPending;
3066
Mathias Agopian4fec8732012-06-29 14:12:52 -07003067 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003068 // clear the "changed" flags in current state
3069 mCurrentState.colorMatrixChanged = false;
3070
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 mDrawingState.traverseInZOrder([](Layer* layer) {
3072 layer->commitChildList();
3073 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003074 mTransactionPending = false;
3075 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003076 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077}
3078
Lloyd Pique32cbe282018-10-19 13:09:22 -07003079void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003080 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003081 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003082 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003083
Lloyd Pique32cbe282018-10-19 13:09:22 -07003084 auto display = displayDevice->getCompositionDisplay();
3085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 Region aboveOpaqueLayers;
3087 Region aboveCoveredLayers;
3088 Region dirty;
3089
Mathias Agopian87baae12012-07-31 12:38:26 -07003090 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091
Robert Carr2047fae2016-11-28 14:09:09 -08003092 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003093 // start with the whole surface at its current location
3094 const Layer::State& s(layer->getDrawingState());
3095
Jesse Hall01e29052013-02-19 16:13:35 -08003096 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003097 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003098 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003099 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003100
Mathias Agopianab028732010-03-16 16:41:46 -07003101 /*
3102 * opaqueRegion: area of a surface that is fully opaque.
3103 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003105
3106 /*
3107 * visibleRegion: area of a surface that is visible on screen
3108 * and not fully transparent. This is essentially the layer's
3109 * footprint minus the opaque regions above it.
3110 * Areas covered by a translucent surface are considered visible.
3111 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003113
3114 /*
3115 * coveredRegion: area of a surface that is covered by all
3116 * visible regions above it (which includes the translucent areas).
3117 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003118 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003119
Jesse Halla8026d22012-09-25 13:25:04 -07003120 /*
3121 * transparentRegion: area of a surface that is hinted to be completely
3122 * transparent. This is only used to tell when the layer has no visible
3123 * non-transparent regions and can be removed from the layer list. It
3124 * does not affect the visibleRegion of this layer or any layers
3125 * beneath it. The hint may not be correct if apps don't respect the
3126 * SurfaceView restrictions (which, sadly, some don't).
3127 */
3128 Region transparentRegion;
3129
Mathias Agopianab028732010-03-16 16:41:46 -07003130
3131 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003132 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003133 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003137 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003138 if (!visibleRegion.isEmpty()) {
3139 // Remove the transparent area from the visible region
3140 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003141 if (tr.preserveRects()) {
3142 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003143 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003145 // transformation too complex, can't do the
3146 // transparent region optimization.
3147 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003148 }
Mathias Agopianab028732010-03-16 16:41:46 -07003149 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150
Mathias Agopianab028732010-03-16 16:41:46 -07003151 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003152 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003153 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003154 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003155 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003156 // the opaque region is the layer's footprint
3157 opaqueRegion = visibleRegion;
3158 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159 }
3160 }
3161
Robert Carre5f4f692018-01-12 13:12:28 -08003162 if (visibleRegion.isEmpty()) {
3163 layer->clearVisibilityRegions();
3164 return;
3165 }
3166
Mathias Agopianab028732010-03-16 16:41:46 -07003167 // Clip the covered region to the visible region
3168 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3169
3170 // Update aboveCoveredLayers for next (lower) layer
3171 aboveCoveredLayers.orSelf(visibleRegion);
3172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173 // subtract the opaque region covered by the layers above us
3174 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175
3176 // compute this layer's dirty region
3177 if (layer->contentDirty) {
3178 // we need to invalidate the whole region
3179 dirty = visibleRegion;
3180 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003181 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182 layer->contentDirty = false;
3183 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003184 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003185 * the exposed region consists of two components:
3186 * 1) what's VISIBLE now and was COVERED before
3187 * 2) what's EXPOSED now less what was EXPOSED before
3188 *
3189 * note that (1) is conservative, we start with the whole
3190 * visible region but only keep what used to be covered by
3191 * something -- which mean it may have been exposed.
3192 *
3193 * (2) handles areas that were not covered by anything but got
3194 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003195 */
Mathias Agopianab028732010-03-16 16:41:46 -07003196 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003197 const Region oldVisibleRegion = layer->visibleRegion;
3198 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003199 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3200 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 }
3202 dirty.subtractSelf(aboveOpaqueLayers);
3203
3204 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003205 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206
Mathias Agopianab028732010-03-16 16:41:46 -07003207 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003209
Jesse Halla8026d22012-09-25 13:25:04 -07003210 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 layer->setVisibleRegion(visibleRegion);
3212 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003213 layer->setVisibleNonTransparentRegion(
3214 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003215 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216
Mathias Agopian87baae12012-07-31 12:38:26 -07003217 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218}
3219
Chia-I Wuab0c3192017-08-01 11:29:00 -07003220void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003221 for (const auto& [token, displayDevice] : mDisplays) {
3222 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003223 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003224 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003225 }
3226 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003227}
3228
Daniel Solomon42d04562019-01-20 21:03:19 -08003229void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3230 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3231 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3232 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3233 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3234 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3235 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3236 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3237 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3238 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3239 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3240 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3241 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3242}
3243
Dan Stoza6b9454d2014-11-07 16:00:59 -08003244bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003246 ALOGV("handlePageFlip");
3247
Brian Andersond6927fb2016-07-23 23:37:30 -07003248 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249
Mathias Agopian4fec8732012-06-29 14:12:52 -07003250 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003251 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003252 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003253
3254 // Store the set of layers that need updates. This set must not change as
3255 // buffers are being latched, as this could result in a deadlock.
3256 // Example: Two producers share the same command stream and:
3257 // 1.) Layer 0 is latched
3258 // 2.) Layer 0 gets a new frame
3259 // 2.) Layer 1 gets a new frame
3260 // 3.) Layer 1 is latched.
3261 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3262 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003263 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003264 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003265 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003266 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3267 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003268 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003269 } else {
3270 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003271 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003272 } else {
3273 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003274 }
Robert Carr2047fae2016-11-28 14:09:09 -08003275 });
3276
Lloyd Piquef2c79392018-12-20 16:23:33 -08003277 if (!mLayersWithQueuedFrames.empty()) {
3278 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3279 // writes to Layer current state. See also b/119481871
3280 Mutex::Autolock lock(mStateLock);
3281
3282 for (auto& layer : mLayersWithQueuedFrames) {
3283 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3284 layer->useSurfaceDamage();
3285 invalidateLayerStack(layer, dirty);
3286 if (layer->isBufferLatched()) {
3287 newDataLatched = true;
3288 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003289 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003290 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003291
Alec Mouri86770e52018-09-24 22:40:58 +00003292 // Clear the renderengine fence here...
3293 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3294 // clear instead of sp::clear.
3295 getBE().flushFence = Fence::NO_FENCE;
3296
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003297 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003298
Vishnu Nairde19f852018-12-18 16:11:53 -08003299 if (visibleRegions) {
3300 // Update input window info if the layer receives its first buffer.
3301 updateInputWindows();
3302 }
3303
Dan Stoza6b9454d2014-11-07 16:00:59 -08003304 // If we will need to wake up at some time in the future to deal with a
3305 // queued frame that shouldn't be displayed during this vsync period, wake
3306 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003307 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003308 signalLayerUpdate();
3309 }
3310
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003311 // enter boot animation on first buffer latch
3312 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3313 ALOGI("Enter boot animation");
3314 mBootStage = BootStage::BOOTANIMATION;
3315 }
3316
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003318 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319}
3320
Mathias Agopianad456f92011-01-13 17:53:01 -08003321void SurfaceFlinger::invalidateHwcGeometry()
3322{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003323 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003324}
3325
Lloyd Pique32cbe282018-10-19 13:09:22 -07003326void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003327 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003328 auto display = displayDevice->getCompositionDisplay();
3329
Dan Stoza71433162014-02-04 16:22:36 -08003330 // We only need to actually compose the display if:
3331 // 1) It is being handled by hardware composer, which may need this to
3332 // keep its virtual display state machine in sync, or
3333 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003334 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003335 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003336 return;
3337 }
3338
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003340 base::unique_fd readyFence;
3341 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003342
3343 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003344 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003345}
3346
Alec Mouri0f714832018-11-12 15:31:06 -08003347bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3348 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003349 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003350
Lloyd Pique32cbe282018-10-19 13:09:22 -07003351 auto display = displayDevice->getCompositionDisplay();
3352 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003353 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003354
3355 const Region bounds(displayState.bounds);
3356 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003357 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003358 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003359
Peiyong Lind3788632018-09-18 16:01:31 -07003360 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003361 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003362
Alec Mouri0f714832018-11-12 15:31:06 -08003363 renderengine::DisplaySettings clientCompositionDisplay;
3364 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3365 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003366
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 if (hasClientComposition) {
3368 ALOGV("hasClientComposition");
3369
Alec Mouri0f714832018-11-12 15:31:06 -08003370 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
Alec Mouri0f714832018-11-12 15:31:06 -08003379 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3380 clientCompositionDisplay.clip = displayState.scissor;
3381 const ui::Transform& displayTransform = displayState.transform;
3382 mat4 m;
3383 m[0][0] = displayTransform[0][0];
3384 m[0][1] = displayTransform[0][1];
3385 m[0][3] = displayTransform[0][2];
3386 m[1][0] = displayTransform[1][0];
3387 m[1][1] = displayTransform[1][1];
3388 m[1][3] = displayTransform[1][2];
3389 m[3][0] = displayTransform[2][0];
3390 m[3][1] = displayTransform[2][1];
3391 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003392
Alec Mouri0f714832018-11-12 15:31:06 -08003393 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003394
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003395 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003396 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003397 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003398 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003399 }
Alec Mouri0f714832018-11-12 15:31:06 -08003400 clientCompositionDisplay.outputDataspace = outputDataspace;
3401 clientCompositionDisplay.maxLuminance =
3402 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003403
Lloyd Pique441d5042018-10-18 16:49:51 -07003404 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003405 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003406 getHwComposer()
3407 .hasDisplayCapability(displayId,
3408 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003409
Peiyong Lind3788632018-09-18 16:01:31 -07003410 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003411 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3412 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003413 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003414 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003415 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003416
Mathias Agopian85d751c2012-08-29 16:59:24 -07003417 /*
3418 * and then, render the layers targeted at the framebuffer
3419 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003420
Dan Stoza9e56aa02015-11-02 13:00:03 -08003421 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003423 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003424 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003425 const Region viewportRegion(displayState.viewport);
3426 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003427 ALOGV("Layer: %s", layer->getName().string());
3428 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003429 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003430 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003431 case HWC2::Composition::Cursor:
3432 case HWC2::Composition::Device:
3433 case HWC2::Composition::Sideband:
3434 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003435 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003436 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003437 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003438 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003439 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 // never clear the very first layer since we're
3441 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003442 renderengine::LayerSettings layerSettings;
3443 Region dummyRegion;
3444 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3445 layerSettings);
3446
3447 if (prepared) {
3448 layerSettings.source.buffer.buffer = nullptr;
3449 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3450 layerSettings.alpha = half(0.0);
3451 layerSettings.disableBlending = true;
3452 clientCompositionLayers.push_back(layerSettings);
3453 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003454 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003455 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003456 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003457 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003458 renderengine::LayerSettings layerSettings;
3459 bool prepared =
3460 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3461 if (prepared) {
3462 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003463 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003464 break;
3465 }
3466 default:
3467 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003468 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003469 } else {
3470 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003471 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003472 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003473 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003474
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003475 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003476 clientCompositionDisplay.clearRegion = clearRegion;
3477 if (!debugRegion.isEmpty()) {
3478 Region::const_iterator it = debugRegion.begin();
3479 Region::const_iterator end = debugRegion.end();
3480 while (it != end) {
3481 const Rect& rect = *it++;
3482 renderengine::LayerSettings layerSettings;
3483 layerSettings.source.buffer.buffer = nullptr;
3484 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3485 layerSettings.geometry.boundaries = rect.toFloatRect();
3486 layerSettings.alpha = half(1.0);
3487 clientCompositionLayers.push_back(layerSettings);
3488 }
3489 }
3490 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3491 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003492 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003493 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494}
3495
Chia-I Wu28e3a252018-09-07 12:05:02 -07003496void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003497 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003498 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499}
3500
Dan Stoza7d89d062015-04-30 13:29:25 -07003501status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003502 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003503 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003504 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003505 const sp<Layer>& parent,
3506 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003507{
Dan Stoza7d89d062015-04-30 13:29:25 -07003508 // add this layer to the current state list
3509 {
3510 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003511 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003512 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3513 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003514 return NO_MEMORY;
3515 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003516 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003517 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003518 } else if (parent == nullptr) {
3519 lbc->onRemovedFromCurrentState();
3520 } else if (parent->isRemovedFromCurrentState()) {
3521 parent->addChild(lbc);
3522 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003523 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003524 parent->addChild(lbc);
3525 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003526
Yiwei Zhang243b3782018-05-15 17:40:04 -07003527 if (gbc != nullptr) {
3528 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3529 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3530 mMaxGraphicBufferProducerListSize,
3531 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3532 mGraphicBufferProducerList.size(),
3533 mMaxGraphicBufferProducerListSize, mNumLayers);
3534 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003535 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003536 }
3537
Mathias Agopian96f08192010-06-02 23:28:45 -07003538 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003539 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003540
Dan Stoza7d89d062015-04-30 13:29:25 -07003541 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003542}
3543
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003544uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003545 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003546}
3547
Mathias Agopian3f844832013-08-07 21:24:32 -07003548uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003549 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550}
3551
Mathias Agopian3f844832013-08-07 21:24:32 -07003552uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003553 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003554}
3555
3556uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003557 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003558 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003559 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003561 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562 }
3563 return old;
3564}
3565
Marissa Wall713b63f2018-10-17 15:42:43 -07003566bool SurfaceFlinger::flushTransactionQueues() {
3567 Mutex::Autolock _l(mStateLock);
3568 auto it = mTransactionQueues.begin();
3569 while (it != mTransactionQueues.end()) {
3570 auto& [applyToken, transactionQueue] = *it;
3571
3572 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3574 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003575 break;
3576 }
chaviw273171b2018-12-26 11:46:30 -08003577 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003578 transactionQueue.pop();
3579 }
3580
3581 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3582 }
3583 return mTransactionQueues.empty();
3584}
3585
chaviwca27f252018-02-06 16:46:39 -08003586bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3587 for (const ComposerState& state : states) {
3588 // Here we need to check that the interface we're given is indeed
3589 // one of our own. A malicious client could give us a nullptr
3590 // IInterface, or one of its own or even one of our own but a
3591 // different type. All these situations would cause us to crash.
3592 if (state.client == nullptr) {
3593 return true;
3594 }
3595
3596 sp<IBinder> binder = IInterface::asBinder(state.client);
3597 if (binder == nullptr) {
3598 return true;
3599 }
3600
3601 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3602 return true;
3603 }
3604 }
3605 return false;
3606}
3607
Marissa Wall17b4e452018-12-26 16:32:34 -08003608bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3609 const Vector<ComposerState>& states) {
3610 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3611 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3612 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3613 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3614 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3615 return false;
3616 }
3617
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 for (const ComposerState& state : states) {
3619 const layer_state_t& s = state.state;
3620 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3621 continue;
3622 }
3623 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003624 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003625 }
3626 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003627 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003628}
3629
3630void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3631 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003632 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003633 const InputWindowCommands& inputWindowCommands,
3634 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003635 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003636 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003637
chaviwca27f252018-02-06 16:46:39 -08003638 if (containsAnyInvalidClientState(states)) {
3639 return;
3640 }
3641
Marissa Wall713b63f2018-10-17 15:42:43 -07003642 // If its TransactionQueue already has a pending TransactionState or if it is pending
3643 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003644 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3645 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003646 setTransactionFlags(eTransactionNeeded);
3647 return;
3648 }
3649
chaviw273171b2018-12-26 11:46:30 -08003650 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003651}
3652
3653void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003654 const Vector<DisplayState>& displays, uint32_t flags,
3655 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003656 uint32_t transactionFlags = 0;
3657
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003658 if (flags & eAnimation) {
3659 // For window updates that are part of an animation we must wait for
3660 // previous animation "frames" to be handled.
3661 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003662 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003663 if (CC_UNLIKELY(err != NO_ERROR)) {
3664 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003665 // caller after a few seconds.
3666 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3667 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003668 mAnimTransactionPending = false;
3669 break;
3670 }
3671 }
3672 }
3673
chaviwca27f252018-02-06 16:46:39 -08003674 for (const DisplayState& display : displays) {
3675 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003676 }
3677
Marissa Walle2ffb422018-10-12 11:33:52 -07003678 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003679 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003680 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003681 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003682 // If the state doesn't require a traversal and there are callbacks, send them now
3683 if (!(clientStateFlags & eTraversalNeeded)) {
3684 mTransactionCompletedThread.sendCallbacks();
3685 }
3686 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003687
chaviw273171b2018-12-26 11:46:30 -08003688 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3689
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003690 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3691 // anyway. This can be used as a flush mechanism for previous async transactions.
3692 // Empty animation transaction can be used to simulate back-pressure, so also force a
3693 // transaction for empty animation transactions.
3694 if (transactionFlags == 0 &&
3695 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003696 transactionFlags = eTransactionNeeded;
3697 }
3698
Mathias Agopian386aa982011-11-07 21:58:03 -08003699 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003700 if (mInterceptor->isEnabled()) {
3701 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003702 }
Irvel468051e2016-06-13 16:44:44 -07003703
Mathias Agopian386aa982011-11-07 21:58:03 -08003704 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003705 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3706 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003707 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003708
3709 // if this is a synchronous transaction, wait for it to take effect
3710 // before returning.
3711 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003712 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003713 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003714 if (flags & eAnimation) {
3715 mAnimTransactionPending = true;
3716 }
3717 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003718 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3719 if (CC_UNLIKELY(err != NO_ERROR)) {
3720 // just in case something goes wrong in SF, return to the
3721 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003722 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3723 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003724 break;
3725 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 }
3728}
3729
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003730uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3731 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3732 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003733
Mathias Agopiane57f2922012-08-09 16:29:12 -07003734 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003735 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3736
3737 const uint32_t what = s.what;
3738 if (what & DisplayState::eSurfaceChanged) {
3739 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3740 state.surface = s.surface;
3741 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003742 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003743 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003744 if (what & DisplayState::eLayerStackChanged) {
3745 if (state.layerStack != s.layerStack) {
3746 state.layerStack = s.layerStack;
3747 flags |= eDisplayTransactionNeeded;
3748 }
3749 }
3750 if (what & DisplayState::eDisplayProjectionChanged) {
3751 if (state.orientation != s.orientation) {
3752 state.orientation = s.orientation;
3753 flags |= eDisplayTransactionNeeded;
3754 }
3755 if (state.frame != s.frame) {
3756 state.frame = s.frame;
3757 flags |= eDisplayTransactionNeeded;
3758 }
3759 if (state.viewport != s.viewport) {
3760 state.viewport = s.viewport;
3761 flags |= eDisplayTransactionNeeded;
3762 }
3763 }
3764 if (what & DisplayState::eDisplaySizeChanged) {
3765 if (state.width != s.width) {
3766 state.width = s.width;
3767 flags |= eDisplayTransactionNeeded;
3768 }
3769 if (state.height != s.height) {
3770 state.height = s.height;
3771 flags |= eDisplayTransactionNeeded;
3772 }
3773 }
3774
Mathias Agopiane57f2922012-08-09 16:29:12 -07003775 return flags;
3776}
3777
Robert Carrd4ae7f32018-06-07 16:10:57 -07003778bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3779 IPCThreadState* ipc = IPCThreadState::self();
3780 const int pid = ipc->getCallingPid();
3781 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003782 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003783 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003784 return false;
3785 }
3786 return true;
3787}
3788
chaviwca27f252018-02-06 16:46:39 -08003789uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3790 const layer_state_t& s = composerState.state;
3791 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3792
Mathias Agopian13127d82013-03-05 17:47:11 -08003793 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003794 if (layer == nullptr) {
3795 return 0;
3796 }
3797
chaviw8b3871a2017-11-01 17:41:01 -07003798 uint32_t flags = 0;
3799
Garfield Tan8a3083e2018-12-03 13:21:07 -08003800 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003801 bool geometryAppliesWithResize =
3802 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003803
3804 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3805 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003806 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003807 layer->pushPendingState();
3808 }
3809
chaviw8b3871a2017-11-01 17:41:01 -07003810 if (what & layer_state_t::ePositionChanged) {
3811 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3812 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003813 }
chaviw8b3871a2017-11-01 17:41:01 -07003814 }
3815 if (what & layer_state_t::eLayerChanged) {
3816 // NOTE: index needs to be calculated before we update the state
3817 const auto& p = layer->getParent();
3818 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003819 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003820 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003821 mCurrentState.layersSortedByZ.removeAt(idx);
3822 mCurrentState.layersSortedByZ.add(layer);
3823 // we need traversal (state changed)
3824 // AND transaction (list changed)
3825 flags |= eTransactionNeeded|eTraversalNeeded;
3826 }
chaviw8b3871a2017-11-01 17:41:01 -07003827 } else {
3828 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003829 flags |= eTransactionNeeded|eTraversalNeeded;
3830 }
3831 }
chaviw8b3871a2017-11-01 17:41:01 -07003832 }
3833 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003834 // NOTE: index needs to be calculated before we update the state
3835 const auto& p = layer->getParent();
3836 if (p == nullptr) {
3837 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3838 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3839 mCurrentState.layersSortedByZ.removeAt(idx);
3840 mCurrentState.layersSortedByZ.add(layer);
3841 // we need traversal (state changed)
3842 // AND transaction (list changed)
3843 flags |= eTransactionNeeded|eTraversalNeeded;
3844 }
3845 } else {
3846 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3847 flags |= eTransactionNeeded|eTraversalNeeded;
3848 }
chaviw8b3871a2017-11-01 17:41:01 -07003849 }
3850 }
3851 if (what & layer_state_t::eSizeChanged) {
3852 if (layer->setSize(s.w, s.h)) {
3853 flags |= eTraversalNeeded;
3854 }
3855 }
3856 if (what & layer_state_t::eAlphaChanged) {
3857 if (layer->setAlpha(s.alpha))
3858 flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eColorChanged) {
3861 if (layer->setColor(s.color))
3862 flags |= eTraversalNeeded;
3863 }
Valerie Haued54efa2019-01-11 20:03:14 -08003864 if (what & layer_state_t::eColorAlphaChanged) {
3865 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3866 }
3867 if (what & layer_state_t::eColorDataspaceChanged) {
3868 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3869 }
Peiyong Lind3788632018-09-18 16:01:31 -07003870 if (what & layer_state_t::eColorTransformChanged) {
3871 if (layer->setColorTransform(s.colorTransform)) {
3872 flags |= eTraversalNeeded;
3873 }
3874 }
chaviw8b3871a2017-11-01 17:41:01 -07003875 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003876 // TODO: b/109894387
3877 //
3878 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3879 // rotation. To see the problem observe that if we have a square parent, and a child
3880 // of the same size, then we rotate the child 45 degrees around it's center, the child
3881 // must now be cropped to a non rectangular 8 sided region.
3882 //
3883 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3884 // private API, and the WindowManager only uses rotation in one case, which is on a top
3885 // level layer in which cropping is not an issue.
3886 //
3887 // However given that abuse of rotation matrices could lead to surfaces extending outside
3888 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3889 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3890 // transformations.
3891 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003892 flags |= eTraversalNeeded;
3893 }
3894 if (what & layer_state_t::eTransparentRegionChanged) {
3895 if (layer->setTransparentRegionHint(s.transparentRegion))
3896 flags |= eTraversalNeeded;
3897 }
3898 if (what & layer_state_t::eFlagsChanged) {
3899 if (layer->setFlags(s.flags, s.mask))
3900 flags |= eTraversalNeeded;
3901 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003902 if (what & layer_state_t::eCropChanged_legacy) {
3903 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003904 flags |= eTraversalNeeded;
3905 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003906 if (what & layer_state_t::eCornerRadiusChanged) {
3907 if (layer->setCornerRadius(s.cornerRadius))
3908 flags |= eTraversalNeeded;
3909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (what & layer_state_t::eLayerStackChanged) {
3911 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3912 // We only allow setting layer stacks for top level layers,
3913 // everything else inherits layer stack from its parent.
3914 if (layer->hasParent()) {
3915 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3916 layer->getName().string());
3917 } else if (idx < 0) {
3918 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3919 "that also does not appear in the top level layer list. Something"
3920 " has gone wrong.", layer->getName().string());
3921 } else if (layer->setLayerStack(s.layerStack)) {
3922 mCurrentState.layersSortedByZ.removeAt(idx);
3923 mCurrentState.layersSortedByZ.add(layer);
3924 // we need traversal (state changed)
3925 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003926 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003927 }
3928 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003929 if (what & layer_state_t::eDeferTransaction_legacy) {
3930 if (s.barrierHandle_legacy != nullptr) {
3931 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3932 } else if (s.barrierGbp_legacy != nullptr) {
3933 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003934 if (authenticateSurfaceTextureLocked(gbp)) {
3935 const auto& otherLayer =
3936 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003937 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003938 } else {
3939 ALOGE("Attempt to defer transaction to to an"
3940 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003941 }
3942 }
chaviw8b3871a2017-11-01 17:41:01 -07003943 // We don't trigger a traversal here because if no other state is
3944 // changed, we don't want this to cause any more work
3945 }
3946 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003947 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003948 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003949 if (!hadParent) {
3950 mCurrentState.layersSortedByZ.remove(layer);
3951 }
chaviw8b3871a2017-11-01 17:41:01 -07003952 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003953 }
chaviw8b3871a2017-11-01 17:41:01 -07003954 }
3955 if (what & layer_state_t::eReparentChildren) {
3956 if (layer->reparentChildren(s.reparentHandle)) {
3957 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003958 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003959 }
chaviw8b3871a2017-11-01 17:41:01 -07003960 if (what & layer_state_t::eDetachChildren) {
3961 layer->detachChildren();
3962 }
3963 if (what & layer_state_t::eOverrideScalingModeChanged) {
3964 layer->setOverrideScalingMode(s.overrideScalingMode);
3965 // We don't trigger a traversal here because if no other state is
3966 // changed, we don't want this to cause any more work
3967 }
Marissa Wall61c58622018-07-18 10:12:20 -07003968 if (what & layer_state_t::eTransformChanged) {
3969 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3970 }
3971 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3972 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3973 flags |= eTraversalNeeded;
3974 }
3975 if (what & layer_state_t::eCropChanged) {
3976 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3977 }
Marissa Wall861616d2018-10-22 12:52:23 -07003978 if (what & layer_state_t::eFrameChanged) {
3979 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3980 }
Marissa Wall61c58622018-07-18 10:12:20 -07003981 if (what & layer_state_t::eBufferChanged) {
3982 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3983 }
3984 if (what & layer_state_t::eAcquireFenceChanged) {
3985 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3986 }
3987 if (what & layer_state_t::eDataspaceChanged) {
3988 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3989 }
3990 if (what & layer_state_t::eHdrMetadataChanged) {
3991 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3992 }
3993 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3994 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3995 }
3996 if (what & layer_state_t::eApiChanged) {
3997 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3998 }
3999 if (what & layer_state_t::eSidebandStreamChanged) {
4000 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4001 }
Robert Carr720e5062018-07-30 17:45:14 -07004002 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004003 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4004 layer->setInputInfo(s.inputInfo);
4005 flags |= eTraversalNeeded;
4006 } else {
4007 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4008 }
Robert Carr720e5062018-07-30 17:45:14 -07004009 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004010 if (what & layer_state_t::eMetadataChanged) {
4011 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4012 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004013 std::vector<sp<CallbackHandle>> callbackHandles;
4014 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4015 mTransactionCompletedThread.run();
4016 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4017 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4018 }
4019 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004020 if (what & layer_state_t::eCachedBufferChanged) {
4021 sp<GraphicBuffer> buffer =
4022 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4023 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4024 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004025 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4026 // Do not put anything that updates layer state or modifies flags after
4027 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004028 return flags;
4029}
4030
chaviw273171b2018-12-26 11:46:30 -08004031uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4032 uint32_t flags = 0;
4033 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4034 flags |= eTraversalNeeded;
4035 }
4036
4037 mInputWindowCommands.merge(inputWindowCommands);
4038 return flags;
4039}
4040
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004041status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4042 uint32_t h, PixelFormat format, uint32_t flags,
4043 LayerMetadata metadata, sp<IBinder>* handle,
4044 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004045 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004046 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004047 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004048 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004049 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004050
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004051 status_t result = NO_ERROR;
4052
4053 sp<Layer> layer;
4054
Cody Northropbc755282017-03-31 12:00:08 -06004055 String8 uniqueName = getUniqueLayerName(name);
4056
Mathias Agopian3165cc22012-08-08 19:42:09 -07004057 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004058 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004059 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4060 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004061
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004063 case ISurfaceComposerClient::eFXSurfaceBufferState:
4064 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4065 break;
chaviw13fdc492017-06-27 12:40:18 -07004066 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004067 // check if buffer size is set for color layer.
4068 if (w > 0 || h > 0) {
4069 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4070 int(w), int(h));
4071 return BAD_VALUE;
4072 }
4073
chaviw13fdc492017-06-27 12:40:18 -07004074 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004075 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004076 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004078 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004079 // check if buffer size is set for container layer.
4080 if (w > 0 || h > 0) {
4081 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4082 int(w), int(h));
4083 return BAD_VALUE;
4084 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004085 result = createContainerLayer(client,
4086 uniqueName, w, h, flags,
4087 handle, &layer);
4088 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 default:
4090 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 break;
4092 }
4093
Dan Stoza7d89d062015-04-30 13:29:25 -07004094 if (result != NO_ERROR) {
4095 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004097
Chia-I Wuab0c3192017-08-01 11:29:00 -07004098 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4099 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004100 if (metadata.has(METADATA_WINDOW_TYPE)) {
4101 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4102 if (windowType == 441731) {
4103 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4104 layer->setPrimaryDisplayOnly();
4105 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004106 }
4107
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004108 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004109
Robert Carrb89ea9d2018-12-10 13:01:14 -08004110 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4111 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4112 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004113 if (result != NO_ERROR) {
4114 return result;
4115 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004116 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004117
4118 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004119 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120}
4121
Cody Northropbc755282017-03-31 12:00:08 -06004122String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4123{
4124 bool matchFound = true;
4125 uint32_t dupeCounter = 0;
4126
4127 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4128 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4129
Dan Stoza436ccf32018-06-21 12:10:12 -07004130 // Grab the state lock since we're accessing mCurrentState
4131 Mutex::Autolock lock(mStateLock);
4132
Cody Northropbc755282017-03-31 12:00:08 -06004133 // Loop over layers until we're sure there is no matching name
4134 while (matchFound) {
4135 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004136 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004137 if (layer->getName() == uniqueName) {
4138 matchFound = true;
4139 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4140 }
4141 });
4142 }
4143
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004144 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4145 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004146
4147 return uniqueName;
4148}
4149
Marissa Wallfd668622018-05-10 10:21:13 -07004150status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4151 uint32_t w, uint32_t h, uint32_t flags,
4152 PixelFormat& format, sp<IBinder>* handle,
4153 sp<IGraphicBufferProducer>* gbp,
4154 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004156 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157 case PIXEL_FORMAT_TRANSPARENT:
4158 case PIXEL_FORMAT_TRANSLUCENT:
4159 format = PIXEL_FORMAT_RGBA_8888;
4160 break;
4161 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004162 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004163 break;
4164 }
4165
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004166 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004167 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004168 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004169 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004170 *handle = layer->getHandle();
4171 *gbp = layer->getProducer();
4172 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004174
Marissa Wallfd668622018-05-10 10:21:13 -07004175 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004176 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004177}
4178
Marissa Wall61c58622018-07-18 10:12:20 -07004179status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4180 uint32_t w, uint32_t h, uint32_t flags,
4181 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004182 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004183 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004184 *handle = layer->getHandle();
4185 *outLayer = layer;
4186
4187 return NO_ERROR;
4188}
4189
chaviw13fdc492017-06-27 12:40:18 -07004190status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004191 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004192 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004194 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004195 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004196 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004197}
4198
Robert Carr6b3f6c52018-08-13 13:05:17 -07004199status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4200 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4201 sp<IBinder>* handle, sp<Layer>* outLayer)
4202{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004203 *outLayer =
4204 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004205 *handle = (*outLayer)->getHandle();
4206 return NO_ERROR;
4207}
4208
4209
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004210void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004211 mLayersPendingRemoval.add(layer);
4212 mLayersRemoved = true;
4213 setTransactionFlags(eTransactionNeeded);
4214}
4215
Robert Carr695d5282018-12-18 15:27:58 -08004216void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004217{
Robert Carr2e102c92018-10-23 12:11:15 -07004218 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004219 // If a layer has a parent, we allow it to out-live it's handle
4220 // with the idea that the parent holds a reference and will eventually
4221 // be cleaned up. However no one cleans up the top-level so we do so
4222 // here.
4223 if (layer->getParent() == nullptr) {
4224 mCurrentState.layersSortedByZ.remove(layer);
4225 }
4226 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004227 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004228}
4229
Mathias Agopianb60314a2012-04-10 22:09:54 -07004230// ---------------------------------------------------------------------------
4231
Andy McFadden13a082e2012-08-24 10:16:42 -07004232void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004233 const auto display = getDefaultDisplayDeviceLocked();
4234 if (!display) return;
4235
4236 const sp<IBinder> token = display->getDisplayToken().promote();
4237 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004238
Jesse Hall01e29052013-02-19 16:13:35 -08004239 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004240 Vector<ComposerState> state;
4241 Vector<DisplayState> displays;
4242 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004243 d.what = DisplayState::eDisplayProjectionChanged |
4244 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004245 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004246 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004247 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004248 d.frame.makeInvalid();
4249 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004250 d.width = 0;
4251 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004252 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004253 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004254
Dominik Laskowskie9774092018-12-11 10:04:24 -08004255 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004256
Dominik Laskowski83b88212018-12-11 13:34:06 -08004257 const nsecs_t vsyncPeriod = getVsyncPeriod();
4258 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004259
Brian Andersond0010582017-03-07 13:20:31 -08004260 // Use phase of 0 since phase is not known.
4261 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004262 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004263 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004264}
4265
4266void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004267 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004268 postMessageAsync(
4269 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004270}
4271
Dominik Laskowskie9774092018-12-11 10:04:24 -08004272void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004273 if (display->isVirtual()) {
4274 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004275 return;
4276 }
4277
Dominik Laskowski075d3172018-05-24 15:50:06 -07004278 const auto displayId = display->getId();
4279 LOG_ALWAYS_FATAL_IF(!displayId);
4280
Dominik Laskowski34157762018-10-31 13:07:19 -07004281 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004282
4283 int currentMode = display->getPowerMode();
4284 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004285 return;
4286 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 display->setPowerMode(mode);
4289
Lloyd Pique4dccc412018-01-22 17:21:36 -08004290 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004291 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004292 }
4293
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004295 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004296 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004297 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004298 if (mUseScheduler) {
4299 mScheduler->onScreenAcquired(mAppConnectionHandle);
4300 } else {
4301 mEventThread->onScreenAcquired();
4302 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004303 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004304 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004306 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004307 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004308 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004309
4310 struct sched_param param = {0};
4311 param.sched_priority = 1;
4312 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4313 ALOGW("Couldn't set SCHED_FIFO on display on");
4314 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004315 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004316 // Turn off the display
4317 struct sched_param param = {0};
4318 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4319 ALOGW("Couldn't set SCHED_OTHER on display off");
4320 }
4321
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004322 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004323 if (mUseScheduler) {
4324 mScheduler->disableHardwareVsync(true);
4325 } else {
4326 disableHardwareVsync(true); // also cancels any in-progress resync
4327 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004328 if (mUseScheduler) {
4329 mScheduler->onScreenReleased(mAppConnectionHandle);
4330 } else {
4331 mEventThread->onScreenReleased();
4332 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004333 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004334
Dominik Laskowski075d3172018-05-24 15:50:06 -07004335 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004336 mVisibleRegionsDirty = true;
4337 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004338 } else if (mode == HWC_POWER_MODE_DOZE ||
4339 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004340 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004341 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004342 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004343 if (mUseScheduler) {
4344 mScheduler->onScreenAcquired(mAppConnectionHandle);
4345 } else {
4346 mEventThread->onScreenAcquired();
4347 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004348 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004349 }
4350 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4351 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004352 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004353 if (mUseScheduler) {
4354 mScheduler->disableHardwareVsync(true);
4355 } else {
4356 disableHardwareVsync(true); // also cancels any in-progress resync
4357 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004358 if (mUseScheduler) {
4359 mScheduler->onScreenReleased(mAppConnectionHandle);
4360 } else {
4361 mEventThread->onScreenReleased();
4362 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004363 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004364 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004365 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004366 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004367 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004368 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004369
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004370 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004371 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004372 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004373 // Update refresh rate stats.
4374 mRefreshRateStats->setPowerMode(mode);
4375 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004376 }
4377
Dominik Laskowski34157762018-10-31 13:07:19 -07004378 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004379}
4380
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004382 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004383 const auto display = getDisplayDevice(displayToken);
4384 if (!display) {
4385 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4386 displayToken.get());
4387 } else if (display->isVirtual()) {
4388 ALOGW("Attempt to set power mode %d for virtual display", mode);
4389 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004390 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004391 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004392 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004393}
4394
4395// ---------------------------------------------------------------------------
4396
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4398 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004399 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004400
Mathias Agopianbd115332013-04-18 16:41:04 -07004401 IPCThreadState* ipc = IPCThreadState::self();
4402 const int pid = ipc->getCallingPid();
4403 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004404
Mathias Agopianbd115332013-04-18 16:41:04 -07004405 if ((uid != AID_SHELL) &&
4406 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004407 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4408 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004409 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004410 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004411 // (this would indicate SF is stuck, but we want to be able to
4412 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004413 status_t err = mStateLock.timedLock(s2ns(1));
4414 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004415 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416 StringAppendF(&result,
4417 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4418 "(no locks held)\n",
4419 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004420 }
4421
Dominik Laskowskic2867142019-01-21 11:33:38 -08004422 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004423
Dominik Laskowskic2867142019-01-21 11:33:38 -08004424 static const std::unordered_map<std::string, Dumper> dumpers = {
4425 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4426 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4427 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4428 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4429 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4430 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4431 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4432 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4433 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4434 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4435 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4436 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4437 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004438 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004439 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4440 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004441
Dominik Laskowskic2867142019-01-21 11:33:38 -08004442 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004443
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4445 (it->second)(args, asProto, result);
4446 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004447 if (asProto) {
4448 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4449 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4450 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004452 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004453 }
4454
Mathias Agopian9795c422009-08-26 16:36:26 -07004455 if (locked) {
4456 mStateLock.unlock();
4457 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004458 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004460 return NO_ERROR;
4461}
4462
Dominik Laskowskic2867142019-01-21 11:33:38 -08004463void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004464 mCurrentState.traverseInZOrder(
4465 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004466}
4467
Dominik Laskowskic2867142019-01-21 11:33:38 -08004468void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004469 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004470
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471 if (args.size() > 1) {
4472 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004473 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004474 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004475 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004476 }
Robert Carr2047fae2016-11-28 14:09:09 -08004477 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004478 } else {
4479 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004480 }
4481}
4482
Dominik Laskowskic2867142019-01-21 11:33:38 -08004483void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004484 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004485 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004486 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004487 }
Robert Carr2047fae2016-11-28 14:09:09 -08004488 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004489
Svetoslavd85084b2014-03-20 10:28:31 -07004490 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004491}
4492
Dominik Laskowskic2867142019-01-21 11:33:38 -08004493void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4494 mTimeStats->parseArgs(asProto, args, result);
4495}
4496
Jamie Gennis6547ff42013-07-16 20:12:42 -07004497// This should only be called from the main thread. Otherwise it would need
4498// the lock and should use mCurrentState rather than mDrawingState.
4499void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004500 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004501 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004502 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004503
4504 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4505}
4506
Yiwei Zhang5434a782018-12-05 18:06:32 -08004507void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004508 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004509
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004510 if (isLayerTripleBufferingDisabled())
4511 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004512
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4514 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4515 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4516 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4517 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4518 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004519 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004520}
4521
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004522void SurfaceFlinger::dumpVSync(std::string& result) const {
4523 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4524 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4525 StringAppendF(&result,
4526 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4527 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4528 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4529 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4530 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4531 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4532
4533 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4534
4535 if (mUseScheduler) {
4536 mScheduler->dump(mAppConnectionHandle, result);
4537 } else {
4538 mEventThread->dump(result);
4539 }
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4543 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004544 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4545 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004546 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004547 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004548 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004549 }
David Sodman4a36e932017-11-07 14:29:47 -08004550 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004551 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004552 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4554 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004555}
4556
Dan Stozae77c7662016-05-13 11:37:28 -07004557void SurfaceFlinger::recordBufferingStats(const char* layerName,
4558 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004559 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4560 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004561 for (const auto& segment : history) {
4562 if (!segment.usedThirdBuffer) {
4563 stats.twoBufferTime += segment.totalTime;
4564 }
4565 if (segment.occupancyAverage < 1.0f) {
4566 stats.doubleBufferedTime += segment.totalTime;
4567 } else if (segment.occupancyAverage < 2.0f) {
4568 stats.tripleBufferedTime += segment.totalTime;
4569 }
4570 ++stats.numSegments;
4571 stats.totalTime += segment.totalTime;
4572 }
4573}
4574
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4576 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004577
4578 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4579 const size_t count = currentLayers.size();
4580 for (size_t i=0 ; i<count ; i++) {
4581 currentLayers[i]->dumpFrameEvents(result);
4582 }
4583}
4584
Yiwei Zhang5434a782018-12-05 18:06:32 -08004585void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004586 result.append("Buffering stats:\n");
4587 result.append(" [Layer name] <Active time> <Two buffer> "
4588 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004589 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004590 typedef std::tuple<std::string, float, float, float> BufferTuple;
4591 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004592 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004593 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004594 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004595 if (stats.numSegments == 0) {
4596 continue;
4597 }
4598 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4599 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4600 stats.totalTime;
4601 float doubleBufferRatio = static_cast<float>(
4602 stats.doubleBufferedTime) / stats.totalTime;
4603 float tripleBufferRatio = static_cast<float>(
4604 stats.tripleBufferedTime) / stats.totalTime;
4605 sorted.insert({activeTime, {name, twoBufferRatio,
4606 doubleBufferRatio, tripleBufferRatio}});
4607 }
4608 for (const auto& sortedPair : sorted) {
4609 float activeTime = sortedPair.first;
4610 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004611 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4612 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004613 }
4614 result.append("\n");
4615}
4616
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004618 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004619 const auto displayId = display->getId();
4620 if (!displayId) {
4621 continue;
4622 }
4623 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004624 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004625 continue;
4626 }
4627
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result,
4629 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4630 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004631 uint8_t port;
4632 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004633 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004634 result.append("no identification data\n");
4635 continue;
4636 }
4637
4638 if (!isEdid(data)) {
4639 result.append("unknown identification data: ");
4640 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004642 }
4643 result.append("\n");
4644 continue;
4645 }
4646
4647 const auto edid = parseEdid(data);
4648 if (!edid) {
4649 result.append("invalid EDID: ");
4650 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004652 }
4653 result.append("\n");
4654 continue;
4655 }
4656
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 result.append(edid->displayName.data(), edid->displayName.length());
4659 result.append("\"\n");
4660 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004661}
4662
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4664 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4665 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4666 StringAppendF(&result, "DisplayColorSetting: %s\n",
4667 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004668
4669 // TODO: print out if wide-color mode is active or not
4670
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004671 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004672 const auto displayId = display->getId();
4673 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004674 continue;
4675 }
4676
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004678 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004679 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004681 }
4682
Lloyd Pique32cbe282018-10-19 13:09:22 -07004683 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684 StringAppendF(&result, " Current color mode: %s (%d)\n",
4685 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004686 }
4687 result.append("\n");
4688}
4689
Yiwei Zhang5434a782018-12-05 18:06:32 -08004690void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004691 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004692 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4693 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004694 continue;
4695 }
4696
Dominik Laskowski05275f12018-11-01 15:03:24 -07004697 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004698 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4699 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004700 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 compositionInfo.dump(result, nullptr);
4702 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004703 }
4704 }
David Sodman7e4ae112018-02-09 15:02:28 -08004705}
4706
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004707LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004708 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004709 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4710 const State& state = useDrawing ? mDrawingState : mCurrentState;
4711 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004712 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004713 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004714 });
4715
4716 return layersProto;
4717}
4718
Lloyd Pique32cbe282018-10-19 13:09:22 -07004719LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004720 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004721
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004722 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004723 resolution->set_w(displayDevice.getWidth());
4724 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004725
Lloyd Pique32cbe282018-10-19 13:09:22 -07004726 auto display = displayDevice.getCompositionDisplay();
4727 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004728
Lloyd Pique32cbe282018-10-19 13:09:22 -07004729 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4730 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4731 layersProto.set_global_transform(displayState.orientation);
4732
4733 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004734 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004735 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004736 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004737 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004739 }
4740 });
4741
4742 return layersProto;
4743}
4744
Dominik Laskowskic2867142019-01-21 11:33:38 -08004745void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4746 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 Colorizer colorizer(colorize);
4748
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004749 // figure out if we're stuck somewhere
4750 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4753
4754 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004755 * Dump library configuration.
4756 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004757
4758 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004759 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004760 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004761 appendSfConfigString(result);
4762 appendUiConfigString(result);
4763 appendGuiConfigString(result);
4764 result.append("\n");
4765
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004766 result.append("\nDisplay identification data:\n");
4767 dumpDisplayIdentificationData(result);
4768
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004769 result.append("\nWide-Color information:\n");
4770 dumpWideColorInfo(result);
4771
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004772 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004773 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004775 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004776 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004777
Andy McFadden41d67d72014-04-25 16:58:34 -07004778 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004779 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004780 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004781 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004782 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004783
Dan Stozab90cf072015-03-05 11:05:59 -08004784 dumpStaticScreenStats(result);
4785 result.append("\n");
4786
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004788
Dan Stozae77c7662016-05-13 11:37:28 -07004789 dumpBufferingStats(result);
4790
Andy McFadden4803b742012-09-24 19:07:20 -07004791 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004792 * Dump the visible layer list
4793 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004794 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4796 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4797 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004798 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004799
Chia-I Wu2f884132018-09-13 15:17:58 -07004800 {
4801 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4802 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004804 result.append("\n");
4805 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806
David Sodman7e4ae112018-02-09 15:02:28 -08004807 result.append("\nFrame-Composition information:\n");
4808 dumpFrameCompositionInfo(result);
4809 result.append("\n");
4810
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004811 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004812 * Dump Display state
4813 */
4814
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004815 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004816 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004817 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004818 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004819 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004820 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004821 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004822
4823 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004824 * Dump SurfaceFlinger global state
4825 */
4826
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004827 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004828 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004829 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004831 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832
Dominik Laskowski075d3172018-05-24 15:50:06 -07004833 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004834 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4835 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4837 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004838 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004839 StringAppendF(&result,
4840 " transaction-flags : %08x\n"
4841 " gpu_to_cpu_unsupported : %d\n",
4842 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004843
Dominik Laskowski075d3172018-05-24 15:50:06 -07004844 if (const auto displayId = getInternalDisplayId();
4845 displayId && getHwComposer().isConnected(*displayId)) {
4846 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004847 StringAppendF(&result,
4848 " refresh-rate : %f fps\n"
4849 " x-dpi : %f\n"
4850 " y-dpi : %f\n",
4851 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4852 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004853 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004854
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004856
Dan Stozae22aec72016-08-01 13:20:59 -07004857 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004858 * Tracing state
4859 */
4860 mTracing.dump(result);
4861 result.append("\n");
4862
4863 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004864 * HWC layer minidump
4865 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004866 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004867 const auto displayId = display->getId();
4868 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004869 continue;
4870 }
4871
Yiwei Zhang5434a782018-12-05 18:06:32 -08004872 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004873 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004875 result.append("\n");
4876 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004877
4878 /*
4879 * Dump HWComposer state
4880 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004881 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004882 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004883 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004884 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004885 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004887
4888 /*
4889 * Dump gralloc state
4890 */
4891 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4892 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004893
4894 /*
4895 * Dump VrFlinger state if in use.
4896 */
4897 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4898 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004899 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004900 result.append("\n");
4901 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004902
4903 /**
4904 * Scheduler dump state.
4905 */
4906 if (mUseScheduler) {
4907 result.append("\nScheduler state:\n");
4908 result.append(mScheduler->doDump() + "\n");
4909 result.append(mRefreshRateStats->doDump() + "\n");
4910 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004911}
4912
Dominik Laskowski075d3172018-05-24 15:50:06 -07004913const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004914 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004915 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004916 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004917 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004918 }
4919 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004920
Dominik Laskowski34157762018-10-31 13:07:19 -07004921 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004922 static const Vector<sp<Layer>> empty;
4923 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004924}
4925
Keun young Park63f165f2012-08-31 10:53:36 -07004926bool SurfaceFlinger::startDdmConnection()
4927{
4928 void* libddmconnection_dso =
4929 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4930 if (!libddmconnection_dso) {
4931 return false;
4932 }
4933 void (*DdmConnection_start)(const char* name);
4934 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004935 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004936 if (!DdmConnection_start) {
4937 dlclose(libddmconnection_dso);
4938 return false;
4939 }
4940 (*DdmConnection_start)(getServiceName());
4941 return true;
4942}
4943
Chia-I Wu28f320b2018-05-03 11:02:56 -07004944void SurfaceFlinger::updateColorMatrixLocked() {
4945 mat4 colorMatrix;
4946 if (mGlobalSaturationFactor != 1.0f) {
4947 // Rec.709 luma coefficients
4948 float3 luminance{0.213f, 0.715f, 0.072f};
4949 luminance *= 1.0f - mGlobalSaturationFactor;
4950 mat4 saturationMatrix = mat4(
4951 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4952 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4953 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4954 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4955 );
4956 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4957 } else {
4958 colorMatrix = mClientColorMatrix * mDaltonizer();
4959 }
4960
4961 if (mCurrentState.colorMatrix != colorMatrix) {
4962 mCurrentState.colorMatrix = colorMatrix;
4963 mCurrentState.colorMatrixChanged = true;
4964 setTransactionFlags(eTransactionNeeded);
4965 }
4966}
4967
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004968status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969#pragma clang diagnostic push
4970#pragma clang diagnostic error "-Wswitch-enum"
4971 switch (static_cast<ISurfaceComposerTag>(code)) {
4972 // These methods should at minimum make sure that the client requested
4973 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004974 case BOOT_FINISHED:
4975 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 case CREATE_DISPLAY:
4977 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004978 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979 case GET_ACTIVE_COLOR_MODE:
4980 case GET_ANIMATION_FRAME_STATS:
4981 case GET_HDR_CAPABILITIES:
4982 case SET_ACTIVE_CONFIG:
4983 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004984 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004985 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004986 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004987 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4988 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004989 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4990 IPCThreadState* ipc = IPCThreadState::self();
4991 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4992 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004993 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004994 }
Robert Carr1db73f62016-12-21 12:58:51 -08004995 return OK;
4996 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004997 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004998 IPCThreadState* ipc = IPCThreadState::self();
4999 const int pid = ipc->getCallingPid();
5000 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5002 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005003 return PERMISSION_DENIED;
5004 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005005 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005006 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005007 // Used by apps to hook Choreographer to SurfaceFlinger.
5008 case CREATE_DISPLAY_EVENT_CONNECTION:
5009 // The following calls are currently used by clients that do not
5010 // request necessary permissions. However, they do not expose any secret
5011 // information, so it is OK to pass them.
5012 case AUTHENTICATE_SURFACE:
5013 case GET_ACTIVE_CONFIG:
5014 case GET_BUILT_IN_DISPLAY:
5015 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005016 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017 case GET_DISPLAY_CONFIGS:
5018 case GET_DISPLAY_STATS:
5019 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5020 // Calling setTransactionState is safe, because you need to have been
5021 // granted a reference to Client* and Handle* to do anything with it.
5022 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005023 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005024 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005025 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005026 case GET_PROTECTED_CONTENT_SUPPORT:
5027 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005028 case UNCACHE_BUFFER:
5029 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030 return OK;
5031 }
5032 case CAPTURE_LAYERS:
5033 case CAPTURE_SCREEN: {
5034 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005035 IPCThreadState* ipc = IPCThreadState::self();
5036 const int pid = ipc->getCallingPid();
5037 const int uid = ipc->getCallingUid();
5038 if ((uid != AID_GRAPHICS) &&
5039 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5040 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5041 return PERMISSION_DENIED;
5042 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005043 return OK;
5044 }
5045 // The following codes are deprecated and should never be allowed to access SF.
5046 case CONNECT_DISPLAY_UNUSED:
5047 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5048 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5049 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005050 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052
5053 // These codes are used for the IBinder protocol to either interrogate the recipient
5054 // side of the transaction for its canonical interface descriptor or to dump its state.
5055 // We let them pass by default.
5056 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5057 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5058 code == IBinder::SYSPROPS_TRANSACTION) {
5059 return OK;
5060 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005061 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005063 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005064 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5065 return OK;
5066 }
5067 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5068 return PERMISSION_DENIED;
5069#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005070}
5071
Ana Krulec13be8ad2018-08-21 02:43:56 +00005072status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5073 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005074 status_t credentialCheck = CheckTransactCodeCredentials(code);
5075 if (credentialCheck != OK) {
5076 return credentialCheck;
5077 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5080 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005081 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005082 IPCThreadState* ipc = IPCThreadState::self();
5083 const int uid = ipc->getCallingUid();
5084 if (CC_UNLIKELY(uid != AID_SYSTEM
5085 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005086 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005087 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005088 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005089 return PERMISSION_DENIED;
5090 }
5091 int n;
5092 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005093 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005094 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 return NO_ERROR;
5096 case 1002: // SHOW_UPDATES
5097 n = data.readInt32();
5098 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005099 invalidateHwcGeometry();
5100 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005103 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005104 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005105 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005106 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005107 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005108 setTransactionFlags(
5109 eTransactionNeeded|
5110 eDisplayTransactionNeeded|
5111 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005112 return NO_ERROR;
5113 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005114 case 1006:{ // send empty update
5115 signalRefresh();
5116 return NO_ERROR;
5117 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005118 case 1008: // toggle use of hw composer
5119 n = data.readInt32();
5120 mDebugDisableHWC = n ? 1 : 0;
5121 invalidateHwcGeometry();
5122 repaintEverything();
5123 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005124 case 1009: // toggle use of transform hint
5125 n = data.readInt32();
5126 mDebugDisableTransformHint = n ? 1 : 0;
5127 invalidateHwcGeometry();
5128 repaintEverything();
5129 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005130 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005131 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005132 reply->writeInt32(0);
5133 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005134 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005135 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005136 return NO_ERROR;
5137 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005138 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005139 if (!display) {
5140 return NAME_NOT_FOUND;
5141 }
5142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005143 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005144 return NO_ERROR;
5145 }
5146 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005147 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005148 // daltonize
5149 n = data.readInt32();
5150 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005151 case 1:
5152 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5153 break;
5154 case 2:
5155 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5156 break;
5157 case 3:
5158 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5159 break;
5160 default:
5161 mDaltonizer.setType(ColorBlindnessType::None);
5162 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005163 }
5164 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005165 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005166 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005167 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005168 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169
5170 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005171 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005174 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005175 // apply a color matrix
5176 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005177 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005178 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005179 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005180 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005181 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005182 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005183 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005184 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005186 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005187
5188 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5189 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005191 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5192 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5193 }
5194
Chia-I Wu28f320b2018-05-03 11:02:56 -07005195 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005196 return NO_ERROR;
5197 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005198 // This is an experimental interface
5199 // Needs to be shifted to proper binder interface when we productize
5200 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005201 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005202 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005203 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005204 return NO_ERROR;
5205 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005206 case 1017: {
5207 n = data.readInt32();
5208 mForceFullDamage = static_cast<bool>(n);
5209 return NO_ERROR;
5210 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005211 case 1018: { // Modify Choreographer's phase offset
5212 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005213 if (mUseScheduler) {
5214 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5215 } else {
5216 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5217 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005218 return NO_ERROR;
5219 }
5220 case 1019: { // Modify SurfaceFlinger's phase offset
5221 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005222 if (mUseScheduler) {
5223 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5224 } else {
5225 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5226 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005227 return NO_ERROR;
5228 }
Irvel468051e2016-06-13 16:44:44 -07005229 case 1020: { // Layer updates interceptor
5230 n = data.readInt32();
5231 if (n) {
5232 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005233 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005234 }
5235 else{
5236 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005237 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005238 }
5239 return NO_ERROR;
5240 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005241 case 1021: { // Disable HWC virtual displays
5242 n = data.readInt32();
5243 mUseHwcVirtualDisplays = !n;
5244 return NO_ERROR;
5245 }
Romain Guy0147a172017-06-01 13:53:56 -07005246 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005247 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005248 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005249
Chia-I Wu28f320b2018-05-03 11:02:56 -07005250 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005251 return NO_ERROR;
5252 }
Romain Guy54f154a2017-10-24 21:40:32 +01005253 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005254 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005255 invalidateHwcGeometry();
5256 repaintEverything();
5257 return NO_ERROR;
5258 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005259 // Deprecate, use 1030 to check whether the device is color managed.
5260 case 1024: {
5261 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005262 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005263 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005264 n = data.readInt32();
5265 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005266 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005267 mTracing.enable();
5268 doTracing("tracing.enable");
5269 reply->writeInt32(NO_ERROR);
5270 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005271 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005272 status_t err = mTracing.disable();
5273 reply->writeInt32(err);
5274 }
5275 return NO_ERROR;
5276 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005277 case 1026: { // Get layer tracing status
5278 reply->writeBool(mTracing.isEnabled());
5279 return NO_ERROR;
5280 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005281 // Is a DisplayColorSetting supported?
5282 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005283 const auto display = getDefaultDisplayDevice();
5284 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005285 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005286 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005287
5288 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5289 switch (setting) {
5290 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005291 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005292 break;
5293 case DisplayColorSetting::UNMANAGED:
5294 reply->writeBool(true);
5295 break;
5296 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005297 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005298 break;
5299 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005300 reply->writeBool(
5301 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005302 break;
5303 }
5304 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005305 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005306 // Is VrFlinger active?
5307 case 1028: {
5308 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005309 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005310 return NO_ERROR;
5311 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005312 // Is device color managed?
5313 case 1030: {
5314 reply->writeBool(useColorManagement);
5315 return NO_ERROR;
5316 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005317 // Override default composition data space
5318 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5319 // && adb shell stop zygote && adb shell start zygote
5320 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5321 // adb shell stop zygote && adb shell start zygote
5322 case 1031: {
5323 Mutex::Autolock _l(mStateLock);
5324 n = data.readInt32();
5325 if (n) {
5326 n = data.readInt32();
5327 if (n) {
5328 Dataspace dataspace = static_cast<Dataspace>(n);
5329 if (!validateCompositionDataspace(dataspace)) {
5330 return BAD_VALUE;
5331 }
5332 mDefaultCompositionDataspace = dataspace;
5333 }
5334 n = data.readInt32();
5335 if (n) {
5336 Dataspace dataspace = static_cast<Dataspace>(n);
5337 if (!validateCompositionDataspace(dataspace)) {
5338 return BAD_VALUE;
5339 }
5340 mWideColorGamutCompositionDataspace = dataspace;
5341 }
5342 } else {
5343 // restore composition data space.
5344 mDefaultCompositionDataspace = defaultCompositionDataspace;
5345 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5346 }
5347 return NO_ERROR;
5348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005349 }
5350 }
5351 return err;
5352}
5353
Steven Thomas6d8110b2017-08-31 18:24:21 -07005354void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005355 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005356 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005357}
5358
Ana Krulec7d1d6832018-12-27 11:10:09 -08005359void SurfaceFlinger::repaintEverythingForHWC() {
5360 mRepaintEverything = true;
5361 mEventQueue->invalidateForHWC();
5362}
5363
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5365class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005366public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005367 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5368 ~WindowDisconnector() {
5369 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005370 }
5371
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372private:
5373 ANativeWindow* mWindow;
5374 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005375};
5376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005377status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005378 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5379 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005380 uint32_t reqWidth, uint32_t reqHeight,
5381 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005382 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005383 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005385 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005386
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005387 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5388
Chia-I Wu20261cb2018-08-23 12:55:44 -07005389 sp<DisplayDevice> display;
5390 {
5391 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005392
Chia-I Wu20261cb2018-08-23 12:55:44 -07005393 display = getDisplayDeviceLocked(displayToken);
5394 if (!display) return BAD_VALUE;
5395
Chia-I Wucb023152018-08-28 12:57:23 -07005396 // set the requested width/height to the logical display viewport size
5397 // by default
5398 if (reqWidth == 0 || reqHeight == 0) {
5399 reqWidth = uint32_t(display->getViewport().width());
5400 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005401 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005402 }
5403
Peiyong Lin0e003c92018-09-17 11:09:51 -07005404 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5405 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005406
5407 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005408 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005409 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5410 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005411}
5412
5413status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5415 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005416 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005417 ATRACE_CALL();
5418
5419 class LayerRenderArea : public RenderArea {
5420 public:
Robert Carr578038f2018-03-09 12:25:24 -08005421 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005422 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5423 bool childrenOnly)
5424 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005425 mLayer(layer),
5426 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005427 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005428 mFlinger(flinger),
5429 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005430 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005431 Rect getBounds() const override {
5432 const Layer::State& layerState(mLayer->getDrawingState());
5433 return mLayer->getBufferSize(layerState);
5434 }
Marissa Wall61c58622018-07-18 10:12:20 -07005435 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005436 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005437 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005438 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005439 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005440 }
chaviwa76b2712017-09-20 12:02:26 -07005441 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005442 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005443 Rect getSourceCrop() const override {
5444 if (mCrop.isEmpty()) {
5445 return getBounds();
5446 } else {
5447 return mCrop;
5448 }
5449 }
Robert Carr578038f2018-03-09 12:25:24 -08005450 class ReparentForDrawing {
5451 public:
5452 const sp<Layer>& oldParent;
5453 const sp<Layer>& newParent;
5454
5455 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5456 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005457 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005458 }
Robert Carr15eae092018-03-23 13:43:53 -07005459 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005460 };
5461
5462 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005463 const Rect sourceCrop = getSourceCrop();
5464 // no need to check rotation because there is none
5465 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5466 sourceCrop.height() != getReqHeight();
5467
Robert Carr578038f2018-03-09 12:25:24 -08005468 if (!mChildrenOnly) {
5469 mTransform = mLayer->getTransform().inverse();
5470 drawLayers();
5471 } else {
5472 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005473 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005474 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5475 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005476
5477 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5478 drawLayers();
5479 }
5480 }
chaviwa76b2712017-09-20 12:02:26 -07005481
chaviwa76b2712017-09-20 12:02:26 -07005482 private:
chaviw7206d492017-11-10 16:16:12 -08005483 const sp<Layer> mLayer;
5484 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005485
5486 // In the "childrenOnly" case we reparent the children to a screenshot
5487 // layer which has no properties set and which does not draw.
5488 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005489 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005490 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005491
5492 SurfaceFlinger* mFlinger;
5493 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005494 };
5495
5496 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5497 auto parent = layerHandle->owner.promote();
5498
Robert Carr2e102c92018-10-23 12:11:15 -07005499 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005500 ALOGE("captureLayers called with a removed parent");
5501 return NAME_NOT_FOUND;
5502 }
5503
Robert Carr578038f2018-03-09 12:25:24 -08005504 const int uid = IPCThreadState::self()->getCallingUid();
5505 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005506 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005507 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5508 return PERMISSION_DENIED;
5509 }
5510
chaviw7206d492017-11-10 16:16:12 -08005511 Rect crop(sourceCrop);
5512 if (sourceCrop.width() <= 0) {
5513 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005514 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005515 }
5516
5517 if (sourceCrop.height() <= 0) {
5518 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005519 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005520 }
5521
5522 int32_t reqWidth = crop.width() * frameScale;
5523 int32_t reqHeight = crop.height() * frameScale;
5524
Chia-I Wu20261cb2018-08-23 12:55:44 -07005525 // really small crop or frameScale
5526 if (reqWidth <= 0) {
5527 reqWidth = 1;
5528 }
5529 if (reqHeight <= 0) {
5530 reqHeight = 1;
5531 }
5532
Peiyong Lin0e003c92018-09-17 11:09:51 -07005533 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005534
Robert Carr578038f2018-03-09 12:25:24 -08005535 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005536 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5537 if (!layer->isVisible()) {
5538 return;
Robert Carr578038f2018-03-09 12:25:24 -08005539 } else if (childrenOnly && layer == parent.get()) {
5540 return;
chaviwa76b2712017-09-20 12:02:26 -07005541 }
5542 visitor(layer);
5543 });
5544 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005545 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005546}
5547
5548status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5549 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005550 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005551 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005552 bool useIdentityTransform) {
5553 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005554
Peiyong Lin0e003c92018-09-17 11:09:51 -07005555 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005556 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5557 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005558 *outBuffer =
5559 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5560 static_cast<android_pixel_format>(reqPixelFormat), 1,
5561 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562
5563 // This mutex protects syncFd and captureResult for communication of the return values from the
5564 // main thread back to this Binder thread
5565 std::mutex captureMutex;
5566 std::condition_variable captureCondition;
5567 std::unique_lock<std::mutex> captureLock(captureMutex);
5568 int syncFd = -1;
5569 std::optional<status_t> captureResult;
5570
Robert Carr03480e22018-01-04 16:02:06 -08005571 const int uid = IPCThreadState::self()->getCallingUid();
5572 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5573
Dominik Laskowski8c001672018-05-30 16:52:06 -07005574 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005575 // If there is a refresh pending, bug out early and tell the binder thread to try again
5576 // after the refresh.
5577 if (mRefreshPending) {
5578 ATRACE_NAME("Skipping screenshot for now");
5579 std::unique_lock<std::mutex> captureLock(captureMutex);
5580 captureResult = std::make_optional<status_t>(EAGAIN);
5581 captureCondition.notify_one();
5582 return;
5583 }
5584
5585 status_t result = NO_ERROR;
5586 int fd = -1;
5587 {
5588 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005589 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005590 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5591 useIdentityTransform, forSystem, &fd);
5592 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 }
5594
5595 {
5596 std::unique_lock<std::mutex> captureLock(captureMutex);
5597 syncFd = fd;
5598 captureResult = std::make_optional<status_t>(result);
5599 captureCondition.notify_one();
5600 }
5601 });
5602
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005603 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005604 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005605 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005606 while (*captureResult == EAGAIN) {
5607 captureResult.reset();
5608 result = postMessageAsync(message);
5609 if (result != NO_ERROR) {
5610 return result;
5611 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005612 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005613 }
5614 result = *captureResult;
5615 }
5616
5617 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005618 sync_wait(syncFd, -1);
5619 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005621
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005622 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005623}
5624
chaviwa76b2712017-09-20 12:02:26 -07005625void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005626 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005627 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5628 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005629 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005630
chaviwa76b2712017-09-20 12:02:26 -07005631 const auto reqWidth = renderArea.getReqWidth();
5632 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005633 const auto sourceCrop = renderArea.getSourceCrop();
5634 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005635
Alec Mouri0f714832018-11-12 15:31:06 -08005636 renderengine::DisplaySettings clientCompositionDisplay;
5637 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005638
Alec Mouri0f714832018-11-12 15:31:06 -08005639 // assume that bounds are never offset, and that they are the same as the
5640 // buffer bounds.
5641 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5642 ui::Transform transform = renderArea.getTransform();
5643 mat4 m;
5644 m[0][0] = transform[0][0];
5645 m[0][1] = transform[0][1];
5646 m[0][3] = transform[0][2];
5647 m[1][0] = transform[1][0];
5648 m[1][1] = transform[1][1];
5649 m[1][3] = transform[1][2];
5650 m[3][0] = transform[2][0];
5651 m[3][1] = transform[2][1];
5652 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005653
Alec Mouri0f714832018-11-12 15:31:06 -08005654 clientCompositionDisplay.globalTransform = m;
5655 mat4 rotMatrix;
5656 // Displacement for repositioning the clipping rectangle after rotating it
5657 // with the rotation hint.
5658 int displacementX = 0;
5659 int displacementY = 0;
5660 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5661 switch (rotation) {
5662 case ui::Transform::ROT_90:
5663 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5664 displacementX = reqWidth;
5665 break;
5666 case ui::Transform::ROT_180:
5667 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5668 displacementX = reqWidth;
5669 displacementY = reqHeight;
5670 break;
5671 case ui::Transform::ROT_270:
5672 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5673 displacementY = reqHeight;
5674 break;
5675 default:
5676 break;
5677 }
5678 // We need to transform the clipping window into the right spot.
5679 // First, rotate the clipping rectangle by the rotation hint to get the
5680 // right orientation
5681 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5682 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5683 const vec4 rotClipTL = rotMatrix * clipTL;
5684 const vec4 rotClipBR = rotMatrix * clipBR;
5685 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5686 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5687 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5688 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5689
5690 // Now reposition the clipping rectangle with the displacement vector
5691 // computed above.
5692 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5693
5694 clientCompositionDisplay.clip =
5695 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5696 newClipRight + displacementX, newClipBottom + displacementY);
5697
5698 // We need to perform the same transformation in layer space, so propagate
5699 // it to the global transform.
5700 mat4 clipTransform = displacementMat * rotMatrix;
5701 clientCompositionDisplay.globalTransform *= clipTransform;
5702 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5703 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005704
chaviw50da5042018-04-09 13:49:37 -07005705 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005706
Alec Mouri0f714832018-11-12 15:31:06 -08005707 renderengine::LayerSettings fillLayer;
5708 fillLayer.source.buffer.buffer = nullptr;
5709 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5710 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5711 fillLayer.alpha = half(alpha);
5712 clientCompositionLayers.push_back(fillLayer);
5713
5714 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005715 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005716 renderengine::LayerSettings layerSettings;
5717 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5718 layerSettings);
5719 if (prepared) {
5720 clientCompositionLayers.push_back(layerSettings);
5721 }
chaviwa76b2712017-09-20 12:02:26 -07005722 });
Alec Mouri0f714832018-11-12 15:31:06 -08005723
5724 clientCompositionDisplay.clearRegion = clearRegion;
5725 base::unique_fd drawFence;
5726 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5727 &drawFence);
5728
5729 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005730}
5731
chaviwa76b2712017-09-20 12:02:26 -07005732status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5733 TraverseLayersFunction traverseLayers,
5734 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005735 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005736 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005737 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005738 ATRACE_CALL();
5739
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005740 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005741
5742 traverseLayers([&](Layer* layer) {
5743 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5744 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005745
Robert Carr03480e22018-01-04 16:02:06 -08005746 // We allow the system server to take screenshots of secure layers for
5747 // use in situations like the Screen-rotation animation and place
5748 // the impetus on WindowManager to not persist them.
5749 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005750 ALOGW("FB is protected: PERMISSION_DENIED");
5751 return PERMISSION_DENIED;
5752 }
Alec Mouri0f714832018-11-12 15:31:06 -08005753 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005754 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005755}
5756
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005757// ---------------------------------------------------------------------------
5758
Dan Stoza412903f2017-04-27 13:42:17 -07005759void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5760 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005761}
5762
Dan Stoza412903f2017-04-27 13:42:17 -07005763void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5764 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005765}
5766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005767void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005768 const LayerVector::Visitor& visitor) {
5769 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005770 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005771 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005772 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005773 continue;
5774 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005775 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005776 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005777 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005778 return;
5779 }
chaviwa76b2712017-09-20 12:02:26 -07005780 if (!layer->isVisible()) {
5781 return;
5782 }
5783 visitor(layer);
5784 });
5785 }
5786}
5787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005788}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005789
Lloyd Pique074e8122018-07-26 12:57:23 -07005790
Mathias Agopian3f844832013-08-07 21:24:32 -07005791#if defined(__gl_h_)
5792#error "don't include gl/gl.h in this file"
5793#endif
5794
5795#if defined(__gl2_h_)
5796#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005797#endif